-
Notifications
You must be signed in to change notification settings - Fork 11
/
e2e_test.go
119 lines (103 loc) · 2.41 KB
/
e2e_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
package check
import (
"strings"
"testing"
"time"
)
type CustomStringContainValidator struct {
Constraint string
}
func (validator CustomStringContainValidator) Validate(v interface{}) Error {
if !strings.Contains(v.(string), validator.Constraint) {
return NewValidationError("customStringContainValidator", v, validator.Constraint)
}
return nil
}
type User struct {
Username string
Password string
Name string
Age int
Email string
Birthday time.Time
}
func (u *User) Validate() StructError {
s := Struct{
"Username": Composite{
NonEmpty{},
Regex{`^[a-zA-Z0-9]+$`},
},
"Password": Composite{
NonEmpty{},
MinChar{8},
},
"Name": NonEmpty{},
"Age": Composite{
GreaterThan{3},
LowerThan{120},
},
"Email": Composite{
Email{},
CustomStringContainValidator{"test.com"},
},
"Birthday": Composite{
Before{time.Date(1990, time.January, 1, 1, 0, 0, 0, time.UTC)},
After{time.Date(1900, time.January, 1, 1, 0, 0, 0, time.UTC)},
},
}
e := s.Validate(u)
return e
}
func TestIntegration(t *testing.T) {
invalidUser := &User{
"not-valid-username*",
"123", // Invalid password length
"", // Cannot be empty
150, // Invalid age
"@test", // Invalid email address
time.Date(1991, time.January, 1, 1, 0, 0, 0, time.UTC), // Invalid date
}
validUser := &User{
"testuser",
"validPassword123",
"Good Name",
20,
time.Date(1980, time.January, 1, 1, 0, 0, 0, time.UTC),
}
e := invalidUser.Validate()
if !e.HasErrors() {
t.Errorf("Expected 'invalidUser' to be invalid")
}
err, ok := e.GetErrorsByKey("Username")
if !ok {
t.Errorf("Expected errors for 'Username'")
} else {
if len(err) < 1 {
t.Errorf("Expected 1 error for 'Username'")
}
}
errMessages := e.ToMessages()
if errMessages["Name"]["nonZero"] != ErrorMessages["nonZero"] {
t.Errorf("Expected proper error message")
}
// json, _ := json.MarshalIndent(errMessages, "", " ")
// log.Println(string(json))
e = validUser.Validate()
if e.HasErrors() {
t.Errorf("Expected 'validUser' to be valid")
}
}
func BenchmarkValidate(b *testing.B) {
for i := 0; i < b.N; i++ {
invalidUser := &User{
"not-valid-username*",
"123", // Invalid password length
"", // Cannot be empty
150, // Invalid age
"@test", // Invalid email address
time.Date(1991, time.January, 1, 1, 0, 0, 0, time.UTC), // Invalid date
}
invalidUser.Validate()
}
}