config_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. "d": "abcd!@#$112"
  30. }`
  31. for _, test := range tests {
  32. test := test
  33. t.Run(test, func(t *testing.T) {
  34. os.Setenv("FOO", "2")
  35. defer os.Unsetenv("FOO")
  36. tmpfile, err := createTempFile(test, text)
  37. assert.Nil(t, err)
  38. defer os.Remove(tmpfile)
  39. var val struct {
  40. A string `json:"a"`
  41. B int `json:"b"`
  42. C string `json:"c"`
  43. D string `json:"d"`
  44. }
  45. MustLoad(tmpfile, &val)
  46. assert.Equal(t, "foo", val.A)
  47. assert.Equal(t, 1, val.B)
  48. assert.Equal(t, "${FOO}", val.C)
  49. assert.Equal(t, "abcd!@#$112", val.D)
  50. })
  51. }
  52. }
  53. func TestConfigJsonEnv(t *testing.T) {
  54. tests := []string{
  55. ".json",
  56. ".yaml",
  57. ".yml",
  58. }
  59. text := `{
  60. "a": "foo",
  61. "b": 1,
  62. "c": "${FOO}",
  63. "d": "abcd!@#$a12 3"
  64. }`
  65. for _, test := range tests {
  66. test := test
  67. t.Run(test, func(t *testing.T) {
  68. os.Setenv("FOO", "2")
  69. defer os.Unsetenv("FOO")
  70. tmpfile, err := createTempFile(test, text)
  71. assert.Nil(t, err)
  72. defer os.Remove(tmpfile)
  73. var val struct {
  74. A string `json:"a"`
  75. B int `json:"b"`
  76. C string `json:"c"`
  77. D string `json:"d"`
  78. }
  79. MustLoad(tmpfile, &val, UseEnv())
  80. assert.Equal(t, "foo", val.A)
  81. assert.Equal(t, 1, val.B)
  82. assert.Equal(t, "2", val.C)
  83. assert.Equal(t, "abcd!@# 3", val.D)
  84. })
  85. }
  86. }
  87. func createTempFile(ext, text string) (string, error) {
  88. tmpfile, err := ioutil.TempFile(os.TempDir(), hash.Md5Hex([]byte(text))+"*"+ext)
  89. if err != nil {
  90. return "", err
  91. }
  92. if err := ioutil.WriteFile(tmpfile.Name(), []byte(text), os.ModeTemporary); err != nil {
  93. return "", err
  94. }
  95. filename := tmpfile.Name()
  96. if err = tmpfile.Close(); err != nil {
  97. return "", err
  98. }
  99. return filename, nil
  100. }