-
Notifications
You must be signed in to change notification settings - Fork 0
/
union_test.go
121 lines (100 loc) · 2.12 KB
/
union_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 owl_test
import (
"encoding/json"
"testing"
"github.com/aacebo/owl"
)
func TestUnion(t *testing.T) {
t.Run("union", func(t *testing.T) {
t.Run("should succeed", func(t *testing.T) {
err := owl.Union(
owl.String().Required(),
owl.Int().Required(),
).Validate("test")
if err != nil {
t.Fatal(err.Error())
}
})
t.Run("should fail", func(t *testing.T) {
err := owl.Union(
owl.String().Required(),
owl.Int().Required(),
).Validate(true)
if err == nil {
t.Fatal()
}
})
})
t.Run("message", func(t *testing.T) {
t.Run("should have custom error message", func(t *testing.T) {
err := owl.Union(
owl.String().Required(),
owl.Int().Required(),
).Message("a test message").Validate(true)
if err == nil {
t.FailNow()
}
if err.Error() != `{"errors":[{"rule":"type","message":"a test message"}]}` {
t.Errorf(
"expected `%s`, received `%s`",
`{"errors":[{"rule":"type","message":"required"}]}`,
err.Error(),
)
}
})
})
t.Run("json", func(t *testing.T) {
t.Run("serialize", func(t *testing.T) {
schema := owl.Union(
owl.String().Required(),
owl.Int().Required(),
)
b, err := json.Marshal(schema)
if err != nil {
t.Error(err)
}
if string(b) != `{"type":"union[string,int]"}` {
t.Errorf(
"expected `%s`, received `%s`",
`{"type":"union[string,int]"}`,
string(b),
)
}
})
})
}
func BenchmarkUnion(b *testing.B) {
b.Run("string or int", func(b *testing.B) {
values := []any{"test", 1}
schema := owl.Union(
owl.String().Required(),
owl.Int().Required(),
)
for i := 0; i < b.N; i++ {
var err error
if i%2 == 0 {
err = schema.Validate(values[0])
} else {
err = schema.Validate(values[1])
}
if err != nil {
b.Fatal(err)
}
}
})
}
func ExampleUnion() {
schema := owl.Union(
owl.String().Required(),
owl.Int().Required(),
)
if err := schema.Validate("test"); err != nil { // nil
panic(err)
}
if err := schema.Validate(1); err != nil { // nil
panic(err)
}
if err := schema.Validate(true); err != nil { // error
panic(err)
}
}