From fb16a6b8d52881f46d9e7ca3c01cf3abc238436f Mon Sep 17 00:00:00 2001 From: Vlad Didenko Date: Wed, 27 May 2015 15:30:04 -0500 Subject: [PATCH] spf13/viper#73 Tests to document current behavior and expose the bug --- viper_test.go | 99 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) diff --git a/viper_test.go b/viper_test.go index 7ad0245..d513e25 100644 --- a/viper_test.go +++ b/viper_test.go @@ -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`)) +}