config_test.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. MustLoad(tmpfile, &val)
  31. assert.Equal(t, "foo", val.A)
  32. assert.Equal(t, 1, val.B)
  33. })
  34. }
  35. }
  36. func createTempFile(ext, text string) (string, error) {
  37. tmpfile, err := ioutil.TempFile(os.TempDir(), hash.Md5Hex([]byte(text))+"*"+ext)
  38. if err != nil {
  39. return "", err
  40. }
  41. if err := ioutil.WriteFile(tmpfile.Name(), []byte(text), os.ModeTemporary); err != nil {
  42. return "", err
  43. }
  44. filename := tmpfile.Name()
  45. if err = tmpfile.Close(); err != nil {
  46. return "", err
  47. }
  48. return filename, nil
  49. }