-
Notifications
You must be signed in to change notification settings - Fork 0
/
results_test.go
105 lines (86 loc) · 2.32 KB
/
results_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
package golidate_test
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"github.com/studiolambda/golidate"
"github.com/studiolambda/golidate/format"
"github.com/studiolambda/golidate/rule"
"github.com/studiolambda/golidate/translate/language"
)
func TestResultsTranslate(t *testing.T) {
t.Run("Simple", func(t *testing.T) {
results := golidate.Validate(
context.Background(),
golidate.Value("something invalid").Name("username").Rules(
rule.Alpha(),
),
)
translated := results.Failed().Translate(language.English)
require.Len(t, translated, 1)
require.Equal(t, "the username field must only contain letters", translated[0].Message)
})
t.Run("Complex", func(t *testing.T) {
results := golidate.Validate(
context.Background(),
golidate.Value("something invalid").Name("username").Rules(
rule.And(rule.MinLen(5), rule.MaxLen(10)),
rule.Not(rule.Nil()),
),
)
require.Len(t, results, 2)
translated := results.Failed().Translate(language.English)
require.Len(t, translated, 1)
expected := language.English["and"](language.English, translated[0])
require.Equal(t, expected.Message, translated[0].Message)
})
}
type NestedResults struct {
Name string
Numbers []int
}
func (n NestedResults) Validate(ctx context.Context) golidate.Results {
return golidate.Validate(
ctx,
golidate.Value(n.Name).Name("name").Rules(
rule.MinLen(4),
),
golidate.Value(n.Numbers).Name("numbers").Rules(
rule.SliceValues[[]int](
rule.Min(1),
rule.Max(10),
),
),
)
}
func TestResultsGroup(t *testing.T) {
nested := NestedResults{Numbers: []int{1, 2, 30}}
results := golidate.Validate(
context.Background(),
golidate.Value("something.valid").Name("username").Rules(
rule.Not(rule.Nil()),
rule.Type[string](),
rule.AlphaDash(),
rule.MinLen(2),
rule.MaxLen(255),
),
golidate.Value(nested).Name("nested"),
golidate.Value("something invalid").Name("password").Rules(
rule.Not(rule.Nil()),
rule.Type[string](),
rule.AlphaDash(),
rule.MinLen(2),
rule.MaxLen(255),
),
)
grouped := results.
Failed().
Translate(language.English).
Group().
Messages(format.Capitalize(), format.Punctuate())
require.Len(t, grouped, 4)
_, ok := grouped["username"]
_, ok2 := grouped["password"]
require.True(t, ok)
require.True(t, ok2)
}