config_test.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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/hash"
  8. )
  9. func TestConfigJson(t *testing.T) {
  10. tests := []string{
  11. ".json",
  12. ".yaml",
  13. ".yml",
  14. }
  15. text := `{
  16. "a": "foo",
  17. "b": 1
  18. }`
  19. for _, test := range tests {
  20. test := test
  21. t.Run(test, func(t *testing.T) {
  22. t.Parallel()
  23. tmpfile, err := createTempFile(test, text)
  24. assert.Nil(t, err)
  25. defer os.Remove(tmpfile)
  26. var val struct {
  27. A string `json:"a"`
  28. B int `json:"b"`
  29. }
  30. err = LoadConfig(tmpfile, &val)
  31. assert.Nil(t, err)
  32. assert.Equal(t, "foo", val.A)
  33. assert.Equal(t, 1, val.B)
  34. })
  35. }
  36. }
  37. func createTempFile(ext, text string) (string, error) {
  38. tmpfile, err := ioutil.TempFile(os.TempDir(), hash.Md5Hex([]byte(text))+"*"+ext)
  39. if err != nil {
  40. return "", err
  41. }
  42. if err := ioutil.WriteFile(tmpfile.Name(), []byte(text), os.ModeTemporary); err != nil {
  43. return "", err
  44. }
  45. filename := tmpfile.Name()
  46. if err = tmpfile.Close(); err != nil {
  47. return "", err
  48. }
  49. return filename, nil
  50. }