-
Notifications
You must be signed in to change notification settings - Fork 3
/
nested_test.go
83 lines (72 loc) · 1.62 KB
/
nested_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
package validator
import (
"context"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
type (
TestInlineObject struct {
Count int `json:"count"`
}
TestObject struct {
Name string `json:"name"`
Inline TestInlineObject `json:"inline"`
Each []string `json:"each"`
}
)
func TestNested_ValidateValue(t *testing.T) {
rules := RuleSet{
"Name": {
NewRequired(),
},
"Inline": {
NewNested(
RuleSet{
"Count": {
NewRequired(),
NewNumber(2, 3),
},
},
),
},
"Each": {
NewEach(NewStringLength(1, 255)),
},
}
obj := TestObject{
Name: "test",
Inline: TestInlineObject{
Count: 1,
},
Each: []string{"test", ""},
}
ctx := context.Background()
err := Validate(ctx, &obj, rules)
assert.Error(t, err)
var result Result
assert.ErrorAs(t, err, &result)
expectedError := Result{errors: []*ValidationError{
{
Message: "Value must be no less than 2.",
Params: map[string]any{"max": int64(3), "min": int64(2)},
ValuePath: []string{"inline", "count"},
},
{
Message: "This value should contain at least 1.",
Params: map[string]any{"max": 255, "min": 1},
ValuePath: []string{"each", "1"},
},
}}
if !reflect.DeepEqual(expectedError, result) {
assert.Equal(t, expectedError, result)
}
errorMessages := err.(Result).ErrorMessagesIndexedByPath()
expectedMessages := map[string][]string{
"inline.count": {"Value must be no less than 2."},
"each.1": {"This value should contain at least 1."},
}
if !reflect.DeepEqual(expectedMessages, errorMessages) {
assert.Equal(t, expectedMessages, errorMessages)
}
}