map_test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package paladin_test
  2. import (
  3. "testing"
  4. "go-common/library/conf/paladin"
  5. "github.com/naoina/toml"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. type fruit struct {
  9. Fruit []struct {
  10. Name string
  11. }
  12. }
  13. func (f *fruit) Set(text string) error {
  14. return toml.Unmarshal([]byte(text), f)
  15. }
  16. func TestMap(t *testing.T) {
  17. s := `
  18. # kv
  19. text = "hello"
  20. number = 100
  21. point = 100.1
  22. boolean = true
  23. KeyCase = "test"
  24. # slice
  25. numbers = [1, 2, 3]
  26. strings = ["a", "b", "c"]
  27. empty = []
  28. [[fruit]]
  29. name = "apple"
  30. [[fruit]]
  31. name = "banana"
  32. # table
  33. [database]
  34. server = "192.168.1.1"
  35. connection_max = 5000
  36. enabled = true
  37. [pool]
  38. [pool.breaker]
  39. xxx = "xxx"
  40. `
  41. m := paladin.Map{}
  42. assert.Nil(t, m.Set(s), s)
  43. str, err := m.Get("text").String()
  44. assert.Nil(t, err)
  45. assert.Equal(t, str, "hello", "text")
  46. n, err := m.Get("number").Int64()
  47. assert.Nil(t, err)
  48. assert.Equal(t, n, int64(100), "number")
  49. p, err := m.Get("point").Float64()
  50. assert.Nil(t, err)
  51. assert.Equal(t, p, 100.1, "point")
  52. b, err := m.Get("boolean").Bool()
  53. assert.Nil(t, err)
  54. assert.Equal(t, b, true, "boolean")
  55. // key lower case
  56. lb, err := m.Get("Boolean").Bool()
  57. assert.Nil(t, err)
  58. assert.Equal(t, lb, true, "boolean")
  59. lt, err := m.Get("KeyCase").String()
  60. assert.Nil(t, err)
  61. assert.Equal(t, lt, "test", "key case")
  62. var sliceInt []int64
  63. err = m.Get("numbers").Slice(&sliceInt)
  64. assert.Nil(t, err)
  65. assert.Equal(t, sliceInt, []int64{1, 2, 3})
  66. var sliceStr []string
  67. err = m.Get("strings").Slice(&sliceStr)
  68. assert.Nil(t, err)
  69. assert.Equal(t, sliceStr, []string{"a", "b", "c"})
  70. err = m.Get("strings").Slice(&sliceStr)
  71. assert.Nil(t, err)
  72. assert.Equal(t, sliceStr, []string{"a", "b", "c"})
  73. // errors
  74. err = m.Get("strings").Slice(sliceInt)
  75. assert.NotNil(t, err)
  76. err = m.Get("strings").Slice(&sliceInt)
  77. assert.NotNil(t, err)
  78. var obj struct {
  79. Name string
  80. }
  81. err = m.Get("strings").Slice(obj)
  82. assert.NotNil(t, err)
  83. err = m.Get("strings").Slice(&obj)
  84. assert.NotNil(t, err)
  85. }