spf13/viper#73 Tests to document current behavior and expose the bug

This commit is contained in:
Vlad Didenko 2015-05-27 15:30:04 -05:00
parent d62d4bb4c6
commit fb16a6b8d5

View file

@ -8,7 +8,9 @@ package viper
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path"
"sort"
"strings"
"testing"
@ -124,6 +126,47 @@ func initTOML() {
marshalReader(r, v.config)
}
// make directories for testing
func initDirs(t *testing.T) (string, string, func()) {
var (
testDirs = []string{`a a`, `b`, `c\c`, `D:`}
config = `improbable`
)
root, err := ioutil.TempDir("", "")
cleanup := true
defer func() {
if cleanup {
os.Chdir("..")
os.RemoveAll(root)
}
}()
assert.Nil(t, err)
err = os.Chdir(root)
assert.Nil(t, err)
err = ioutil.WriteFile(path.Join(root, config+".toml"), []byte("key = \"root\"\n"), 0640)
assert.Nil(t, err)
for _, dir := range testDirs {
err = os.Mkdir(dir, 0750)
assert.Nil(t, err)
err = ioutil.WriteFile(path.Join(dir, config+".toml"), []byte("key = \"value is "+dir+"\"\n"), 0640)
assert.Nil(t, err)
}
cleanup = false
return root, config, func() {
os.Chdir("..")
os.RemoveAll(root)
}
}
//stubs for PFlag Values
type stringValue string
@ -551,3 +594,59 @@ func TestReadBufConfig(t *testing.T) {
assert.Equal(t, map[interface{}]interface{}{"jacket": "leather", "trousers": "denim"}, v.Get("clothing"))
assert.Equal(t, 35, v.Get("age"))
}
func TestCWDSearch(t *testing.T) {
_, config, cleanup := initDirs(t)
defer cleanup()
v := New()
v.SetConfigName(config)
v.SetDefault(`key`, `default`)
err := v.ReadInConfig()
assert.Nil(t, err)
assert.Equal(t, `root`, v.GetString(`key`))
}
func TestDirsSearch(t *testing.T) {
root, config, cleanup := initDirs(t)
defer cleanup()
v := New()
v.SetConfigName(config)
v.SetDefault(`key`, `default`)
entries, err := ioutil.ReadDir(root)
for _, e := range entries {
if e.IsDir() {
v.AddConfigPath(e.Name())
}
}
err = v.ReadInConfig()
assert.Nil(t, err)
assert.Equal(t, `value is `+path.Base(v.configPaths[0]), v.GetString(`key`))
}
func TestWrongDirsSearchNotFoundOK(t *testing.T) {
_, config, cleanup := initDirs(t)
defer cleanup()
v := New()
v.SetConfigName(config)
v.SetDefault(`key`, `default`)
v.AddConfigPath(`whattayoutalkingbout`)
v.AddConfigPath(`thispathaintthere`)
err := v.ReadInConfig()
assert.Nil(t, err)
// Should not see the value "root" which comes from config in CWD
assert.Equal(t, `default`, v.GetString(`key`))
}