-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate_structs_test.go
73 lines (67 loc) · 1.67 KB
/
validate_structs_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
package structs
import (
"testing"
"github.com/stretchr/testify/assert"
)
type TestStructWithRules struct {
Field1 string `json:"field_1" rules:"required"`
Field2 int `json:"field_2" rules:"required"`
}
func Test_Validate_StructFields(t *testing.T) {
tests := []struct {
name string
input any
tagPriority []string
values map[string]any
expectedErrors map[string][]string
wantErr error
}{
{
name: "all json fields valid",
input: &TestStructWithRules{},
tagPriority: []string{"json"},
values: map[string]any{
"field_1": "field_1_value",
"field_2": "field_2_value",
},
expectedErrors: map[string][]string{},
},
{
name: "one json field invalid",
input: &TestStructWithRules{},
tagPriority: []string{"json"},
values: map[string]any{
"field_2": "field_2_value",
},
expectedErrors: map[string][]string{
"field_1": {"required"},
},
},
{
name: "all json fields invalid",
input: &TestStructWithRules{},
tagPriority: []string{"json"},
values: map[string]any{},
expectedErrors: map[string][]string{
"field_1": {"required"},
"field_2": {"required"},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fields, err := GetStructFields(tt.input, nil)
if tt.wantErr != nil {
assert.ErrorIs(t, err, tt.wantErr)
return
}
errors, err := ValidateStructFields(DefaultRules, fields, tt.values, "json", tt.tagPriority...)
if tt.wantErr != nil {
assert.ErrorIs(t, err, tt.wantErr)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.expectedErrors, errors)
})
}
}