properties_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package conf
  2. import (
  3. "os"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. "github.com/tal-tech/go-zero/core/fs"
  7. )
  8. func TestProperties(t *testing.T) {
  9. text := `app.name = test
  10. app.program=app
  11. # this is comment
  12. app.threads = 5`
  13. tmpfile, err := fs.TempFilenameWithText(text)
  14. assert.Nil(t, err)
  15. defer os.Remove(tmpfile)
  16. props, err := LoadProperties(tmpfile)
  17. assert.Nil(t, err)
  18. assert.Equal(t, "test", props.GetString("app.name"))
  19. assert.Equal(t, "app", props.GetString("app.program"))
  20. assert.Equal(t, 5, props.GetInt("app.threads"))
  21. val := props.ToString()
  22. assert.Contains(t, val, "app.name")
  23. assert.Contains(t, val, "app.program")
  24. assert.Contains(t, val, "app.threads")
  25. }
  26. func TestPropertiesEnv(t *testing.T) {
  27. text := `app.name = test
  28. app.program=app
  29. app.env1 = ${FOO}
  30. app.env2 = $none
  31. # this is comment
  32. app.threads = 5`
  33. tmpfile, err := fs.TempFilenameWithText(text)
  34. assert.Nil(t, err)
  35. defer os.Remove(tmpfile)
  36. os.Setenv("FOO", "2")
  37. defer os.Unsetenv("FOO")
  38. props, err := LoadProperties(tmpfile, UseEnv())
  39. assert.Nil(t, err)
  40. assert.Equal(t, "test", props.GetString("app.name"))
  41. assert.Equal(t, "app", props.GetString("app.program"))
  42. assert.Equal(t, 5, props.GetInt("app.threads"))
  43. assert.Equal(t, "2", props.GetString("app.env1"))
  44. assert.Equal(t, "", props.GetString("app.env2"))
  45. val := props.ToString()
  46. assert.Contains(t, val, "app.name")
  47. assert.Contains(t, val, "app.program")
  48. assert.Contains(t, val, "app.threads")
  49. assert.Contains(t, val, "app.env1")
  50. assert.Contains(t, val, "app.env2")
  51. }
  52. func TestLoadProperties_badContent(t *testing.T) {
  53. filename, err := fs.TempFilenameWithText("hello")
  54. assert.Nil(t, err)
  55. defer os.Remove(filename)
  56. _, err = LoadProperties(filename)
  57. assert.NotNil(t, err)
  58. assert.True(t, len(err.Error()) > 0)
  59. }
  60. func TestSetString(t *testing.T) {
  61. key := "a"
  62. value := "the value of a"
  63. props := NewProperties()
  64. props.SetString(key, value)
  65. assert.Equal(t, value, props.GetString(key))
  66. }
  67. func TestSetInt(t *testing.T) {
  68. key := "a"
  69. value := 101
  70. props := NewProperties()
  71. props.SetInt(key, value)
  72. assert.Equal(t, value, props.GetInt(key))
  73. }
  74. func TestLoadBadFile(t *testing.T) {
  75. _, err := LoadProperties("nosuchfile")
  76. assert.NotNil(t, err)
  77. }