forked from go-ozzo/ozzo-validation
-
Notifications
You must be signed in to change notification settings - Fork 6
/
struct_test.go
352 lines (327 loc) · 11.9 KB
/
struct_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// Copyright 2016 Qiang Xue. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package validation
import (
"context"
"fmt"
"reflect"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
type Struct1 struct {
Field1 int
Field2 *int
Field3 []int
Field4 [4]int
field5 int
Struct2
S1 *Struct2
S2 Struct2
JSONField int `json:"some_json_field"`
JSONIgnoredField int `json:"-"`
ProtobufField string `protobuf:"bytes,1,opt,name=some_protobuf_field,json=someProtobufField,proto3" json:"some_protobuf_field,omitempty"`
}
type Struct2 struct {
Field21 string
Field22 string
}
type Struct3 struct {
*Struct2
S1 string
}
func TestFindStructField(t *testing.T) {
var s1 Struct1
v1 := reflect.ValueOf(&s1).Elem()
assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.Field1)))
assert.Nil(t, findStructField(v1, reflect.ValueOf(s1.Field2)))
assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.Field2)))
assert.Nil(t, findStructField(v1, reflect.ValueOf(s1.Field3)))
assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.Field3)))
assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.Field4)))
assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.field5)))
assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.Struct2)))
assert.Nil(t, findStructField(v1, reflect.ValueOf(s1.S1)))
assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.S1)))
assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.Field21)))
assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.Field22)))
assert.NotNil(t, findStructField(v1, reflect.ValueOf(&s1.Struct2.Field22)))
s2 := reflect.ValueOf(&s1.Struct2).Elem()
assert.NotNil(t, findStructField(s2, reflect.ValueOf(&s1.Field21)))
assert.NotNil(t, findStructField(s2, reflect.ValueOf(&s1.Struct2.Field21)))
assert.NotNil(t, findStructField(s2, reflect.ValueOf(&s1.Struct2.Field22)))
s3 := Struct3{
Struct2: &Struct2{},
}
v3 := reflect.ValueOf(&s3).Elem()
assert.NotNil(t, findStructField(v3, reflect.ValueOf(&s3.Struct2)))
assert.NotNil(t, findStructField(v3, reflect.ValueOf(&s3.Field21)))
}
func TestValidateStruct(t *testing.T) {
var m0 *Model1
m1 := Model1{A: "abc", B: "xyz", c: "abc", G: "xyz", H: []string{"abc", "abc"}, I: map[string]string{"foo": "abc"}}
m2 := Model1{E: String123("xyz")}
m3 := Model2{}
m4 := Model2{M3: Model3{A: "abc"}, Model3: Model3{A: "abc"}}
m5 := Model2{Model3: Model3{A: "internal"}}
m6 := struct {
A int
B struct {
C struct {
D string
}
}
}{}
tests := []struct {
tag string
model interface{}
rules []*FieldRules
err string
}{
// empty rules
{"t1.1", &m1, []*FieldRules{}, ""},
{"t1.2", &m1, []*FieldRules{Field(&m1.A), Field(&m1.B)}, ""},
// normal rules
{"t2.1", &m1, []*FieldRules{Field(&m1.A, &validateAbc{}), Field(&m1.B, &validateXyz{})}, ""},
{"t2.2", &m1, []*FieldRules{Field(&m1.A, &validateXyz{}), Field(&m1.B, &validateAbc{})}, "A: error xyz; B: error abc."},
{"t2.3", &m1, []*FieldRules{Field(&m1.A, &validateXyz{}), Field(&m1.c, &validateXyz{})}, "A: error xyz; c: error xyz."},
{"t2.4", &m1, []*FieldRules{Field(&m1.D, Length(0, 5))}, ""},
{"t2.5", &m1, []*FieldRules{Field(&m1.F, Length(0, 5))}, ""},
{"t2.6", &m1, []*FieldRules{Field(&m1.H, Each(&validateAbc{})), Field(&m1.I, Each(&validateAbc{}))}, ""},
{"t2.7", &m1, []*FieldRules{Field(&m1.H, Each(&validateXyz{})), Field(&m1.I, Each(&validateXyz{}))}, "H: (0: error xyz; 1: error xyz.); I: (foo: error xyz.)."},
{"t2.8", &m6, []*FieldRules{FieldStruct(&m6.B, FieldStruct(&m6.B.C, Field(&m6.B.C.D, Required)))}, "B: (C: (D: cannot be blank.).)."},
// non-struct pointer
{"t3.1", m1, []*FieldRules{}, ErrStructPointer.Error()},
{"t3.2", nil, []*FieldRules{}, ErrStructPointer.Error()},
{"t3.3", m0, []*FieldRules{}, ""},
{"t3.4", &m0, []*FieldRules{}, ErrStructPointer.Error()},
// invalid field spec
{"t4.1", &m1, []*FieldRules{Field(m1)}, ErrFieldPointer(0).Error()},
{"t4.2", &m1, []*FieldRules{Field(&m1)}, ErrFieldNotFound(0).Error()},
// struct tag
{"t5.1", &m1, []*FieldRules{Field(&m1.G, &validateAbc{})}, "g: error abc."},
// validatable field
{"t6.1", &m2, []*FieldRules{Field(&m2.E)}, "E: error 123."},
{"t6.2", &m2, []*FieldRules{Field(&m2.E, Skip)}, ""},
{"t6.3", &m2, []*FieldRules{Field(&m2.E, Skip.When(true))}, ""},
{"t6.4", &m2, []*FieldRules{Field(&m2.E, Skip.When(false))}, "E: error 123."},
// Required, NotNil
{"t7.1", &m2, []*FieldRules{Field(&m2.F, Required)}, "F: cannot be blank."},
{"t7.2", &m2, []*FieldRules{Field(&m2.F, NotNil)}, "F: is required."},
{"t7.3", &m2, []*FieldRules{Field(&m2.F, Skip, Required)}, ""},
{"t7.4", &m2, []*FieldRules{Field(&m2.F, Skip, NotNil)}, ""},
{"t7.5", &m2, []*FieldRules{Field(&m2.F, Skip.When(true), Required)}, ""},
{"t7.6", &m2, []*FieldRules{Field(&m2.F, Skip.When(true), NotNil)}, ""},
{"t7.7", &m2, []*FieldRules{Field(&m2.F, Skip.When(false), Required)}, "F: cannot be blank."},
{"t7.8", &m2, []*FieldRules{Field(&m2.F, Skip.When(false), NotNil)}, "F: is required."},
// embedded structs
{"t8.1", &m3, []*FieldRules{Field(&m3.M3, Skip)}, ""},
{"t8.2", &m3, []*FieldRules{Field(&m3.M3)}, "M3: (A: error abc.)."},
{"t8.3", &m3, []*FieldRules{Field(&m3.Model3, Skip)}, ""},
{"t8.4", &m3, []*FieldRules{Field(&m3.Model3)}, "A: error abc."},
{"t8.5", &m4, []*FieldRules{Field(&m4.M3)}, ""},
{"t8.6", &m4, []*FieldRules{Field(&m4.Model3)}, ""},
{"t8.7", &m3, []*FieldRules{Field(&m3.A, Required), Field(&m3.B, Required)}, "A: cannot be blank; B: cannot be blank."},
{"t8.8", &m3, []*FieldRules{Field(&m4.A, Required)}, "field #0 cannot be found in the struct"},
// internal error
{"t9.1", &m5, []*FieldRules{Field(&m5.A, &validateAbc{}), Field(&m5.B, Required), Field(&m5.A, &validateInternalError{})}, "error internal"},
}
for _, test := range tests {
err1 := ValidateStruct(test.model, test.rules...)
err2 := ValidateStructWithContext(context.Background(), test.model, test.rules...)
assertError(t, test.err, err1, test.tag)
assertError(t, test.err, err2, test.tag)
}
// embedded struct
err := Validate(&m3)
assert.EqualError(t, err, "A: error abc.")
a := struct {
Name string
Value string
}{"name", "demo"}
err = ValidateStruct(&a,
Field(&a.Name, Required),
Field(&a.Value, Required, Length(5, 10)),
)
assert.EqualError(t, err, "Value: the length must be between 5 and 10.")
}
func TestValidateStructWithContext(t *testing.T) {
m1 := Model1{A: "abc", B: "xyz", c: "abc", G: "xyz"}
m2 := Model2{Model3: Model3{A: "internal"}}
m3 := Model5{}
m4 := struct {
A int
B struct {
C struct {
D string
}
}
}{}
tests := []struct {
tag string
model interface{}
rules []*FieldRules
err string
}{
// normal rules
{"t1.1", &m1, []*FieldRules{Field(&m1.A, &validateContextAbc{}), Field(&m1.B, &validateContextXyz{})}, ""},
{"t1.2", &m1, []*FieldRules{Field(&m1.A, &validateContextXyz{}), Field(&m1.B, &validateContextAbc{})}, "A: error xyz; B: error abc."},
{"t1.3", &m1, []*FieldRules{Field(&m1.A, &validateContextXyz{}), Field(&m1.c, &validateContextXyz{})}, "A: error xyz; c: error xyz."},
{"t1.4", &m1, []*FieldRules{Field(&m1.G, &validateContextAbc{})}, "g: error abc."},
{"t1.6", &m4, []*FieldRules{FieldStruct(&m4.B, FieldStruct(&m4.B.C, Field(&m4.B.C.D, Required)))}, "B: (C: (D: cannot be blank.).)."},
// skip rule
{"t2.1", &m1, []*FieldRules{Field(&m1.G, Skip, &validateContextAbc{})}, ""},
{"t2.2", &m1, []*FieldRules{Field(&m1.G, &validateContextAbc{}, Skip)}, "g: error abc."},
// internal error
{"t3.1", &m2, []*FieldRules{Field(&m2.A, &validateContextAbc{}), Field(&m2.B, Required), Field(&m2.A, &validateInternalError{})}, "error internal"},
}
for _, test := range tests {
err := ValidateStructWithContext(context.Background(), test.model, test.rules...)
assertError(t, test.err, err, test.tag)
}
// embedded struct
err := ValidateWithContext(context.Background(), &m3)
if assert.NotNil(t, err) {
assert.Equal(t, "A: error abc.", err.Error())
}
a := struct {
Name string
Value string
}{"name", "demo"}
err = ValidateStructWithContext(context.Background(), &a,
Field(&a.Name, Required),
Field(&a.Value, Required, Length(5, 10)),
)
if assert.NotNil(t, err) {
assert.Equal(t, "Value: the length must be between 5 and 10.", err.Error())
}
}
func Test_getErrorFieldName(t *testing.T) {
var s1 Struct1
v1 := reflect.ValueOf(&s1).Elem()
sf1 := findStructField(v1, reflect.ValueOf(&s1.Field1))
assert.NotNil(t, sf1)
assert.Equal(t, "Field1", getErrorFieldName(sf1))
jsonField := findStructField(v1, reflect.ValueOf(&s1.JSONField))
assert.NotNil(t, jsonField)
assert.Equal(t, "some_json_field", getErrorFieldName(jsonField))
jsonIgnoredField := findStructField(v1, reflect.ValueOf(&s1.JSONIgnoredField))
assert.NotNil(t, jsonIgnoredField)
assert.Equal(t, "JSONIgnoredField", getErrorFieldName(jsonIgnoredField))
}
func Test_GetErrorFieldName_Override(t *testing.T) {
// get the default so that we can revert when done with this test
origGetErrorFieldName := GetErrorFieldName
defer func() {
GetErrorFieldName = origGetErrorFieldName
}()
var s1 Struct1
v1 := reflect.ValueOf(&s1).Elem()
// custom GetErrorFieldName function to get field name from protocol buffer (proto3) json encoding
getErrorFieldNameFromProto3 := func(f *reflect.StructField) string {
if tag := f.Tag.Get("protobuf"); tag != "" && tag != "-" {
for _, v := range strings.Split(tag, ",") {
if vs := strings.Split(v, "="); len(vs) == 2 && vs[0] == "json" {
return vs[1]
}
}
}
return f.Name
}
// override the default
GetErrorFieldName = getErrorFieldNameFromProto3
protobufField := findStructField(v1, reflect.ValueOf(&s1.ProtobufField))
assert.NotNil(t, protobufField)
assert.Equal(t, "someProtobufField", GetErrorFieldName(protobufField))
}
func TestErrorFieldName(t *testing.T) {
type args struct {
structPtr interface{}
fieldPtr interface{}
}
type testStruct struct {
name string
args args
want string
wantErr assert.ErrorAssertionFunc
initFn func(tt *testStruct)
}
tests := []testStruct{
{
name: "find field JSON tag succeeds",
args: args{},
want: "some_json_field",
wantErr: assert.NoError,
initFn: func(tt *testStruct) {
struct1 := &Struct1{}
tt.args.structPtr = struct1
tt.args.fieldPtr = &struct1.JSONField
},
},
{
name: "nil struct pointer succeeds with no error and empty JSON name",
args: args{},
want: "",
wantErr: assert.NoError,
initFn: func(tt *testStruct) {
tt.args.structPtr = (*Struct1)(nil)
tt.args.fieldPtr = nil
},
},
{
name: "plain old nil pointer fails",
args: args{},
want: "",
wantErr: assert.Error,
initFn: func(tt *testStruct) {
tt.args.structPtr = nil
tt.args.fieldPtr = nil
},
},
{
name: "pointer to non-struct fails",
args: args{},
want: "",
wantErr: assert.Error,
initFn: func(tt *testStruct) {
var value int
tt.args.structPtr = &value
tt.args.fieldPtr = nil
},
},
{
name: "nil field pointer fails",
args: args{},
want: "",
wantErr: assert.Error,
initFn: func(tt *testStruct) {
struct1 := &Struct1{}
tt.args.structPtr = struct1
tt.args.fieldPtr = nil
},
},
{
name: "field pointer to a different struct fails",
args: args{},
want: "",
wantErr: assert.Error,
initFn: func(tt *testStruct) {
struct1 := &Struct1{}
struct2 := &Struct2{}
tt.args.structPtr = struct1
tt.args.fieldPtr = &struct2.Field21
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.initFn(&tt)
got, err := ErrorFieldName(tt.args.structPtr, tt.args.fieldPtr)
if !tt.wantErr(t, err, fmt.Sprintf("ErrorFieldName(%v, %v)", tt.args.structPtr, tt.args.fieldPtr)) {
return
}
assert.Equalf(t, tt.want, got, "ErrorFieldName(%v, %v)", tt.args.structPtr, tt.args.fieldPtr)
})
}
}