forked from go-rel/changeset
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidate_required_test.go
101 lines (86 loc) · 2.53 KB
/
validate_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
package changeset
import (
"fmt"
"strings"
"testing"
"time"
"github.com/Fs02/changeset/params"
"github.com/stretchr/testify/assert"
)
type customString string
func (c customString) IsZero() bool {
return strings.TrimSpace(string(c)) == ""
}
func TestValidateRequired(t *testing.T) {
ch := &Changeset{
values: map[string]interface{}{
"field3": true,
},
changes: map[string]interface{}{
"field1": 1,
"field2": " 1 ",
},
}
ValidateRequired(ch, []string{"field1", "field2", "field3"})
assert.Nil(t, ch.Errors())
}
func TestValidateRequired_cast(t *testing.T) {
type customString string
type customType struct {
Field1 customString
Field2 customString
Field3 customString
FieldTime time.Time
}
ct := customType{Field1: "field1", FieldTime: time.Now()}
ch := Cast(ct, params.Map{"field2": "field2", "field3": "field3"}, []string{"field1", "field2", "field3", "field_time"})
ValidateRequired(ch, []string{"field1", "field2", "field3", "field_time"})
assert.Nil(t, ch.Errors())
}
func TestValidateRequired_error(t *testing.T) {
ch := &Changeset{
changes: map[string]interface{}{
"field1": nil,
"field2": " ",
},
}
ValidateRequired(ch, []string{"field1", "field2", "field3"})
assert.NotNil(t, ch.Errors())
assert.Equal(t, 3, len(ch.Errors()))
assert.Equal(t, "field1 is required", ch.Errors()[0].Error())
assert.Equal(t, "field2 is required", ch.Errors()[1].Error())
assert.Equal(t, "field3 is required", ch.Errors()[2].Error())
// empty struct
ch = &Changeset{
zero: true,
values: map[string]interface{}{
"field1": 0,
"field2": "",
"field3": false,
},
changes: map[string]interface{}{
"field1": 1,
},
}
ValidateRequired(ch, []string{"field1", "field2", "field3"})
assert.NotNil(t, ch.Errors())
assert.Equal(t, 2, len(ch.Errors()))
assert.Equal(t, "field2 is required", ch.Errors()[0].Error())
assert.Equal(t, "field3 is required", ch.Errors()[1].Error())
}
func TestValidateRequired_cast_error(t *testing.T) {
type customType struct {
Field1 customString
Field2 customString
Field3 customString
FieldTime time.Time
}
ct := customType{Field1: "field1"}
fmt.Println(ct.FieldTime)
ch := Cast(ct, params.Map{"field2": "field2"}, []string{"field1", "field2", "field3", "field_time"})
ValidateRequired(ch, []string{"field1", "field2", "field3", "field_time"})
assert.NotNil(t, ch.Errors())
assert.Equal(t, 2, len(ch.Errors()))
assert.Equal(t, "field3 is required", ch.Errors()[0].Error())
assert.Equal(t, "field_time is required", ch.Errors()[1].Error())
}