-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathcrossfield_test.go
121 lines (92 loc) · 2.33 KB
/
crossfield_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
package checker
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
type crossStruct struct {
Int1 int
Int2 int
Uint1 uint
Uint2 uint
Float1 float64
Float2 float64
Date1 time.Time
Date2 time.Time
}
func getCrossChecker() Checker {
crossChecker := NewChecker()
crossRuleInt := CrossComp("Int1", "Int2", CrossFieldNe).
Prompt("Int1 should not be equal to Int2")
crossChecker.Add(crossRuleInt, "")
crossRuleUInt := CrossComp("Uint1", "Uint2", CrossFieldGt)
crossChecker.Add(crossRuleUInt, "invalid uint1 and uint2")
crossRuleFloat := CrossComp("Float1", "Float2", CrossFieldLt)
crossChecker.Add(crossRuleFloat, "invalid Float1 and Float2")
crossRuleTime := CrossComp("Date1", "Date2", CrossFieldLe)
crossChecker.Add(crossRuleTime, "invalid Date1 and Date2")
return crossChecker
}
func TestCrossFieldSimple(t *testing.T) {
crossChecker := getCrossChecker()
layout := "2006-01-02"
date1, _ := time.Parse(layout, "2020-12-12")
date2, _ := time.Parse(layout, "2021-12-12")
cross := crossStruct{
Int1: 1,
Int2: 2,
Uint1: 10,
Uint2: 9,
Float1: 3.14,
Float2: 6.28,
Date1: date1,
Date2: date2,
}
isValid, _, errMsg := crossChecker.Check(cross)
assert.Equal(t, isValid, true, errMsg)
cross.Int1 = 2
isValid, prompt, _ := crossChecker.Check(cross)
assert.Equal(t, false, isValid, "")
assert.Equal(t, "Int1 should not be equal to Int2", prompt, "wrong prompt")
}
type innerInt struct {
Val int
}
func (i innerInt) EqualTo(other interface{}) bool {
otherInt, ok := other.(innerInt)
if !ok {
return false
}
return i.Val == otherInt.Val
}
func (i innerInt) LessThan(other interface{}) bool {
otherInt, ok := other.(innerInt)
if !ok {
return false
}
return i.Val < otherInt.Val
}
type crossInner struct {
Int1 innerInt
Int2 innerInt
}
func TestCrossFieldCustom(t *testing.T) {
crossChecker := NewChecker()
prompt := "Int1 should be ge Int2"
crossRuleInt := CrossComp("Int1", "Int2", CrossFieldGe).Prompt(prompt)
crossChecker.Add(crossRuleInt, "")
cross := crossInner{
Int1: innerInt{
Val: 10,
},
Int2: innerInt{
Val: 2,
},
}
isValid, _, _ := crossChecker.Check(cross)
assert.Equal(t, true, isValid, "")
cross.Int1.Val = -1
isValid, errPrompt, _ := crossChecker.Check(cross)
assert.Equal(t, false, isValid, "")
assert.Equal(t, prompt, errPrompt, "wrong errPrompt")
}