-
Notifications
You must be signed in to change notification settings - Fork 6
/
validate_test.go
107 lines (91 loc) · 2.35 KB
/
validate_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
package gody
import (
"reflect"
"testing"
"github.com/guiferpa/gody/v2/rule/ruletest"
)
type StructAForTest struct {
A string `validate:"fake"`
B string
}
func TestValidateMatchRule(t *testing.T) {
payload := StructAForTest{A: "", B: "test-b"}
rule := ruletest.NewRule("fake", true, nil)
validated, err := Validate(payload, []Rule{rule})
if !validated {
t.Error("Validated result is not expected")
return
}
if err != nil {
t.Error("Error result from validate is not expected")
return
}
if !rule.ValidateCalled {
t.Error("The rule validate wasn't call")
return
}
}
func TestValidateNoMatchRule(t *testing.T) {
payload := StructAForTest{A: "", B: "test-b"}
rule := ruletest.NewRule("mock", true, nil)
validated, err := Validate(payload, []Rule{rule})
if !validated {
t.Error("Validated result is not expected")
return
}
if err != nil {
t.Error("Error result from validate is not expected")
return
}
if rule.ValidateCalled {
t.Error("The rule validate was call")
return
}
}
type StructBForTest struct {
C int `validate:"test"`
D bool
}
type errStructBForValidation struct{}
func (_ *errStructBForValidation) Error() string {
return ""
}
func TestValidateWithRuleError(t *testing.T) {
payload := StructBForTest{C: 10}
rule := ruletest.NewRule("test", true, &errStructBForValidation{})
validated, err := Validate(payload, []Rule{rule})
if !validated {
t.Error("Validated result is not expected")
return
}
if !rule.ValidateCalled {
t.Error("The rule validate was call")
return
}
if _, ok := err.(*errStructBForValidation); !ok {
t.Errorf("Unexpected error type: got: %v", err)
return
}
}
func TestSetTagName(t *testing.T) {
validator := NewValidator()
if got, want := validator.tagName, DefaultTagName; got != want {
t.Errorf("Unexpected default tag value from validator struct type: got: %v, want: %v", got, want)
return
}
newTag := "new-tag"
validator.SetTagName(newTag)
if got, want := validator.tagName, newTag; got != want {
t.Errorf("Unexpected default tag value from validator struct type: got: %v, want: %v", got, want)
return
}
err := validator.SetTagName("")
if err == nil {
t.Errorf("Unexpected error as nil")
return
}
if ce, ok := err.(*ErrEmptyTagName); !ok {
t.Errorf("Unexpected error type: got: %v, want: %v", reflect.TypeOf(ce), reflect.TypeOf(&ErrEmptyTagName{}))
return
}
}