field_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package dynamodbattribute
  2. import (
  3. "reflect"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. type testUnionValues struct {
  8. Name string
  9. Value interface{}
  10. }
  11. type unionSimple struct {
  12. A int
  13. B string
  14. C []string
  15. }
  16. type unionComplex struct {
  17. unionSimple
  18. A int
  19. }
  20. type unionTagged struct {
  21. A int `json:"A"`
  22. }
  23. type unionTaggedComplex struct {
  24. unionSimple
  25. unionTagged
  26. B string
  27. }
  28. func TestUnionStructFields(t *testing.T) {
  29. var cases = []struct {
  30. in interface{}
  31. expect []testUnionValues
  32. }{
  33. {
  34. in: unionSimple{1, "2", []string{"abc"}},
  35. expect: []testUnionValues{
  36. {"A", 1},
  37. {"B", "2"},
  38. {"C", []string{"abc"}},
  39. },
  40. },
  41. {
  42. in: unionComplex{
  43. unionSimple: unionSimple{1, "2", []string{"abc"}},
  44. A: 2,
  45. },
  46. expect: []testUnionValues{
  47. {"B", "2"},
  48. {"C", []string{"abc"}},
  49. {"A", 2},
  50. },
  51. },
  52. {
  53. in: unionTaggedComplex{
  54. unionSimple: unionSimple{1, "2", []string{"abc"}},
  55. unionTagged: unionTagged{3},
  56. B: "3",
  57. },
  58. expect: []testUnionValues{
  59. {"C", []string{"abc"}},
  60. {"A", 3},
  61. {"B", "3"},
  62. },
  63. },
  64. }
  65. for i, c := range cases {
  66. v := reflect.ValueOf(c.in)
  67. fields := unionStructFields(v.Type(), MarshalOptions{SupportJSONTags: true})
  68. for j, f := range fields {
  69. expected := c.expect[j]
  70. assert.Equal(t, expected.Name, f.Name, "case %d, field %d", i, j)
  71. actual := v.FieldByIndex(f.Index).Interface()
  72. assert.EqualValues(t, expected.Value, actual, "case %d, field %d", i, j)
  73. }
  74. }
  75. }
  76. func TestFieldByName(t *testing.T) {
  77. fields := []field{
  78. {Name: "Abc"}, {Name: "mixCase"}, {Name: "UPPERCASE"},
  79. }
  80. cases := []struct {
  81. Name, FieldName string
  82. Found bool
  83. }{
  84. {"abc", "Abc", true}, {"ABC", "Abc", true}, {"Abc", "Abc", true},
  85. {"123", "", false},
  86. {"ab", "", false},
  87. {"MixCase", "mixCase", true},
  88. {"uppercase", "UPPERCASE", true}, {"UPPERCASE", "UPPERCASE", true},
  89. }
  90. for _, c := range cases {
  91. f, ok := fieldByName(fields, c.Name)
  92. assert.Equal(t, c.Found, ok)
  93. if ok {
  94. assert.Equal(t, c.FieldName, f.Name)
  95. }
  96. }
  97. }