Repository navigation
Expand file tree
/
Copy pathvalidator_test.go
More file actions
77 lines (70 loc) · 2.18 KB
/
Copy pathvalidator_test.go
File metadata and controls
77 lines (70 loc) · 2.18 KB
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
package validator
import (
"context"
"reflect"
"testing"
)
func TestErrorsModel(t *testing.T) {
e := &Errors{}
if e.Error() != "" || e.Has("a") {
t.Fatal("empty errors should be empty")
}
e.add(FieldError{Field: "email", Rule: "required", Message: "The email is required."}, "email")
e.add(FieldError{Field: "email", Rule: "email", Message: "The email must be valid."}, "email")
e.add(FieldError{Field: "age", Rule: "min", Message: "The age is too small."}, "age")
if !e.Has("email") {
t.Error("Has(email) should be true")
}
if e.OneFor("email") != "The email is required." {
t.Errorf("One(email)=%q", e.OneFor("email"))
}
if e.One() != "The email is required." {
t.Errorf("One()=%q", e.One())
}
if len(e.Messages("email")) != 2 {
t.Errorf("Messages(email) len=%d want 2", len(e.Messages("email")))
}
all := e.All()
if len(all) != 2 || len(all["email"]) != 2 {
t.Errorf("All() projection wrong: %v", all)
}
// fields sorted
want := "age: The age is too small.; email: The email is required."
if got := e.Error(); got != want {
t.Errorf("Error()=%q want %q", got, want)
}
}
func TestRegistryAndFuncRule(t *testing.T) {
called := false
v := MustNew(WithoutBuiltinRules(),
WithRuleFunc("always", func(f *Field) bool { called = true; return true }, "nope"))
r, ok := v.registry.rule("always")
if !ok {
t.Fatal("rule 'always' not registered")
}
f := &Field{name: "x", rv: reflect.ValueOf("y")}
if !r.Passes(f) || !called {
t.Error("func rule should pass and be invoked")
}
if r.Message() != "nope" {
t.Errorf("Message()=%q", r.Message())
}
}
func TestFieldBasics(t *testing.T) {
f := &Field{name: "c", rv: reflect.ValueOf(1), ctx: context.Background()}
if f.Name() != "c" || f.Reflect().Interface() != 1 {
t.Error("name/val accessors")
}
if f.Context() == nil {
t.Error("Context() must never be nil")
}
if _, ok := f.Sibling[int]("x"); ok {
t.Error("Sibling with no lookup must report false")
}
// Sibling resolves via the data source
vd := &Validation{src: mapSource{m: map[string]any{"other": 42}}}
g := &Field{name: "g", scope: "g", vd: vd}
if s, ok := g.Sibling[int]("other"); !ok || s != 42 {
t.Error("Sibling should resolve via the source")
}
}