go-zero/core/conf/config_test.go

63 lines
1.1 KiB
Go
Raw Normal View History

package conf
import (
"io/ioutil"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/tal-tech/go-zero/core/hash"
)
func TestConfigJson(t *testing.T) {
tests := []string{
".json",
".yaml",
".yml",
}
text := `{
"a": "foo",
2020-12-25 11:42:19 +08:00
"b": 1,
"c": "${FOO}"
}`
for _, test := range tests {
test := test
t.Run(test, func(t *testing.T) {
t.Parallel()
2020-12-25 11:42:19 +08:00
os.Setenv("FOO", "2")
defer os.Unsetenv("FOO")
tmpfile, err := createTempFile(test, text)
assert.Nil(t, err)
defer os.Remove(tmpfile)
var val struct {
A string `json:"a"`
B int `json:"b"`
2020-12-25 11:42:19 +08:00
C string `json:"c"`
}
2020-09-30 17:47:56 +08:00
MustLoad(tmpfile, &val)
assert.Equal(t, "foo", val.A)
assert.Equal(t, 1, val.B)
2020-12-25 11:42:19 +08:00
assert.Equal(t, "2", val.C)
})
}
}
func createTempFile(ext, text string) (string, error) {
tmpfile, err := ioutil.TempFile(os.TempDir(), hash.Md5Hex([]byte(text))+"*"+ext)
if err != nil {
return "", err
}
if err := ioutil.WriteFile(tmpfile.Name(), []byte(text), os.ModeTemporary); err != nil {
return "", err
}
filename := tmpfile.Name()
if err = tmpfile.Close(); err != nil {
return "", err
}
return filename, nil
}