1// Copyright 2019 Google Inc. All rights reserved. 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15package proptools 16 17import ( 18 "reflect" 19 "testing" 20) 21 22func TestHasTag(t *testing.T) { 23 type testType struct { 24 NoTag string 25 EmptyTag string `` 26 OtherTag string `foo:"bar"` 27 MatchingTag string `name:"value"` 28 ExtraValues string `name:"foo,value,bar"` 29 ExtraTags string `foo:"bar" name:"value"` 30 } 31 32 tests := []struct { 33 field string 34 want bool 35 }{ 36 { 37 field: "NoTag", 38 want: false, 39 }, 40 { 41 field: "EmptyTag", 42 want: false, 43 }, 44 { 45 field: "OtherTag", 46 want: false, 47 }, 48 { 49 field: "MatchingTag", 50 want: true, 51 }, 52 { 53 field: "ExtraValues", 54 want: true, 55 }, 56 { 57 field: "ExtraTags", 58 want: true, 59 }, 60 } 61 for _, test := range tests { 62 t.Run(test.field, func(t *testing.T) { 63 field, _ := reflect.TypeOf(testType{}).FieldByName(test.field) 64 if got := HasTag(field, "name", "value"); got != test.want { 65 t.Errorf(`HasTag(%q, "name", "value") = %v, want %v`, field.Tag, got, test.want) 66 } 67 }) 68 } 69} 70 71func TestPropertyIndexesWithTag(t *testing.T) { 72 tests := []struct { 73 name string 74 ps interface{} 75 want [][]int 76 }{ 77 { 78 name: "none", 79 ps: &struct { 80 Foo string 81 }{}, 82 want: nil, 83 }, 84 { 85 name: "one", 86 ps: &struct { 87 Foo string `name:"value"` 88 }{}, 89 want: [][]int{{0}}, 90 }, 91 { 92 name: "two", 93 ps: &struct { 94 Foo string `name:"value"` 95 Bar string `name:"value"` 96 }{}, 97 want: [][]int{{0}, {1}}, 98 }, 99 { 100 name: "some", 101 ps: &struct { 102 Foo string `name:"other"` 103 Bar string `name:"value"` 104 }{}, 105 want: [][]int{{1}}, 106 }, 107 { 108 name: "embedded", 109 ps: &struct { 110 Foo struct { 111 Bar string `name:"value"` 112 } 113 }{}, 114 want: [][]int{{0, 0}}, 115 }, 116 { 117 name: "embedded ptr", 118 ps: &struct { 119 Foo *struct { 120 Bar string `name:"value"` 121 } 122 }{}, 123 want: [][]int{{0, 0}}, 124 }, 125 { 126 name: "nil", 127 ps: (*struct { 128 Foo string `name:"value"` 129 })(nil), 130 want: [][]int{{0}}, 131 }, 132 } 133 for _, test := range tests { 134 t.Run(test.name, func(t *testing.T) { 135 if got := PropertyIndexesWithTag(test.ps, "name", "value"); !reflect.DeepEqual(got, test.want) { 136 t.Errorf("PropertyIndexesWithTag() = %v, want %v", got, test.want) 137 } 138 }) 139 } 140} 141