forked from huttotw/grules
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrule_test.go
111 lines (107 loc) · 2 KB
/
rule_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
package grules
import (
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestValidate(t *testing.T) {
testCases := []struct {
desc string
rule string
shouldError bool
expectedError string
}{
{
desc: "valid rule",
rule: `
{
"path": "foo.bar",
"comparer": "eq",
"value": 42
}
`,
shouldError: false,
},
{
desc: "valid rule with children",
rule: `
{
"operator": "or",
"rules": [
{
"path": "foo.bar",
"comparer": "eq",
"value": 42
},
{
"path": "fizz.buzz",
"comparer": "eq",
"value": 24
}
]
}
`,
shouldError: false,
},
{
desc: "nothing set",
rule: `{}`,
shouldError: true,
expectedError: "must set either path, comparer, and value OR operator and rules",
},
{
desc: "setting both base rule and child rules",
rule: `
{
"path": "foo.bar",
"comparer": "eq",
"value": 42,
"operator": "or",
"rules": [
{
"path": "foo.bar",
"comparer": "eq",
"value": 42
},
{
"path": "fizz.buzz",
"comparer": "eq",
"value": 24
}
]
}
`,
shouldError: true,
expectedError: "setting path, comparer, and value AS WELL AS operator and rules is not valid",
},
{
desc: "missing value for basic rule",
rule: `
{
"path": "foo.bar",
"comparer": "eq"
}
`,
shouldError: true,
expectedError: "must set either path, comparer, and value OR operator and rules",
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
var rule Rule
err := json.NewDecoder(strings.NewReader(tc.rule)).Decode(&rule)
if err != nil {
t.Error("test case rule is not valid:", err.Error())
t.FailNow()
}
err = rule.Validate()
if tc.shouldError && err == nil {
assert.Fail(t, "should have errored but didn't")
}
if err != nil {
assert.EqualError(t, err, tc.expectedError)
}
})
}
}