github.com/aavshr/aws-sdk-go@v1.41.3/service/dynamodb/dynamodbattribute/field_test.go (about) 1 package dynamodbattribute 2 3 import ( 4 "reflect" 5 "testing" 6 ) 7 8 type testUnionValues struct { 9 Name string 10 Value interface{} 11 } 12 13 type unionSimple struct { 14 A int 15 B string 16 C []string 17 } 18 19 type unionComplex struct { 20 unionSimple 21 A int 22 } 23 24 type unionTagged struct { 25 A int `json:"A"` 26 } 27 28 type unionTaggedComplex struct { 29 unionSimple 30 unionTagged 31 B string 32 } 33 34 func TestUnionStructFields(t *testing.T) { 35 var cases = []struct { 36 in interface{} 37 expect []testUnionValues 38 }{ 39 { 40 in: unionSimple{1, "2", []string{"abc"}}, 41 expect: []testUnionValues{ 42 {"A", 1}, 43 {"B", "2"}, 44 {"C", []string{"abc"}}, 45 }, 46 }, 47 { 48 in: unionComplex{ 49 unionSimple: unionSimple{1, "2", []string{"abc"}}, 50 A: 2, 51 }, 52 expect: []testUnionValues{ 53 {"B", "2"}, 54 {"C", []string{"abc"}}, 55 {"A", 2}, 56 }, 57 }, 58 { 59 in: unionTaggedComplex{ 60 unionSimple: unionSimple{1, "2", []string{"abc"}}, 61 unionTagged: unionTagged{3}, 62 B: "3", 63 }, 64 expect: []testUnionValues{ 65 {"C", []string{"abc"}}, 66 {"A", 3}, 67 {"B", "3"}, 68 }, 69 }, 70 } 71 72 for i, c := range cases { 73 v := reflect.ValueOf(c.in) 74 75 fields := unionStructFields(v.Type(), MarshalOptions{SupportJSONTags: true}) 76 for j, f := range fields.All() { 77 expected := c.expect[j] 78 if e, a := expected.Name, f.Name; e != a { 79 t.Errorf("%d:%d expect %v, got %v", i, j, e, f) 80 } 81 actual := v.FieldByIndex(f.Index).Interface() 82 if e, a := expected.Value, actual; !reflect.DeepEqual(e, a) { 83 t.Errorf("%d:%d expect %v, got %v", i, j, e, f) 84 } 85 } 86 } 87 } 88 89 func TestCachedFields(t *testing.T) { 90 type myStruct struct { 91 Dog int 92 CAT string 93 bird bool 94 } 95 96 fields := unionStructFields(reflect.TypeOf(myStruct{}), MarshalOptions{}) 97 98 const expectedNumFields = 2 99 if numFields := len(fields.All()); numFields != expectedNumFields { 100 t.Errorf("expected number of fields to be %d but got %d", expectedNumFields, numFields) 101 } 102 103 cases := []struct { 104 Name string 105 FieldName string 106 Found bool 107 }{ 108 {"Dog", "Dog", true}, 109 {"dog", "Dog", true}, 110 {"DOG", "Dog", true}, 111 {"Yorkie", "", false}, 112 {"Cat", "CAT", true}, 113 {"cat", "CAT", true}, 114 {"CAT", "CAT", true}, 115 {"tiger", "", false}, 116 {"bird", "", false}, 117 } 118 119 for _, c := range cases { 120 f, found := fields.FieldByName(c.Name) 121 if found != c.Found { 122 t.Errorf("expected found to be %v but got %v", c.Found, found) 123 } 124 if found && f.Name != c.FieldName { 125 t.Errorf("expected field name to be %s but got %s", c.FieldName, f.Name) 126 } 127 } 128 }