forked from go-ozzo/ozzo-validation
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrequired_test.go
144 lines (130 loc) · 2.28 KB
/
required_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
// 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 (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestRequired(t *testing.T) {
s1 := "123"
s2 := ""
var time1 time.Time
tests := []struct {
tag string
value any
err string
}{
{
"t1",
123,
"",
},
{
"t2",
"",
"cannot be blank",
},
{
"t3",
&s1,
"",
},
{
"t4",
&s2,
"cannot be blank",
},
{
"t5",
nil,
"cannot be blank",
},
{
"t6",
time1,
"cannot be blank",
},
}
for _, test := range tests {
r := Required
err := r.Validate(test.value)
assertError(t, test.err, err, test.tag)
}
}
func TestRequiredRule_When(t *testing.T) {
r := Required.When(false)
err := Validate(nil, r)
assert.Nil(t, err)
r = Required.When(true)
err = Validate(nil, r)
assert.Equal(t, ErrRequired, err)
}
func TestNilOrNotEmpty(t *testing.T) {
s1 := "123"
s2 := ""
tests := []struct {
tag string
value any
err string
}{
{
"t1",
123,
"",
},
{
"t2",
"",
"cannot be blank",
},
{
"t3",
&s1,
"",
},
{
"t4",
&s2,
"cannot be blank",
},
{
"t5",
nil,
"",
},
}
for _, test := range tests {
r := NilOrNotEmpty
err := r.Validate(test.value)
assertError(t, test.err, err, test.tag)
}
}
func Test_requiredRule_Error(t *testing.T) {
r := Required
assert.Equal(t, "cannot be blank", r.Validate(nil).Error())
assert.False(t, r.skipNil)
r2 := r.Error("123")
assert.Equal(t, "cannot be blank", r.Validate(nil).Error())
assert.False(t, r.skipNil)
assert.Equal(t, "123", r2.err.Message())
assert.False(t, r2.skipNil)
r = NilOrNotEmpty
assert.Equal(t, "cannot be blank", r.Validate("").Error())
assert.True(t, r.skipNil)
r2 = r.Error("123")
assert.Equal(t, "cannot be blank", r.Validate("").Error())
assert.True(t, r.skipNil)
assert.Equal(t, "123", r2.err.Message())
assert.True(t, r2.skipNil)
}
func TestRequiredRule_Error(t *testing.T) {
r := Required
err := NewError("code", "abc")
r = r.ErrorObject(err)
assert.Equal(t, err, r.err)
assert.Equal(t, err.Code(), r.err.Code())
assert.Equal(t, err.Message(), r.err.Message())
assert.NotEqual(t, err, Required.err)
}