-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator_test.go
95 lines (76 loc) · 1.84 KB
/
validator_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
package typutil_test
import (
"errors"
"strings"
"testing"
"github.com/KarpelesLab/typutil"
)
type valA struct {
A string `validator:"not_empty"`
}
func TestValidator(t *testing.T) {
var a *valA
err := typutil.Assign(&a, map[string]any{"A": ""})
if err == nil || !errors.Is(err, typutil.ErrEmptyValue) {
t.Errorf("struct to struct assign failed: %s", err)
}
err = typutil.Assign(&a, map[string]any{"A": "hello"})
if err != nil {
t.Errorf("struct to struct assign failed: %s", err)
return
}
if a.A != "hello" {
t.Errorf("assign failed")
}
err = typutil.Validate(a)
if err != nil {
t.Errorf("validate failed: %s", err)
}
a.A = ""
err = typutil.Validate(a)
if err == nil || !errors.Is(err, typutil.ErrEmptyValue) {
t.Errorf("validate error failed: %v", err)
}
}
type valB struct {
X string `validator:"valb_test"`
}
func TestPtrValidator(t *testing.T) {
var b *valB
typutil.SetValidator("valb_test", func(s *string) error {
*s = strings.ToUpper(*s)
return nil
})
err := typutil.Assign(&b, map[string]any{"X": "Value"})
if err != nil {
t.Errorf("struct to struct assign failed: %s", err)
return
}
if b.X != "VALUE" {
t.Errorf("validator alter failed, got %s", b.X)
}
b.X = "another value"
err = typutil.Validate(b)
if err != nil {
t.Errorf("failed to validate struct: %s", err)
}
if b.X != "ANOTHER VALUE" {
t.Errorf("unexpected X value: %s", b.X)
}
}
type valC struct {
A string `validator:"minlength=3"`
}
func TestArgValidator(t *testing.T) {
var c *valC
err := typutil.Assign(&c, map[string]any{"A": "b"})
if err == nil {
t.Errorf("should have had an error")
} else if err.Error() != "on field A: string must be at least 3 characters" {
t.Errorf("unexpected error %s", err)
}
err = typutil.Assign(&c, map[string]any{"A": "boo"})
if err != nil {
t.Errorf("unexpected error %s", err)
}
}