config_test.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package conf
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. "github.com/tal-tech/go-zero/core/fs"
  8. "github.com/tal-tech/go-zero/core/hash"
  9. )
  10. func TestLoadConfig_notExists(t *testing.T) {
  11. assert.NotNil(t, LoadConfig("not_a_file", nil))
  12. }
  13. func TestLoadConfig_notRecogFile(t *testing.T) {
  14. filename, err := fs.TempFilenameWithText("hello")
  15. assert.Nil(t, err)
  16. defer os.Remove(filename)
  17. assert.NotNil(t, LoadConfig(filename, nil))
  18. }
  19. func TestConfigJson(t *testing.T) {
  20. tests := []string{
  21. ".json",
  22. ".yaml",
  23. ".yml",
  24. }
  25. text := `{
  26. "a": "foo",
  27. "b": 1,
  28. "c": "${FOO}"
  29. }`
  30. for _, test := range tests {
  31. test := test
  32. t.Run(test, func(t *testing.T) {
  33. os.Setenv("FOO", "2")
  34. defer os.Unsetenv("FOO")
  35. tmpfile, err := createTempFile(test, text)
  36. assert.Nil(t, err)
  37. defer os.Remove(tmpfile)
  38. var val struct {
  39. A string `json:"a"`
  40. B int `json:"b"`
  41. C string `json:"c"`
  42. }
  43. MustLoad(tmpfile, &val)
  44. assert.Equal(t, "foo", val.A)
  45. assert.Equal(t, 1, val.B)
  46. assert.Equal(t, "2", val.C)
  47. })
  48. }
  49. }
  50. func createTempFile(ext, text string) (string, error) {
  51. tmpfile, err := ioutil.TempFile(os.TempDir(), hash.Md5Hex([]byte(text))+"*"+ext)
  52. if err != nil {
  53. return "", err
  54. }
  55. if err := ioutil.WriteFile(tmpfile.Name(), []byte(text), os.ModeTemporary); err != nil {
  56. return "", err
  57. }
  58. filename := tmpfile.Name()
  59. if err = tmpfile.Close(); err != nil {
  60. return "", err
  61. }
  62. return filename, nil
  63. }