github.com/shuguocloud/go-zero@v1.3.0/core/conf/config_test.go (about) 1 package conf 2 3 import ( 4 "io/ioutil" 5 "os" 6 "testing" 7 8 "github.com/stretchr/testify/assert" 9 "github.com/shuguocloud/go-zero/core/fs" 10 "github.com/shuguocloud/go-zero/core/hash" 11 ) 12 13 func TestLoadConfig_notExists(t *testing.T) { 14 assert.NotNil(t, LoadConfig("not_a_file", nil)) 15 } 16 17 func TestLoadConfig_notRecogFile(t *testing.T) { 18 filename, err := fs.TempFilenameWithText("hello") 19 assert.Nil(t, err) 20 defer os.Remove(filename) 21 assert.NotNil(t, LoadConfig(filename, nil)) 22 } 23 24 func TestConfigJson(t *testing.T) { 25 tests := []string{ 26 ".json", 27 ".yaml", 28 ".yml", 29 } 30 text := `{ 31 "a": "foo", 32 "b": 1, 33 "c": "${FOO}", 34 "d": "abcd!@#$112" 35 }` 36 for _, test := range tests { 37 test := test 38 t.Run(test, func(t *testing.T) { 39 os.Setenv("FOO", "2") 40 defer os.Unsetenv("FOO") 41 tmpfile, err := createTempFile(test, text) 42 assert.Nil(t, err) 43 defer os.Remove(tmpfile) 44 45 var val struct { 46 A string `json:"a"` 47 B int `json:"b"` 48 C string `json:"c"` 49 D string `json:"d"` 50 } 51 MustLoad(tmpfile, &val) 52 assert.Equal(t, "foo", val.A) 53 assert.Equal(t, 1, val.B) 54 assert.Equal(t, "${FOO}", val.C) 55 assert.Equal(t, "abcd!@#$112", val.D) 56 }) 57 } 58 } 59 60 func TestConfigJsonEnv(t *testing.T) { 61 tests := []string{ 62 ".json", 63 ".yaml", 64 ".yml", 65 } 66 text := `{ 67 "a": "foo", 68 "b": 1, 69 "c": "${FOO}", 70 "d": "abcd!@#$a12 3" 71 }` 72 for _, test := range tests { 73 test := test 74 t.Run(test, func(t *testing.T) { 75 os.Setenv("FOO", "2") 76 defer os.Unsetenv("FOO") 77 tmpfile, err := createTempFile(test, text) 78 assert.Nil(t, err) 79 defer os.Remove(tmpfile) 80 81 var val struct { 82 A string `json:"a"` 83 B int `json:"b"` 84 C string `json:"c"` 85 D string `json:"d"` 86 } 87 MustLoad(tmpfile, &val, UseEnv()) 88 assert.Equal(t, "foo", val.A) 89 assert.Equal(t, 1, val.B) 90 assert.Equal(t, "2", val.C) 91 assert.Equal(t, "abcd!@# 3", val.D) 92 }) 93 } 94 } 95 96 func createTempFile(ext, text string) (string, error) { 97 tmpfile, err := ioutil.TempFile(os.TempDir(), hash.Md5Hex([]byte(text))+"*"+ext) 98 if err != nil { 99 return "", err 100 } 101 102 if err := ioutil.WriteFile(tmpfile.Name(), []byte(text), os.ModeTemporary); err != nil { 103 return "", err 104 } 105 106 filename := tmpfile.Name() 107 if err = tmpfile.Close(); err != nil { 108 return "", err 109 } 110 111 return filename, nil 112 }