Added config file creation and opening tests

This commit is contained in:
cpb8010 2013-07-16 23:37:03 -04:00
parent 4d4a979864
commit 8f7a1c08e2
2 changed files with 52 additions and 5 deletions

View file

@ -68,7 +68,7 @@ func Open(path string) (*Config, error) {
} }
defer f.Close() defer f.Close()
conf, err := New(f) conf, err := newConfig(f)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -76,7 +76,7 @@ func Open(path string) (*Config, error) {
} }
// New decodes JSON from a Reader into a Config. // New decodes JSON from a Reader into a Config.
func New(raw io.Reader) (*Config, error) { func newConfig(raw io.Reader) (*Config, error) {
conf := &Config{} conf := &Config{}
err := json.NewDecoder(raw).Decode(conf) err := json.NewDecoder(raw).Decode(conf)
if err != nil { if err != nil {

View file

@ -5,11 +5,13 @@
package config package config
import ( import (
"bufio"
"os"
"strings" "strings"
"testing" "testing"
) )
var exampleConfig = `{ var exampleJson = `{
"network": "tcp", "network": "tcp",
"addr": ":34000", "addr": ":34000",
@ -35,8 +37,53 @@ var exampleConfig = `{
}` }`
func TestNew(t *testing.T) { func TestNewConfig(t *testing.T) {
if _, err := New(strings.NewReader(exampleConfig)); err != nil { if _, err := newConfig(strings.NewReader(exampleJson)); err != nil {
t.Error(err) t.Error(err)
} }
} }
func writeAndOpenJsonTest(t *testing.T, fn string) {
expandFn := os.ExpandEnv(fn)
//write json to relative path, clean up
tfile, ferr := os.Create(expandFn)
//Remove failure not counted as error
defer os.Remove(expandFn)
if ferr != nil {
t.Fatal("Failed to create %s. Error: %v", expandFn, ferr)
}
tWriter := bufio.NewWriter(tfile)
cw, err := tWriter.WriteString(exampleJson)
if err != nil {
t.Fatal("Failed to write json to config file. %v", err)
}
if cw < len(exampleJson) {
t.Error("Incorrect length of config file written %v vs. %v", cw, len(exampleJson))
}
fErr := tWriter.Flush()
if fErr != nil {
t.Error("Flush error: %v", fErr)
}
_, oErr := Open(fn)
if oErr != nil {
t.Error("Open error: %v", oErr)
}
}
//These implcitly require the test program have
// read/write/delete file system permissions
func TestOpenCurDir(t *testing.T) {
if !testing.Short() {
writeAndOpenJsonTest(t, "testConfig.json")
} else {
t.Log("Write/Read file test skipped")
}
}
func TestOpenAbsEnvPath(t *testing.T) {
if !testing.Short() {
writeAndOpenJsonTest(t, "$GOROOT/testConfig.json")
} else {
t.Log("Write/Read file test skipped")
}
}