-
Notifications
You must be signed in to change notification settings - Fork 52
/
json.go
206 lines (189 loc) · 7.5 KB
/
json.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package match
import (
"fmt"
"reflect"
"github.com/tidwall/gjson"
)
// JSON will perform some matches on the given JSON body, returning an error on a mis-match.
// It can be assumed that the bytes are valid JSON.
type JSON func(body []byte) error
// JSONKeyEqual returns a matcher which will check that `wantKey` is present and its value matches `wantValue`.
// `wantKey` can be nested, see https://godoc.org/github.com/tidwall/gjson#Get for details.
// `wantValue` is matched via reflect.DeepEqual and the JSON takes the forms according to https://godoc.org/github.com/tidwall/gjson#Result.Value
func JSONKeyEqual(wantKey string, wantValue interface{}) JSON {
return func(body []byte) error {
res := gjson.GetBytes(body, wantKey)
if res.Index == 0 {
return fmt.Errorf("key '%s' missing", wantKey)
}
gotValue := res.Value()
if !reflect.DeepEqual(gotValue, wantValue) {
return fmt.Errorf("key '%s' got '%v' want '%v'", wantKey, gotValue, wantValue)
}
return nil
}
}
// JSONKeyPresent returns a matcher which will check that `wantKey` is present in the JSON object.
// `wantKey` can be nested, see https://godoc.org/github.com/tidwall/gjson#Get for details.
func JSONKeyPresent(wantKey string) JSON {
return func(body []byte) error {
res := gjson.GetBytes(body, wantKey)
if !res.Exists() {
return fmt.Errorf("key '%s' missing", wantKey)
}
return nil
}
}
// JSONKeyTypeEqual returns a matcher which will check that `wantKey` is present and its value is of the type `wantType`.
// `wantKey` can be nested, see https://godoc.org/github.com/tidwall/gjson#Get for details.
func JSONKeyTypeEqual(wantKey string, wantType gjson.Type) JSON {
return func(body []byte) error {
res := gjson.GetBytes(body, wantKey)
if !res.Exists() {
return fmt.Errorf("key '%s' missing", wantKey)
}
if res.Type != wantType {
return fmt.Errorf("key '%s' is of the wrong type, got %s want %s", wantKey, res.Type, wantType)
}
return nil
}
}
func jsonCheckOffInternal(wantKey string, wantItems []interface{}, allowUnwantedItems bool, mapper func(gjson.Result) interface{}, fn func(interface{}, gjson.Result) error) JSON {
return func(body []byte) error {
res := gjson.GetBytes(body, wantKey)
if !res.Exists() {
return fmt.Errorf("missing key '%s'", wantKey)
}
if !res.IsArray() && !res.IsObject() {
return fmt.Errorf("JSONCheckOff: key '%s' is not an array or object", wantKey)
}
var err error
res.ForEach(func(key, val gjson.Result) bool {
itemRes := key
if res.IsArray() {
itemRes = val
}
// convert it to something we can check off
item := mapper(itemRes)
if item == nil {
err = fmt.Errorf("JSONCheckOff: mapper function mapped %v to nil", itemRes.Raw)
return false
}
// check off the item
want := -1
for i, w := range wantItems {
if reflect.DeepEqual(w, item) {
want = i
break
}
}
if !allowUnwantedItems && want == -1 {
err = fmt.Errorf("JSONCheckOff: unexpected item %s", item)
return false
}
if want != -1 {
// delete the wanted item
wantItems = append(wantItems[:want], wantItems[want+1:]...)
}
// do further checks
if fn != nil {
err = fn(item, val)
if err != nil {
return false
}
}
return true
})
// at this point we should have gone through all of wantItems.
// If we haven't then we expected to see some items but didn't.
if err == nil && len(wantItems) > 0 {
err = fmt.Errorf("JSONCheckOff: did not see items: %v", wantItems)
}
return err
}
}
// JSONCheckOffAllowUnwanted returns a matcher which will loop over `wantKey` and ensure that the items
// (which can be array elements or object keys)
// are present exactly once in any order in `wantItems`. Allows unexpected items or items
// appear that more than once. This matcher can be used to check off items in
// an array/object. The `mapper` function should map the item to an interface which will be
// comparable via `reflect.DeepEqual` with items in `wantItems`. The optional `fn` callback
// allows more checks to be performed other than checking off the item from the list. It is
// called with 2 args: the result of the `mapper` function and the element itself (or value if
// it's an object).
//
// Usage: (ensures `events` has these events in any order, with the right event type)
// JSONCheckOffAllowUnwanted("events", []interface{}{"$foo:bar", "$baz:quuz"}, func(r gjson.Result) interface{} {
// return r.Get("event_id").Str
// }, func(eventID interface{}, eventBody gjson.Result) error {
// if eventBody.Get("type").Str != "m.room.message" {
// return fmt.Errorf("expected event to be 'm.room.message'")
// }
// })
func JSONCheckOffAllowUnwanted(wantKey string, wantItems []interface{}, mapper func(gjson.Result) interface{}, fn func(interface{}, gjson.Result) error) JSON {
return jsonCheckOffInternal(wantKey, wantItems, true, mapper, fn)
}
// JSONCheckOff returns a matcher which will loop over `wantKey` and ensure that the items
// (which can be array elements or object keys)
// are present exactly once in any order in `wantItems`. If there are unexpected items or items
// appear more than once then the match fails. This matcher can be used to check off items in
// an array/object. The `mapper` function should map the item to an interface which will be
// comparable via `reflect.DeepEqual` with items in `wantItems`. The optional `fn` callback
// allows more checks to be performed other than checking off the item from the list. It is
// called with 2 args: the result of the `mapper` function and the element itself (or value if
// it's an object).
//
// Usage: (ensures `events` has these events in any order, with the right event type)
// JSONCheckOff("events", []interface{}{"$foo:bar", "$baz:quuz"}, func(r gjson.Result) interface{} {
// return r.Get("event_id").Str
// }, func(eventID interface{}, eventBody gjson.Result) error {
// if eventBody.Get("type").Str != "m.room.message" {
// return fmt.Errorf("expected event to be 'm.room.message'")
// }
// })
func JSONCheckOff(wantKey string, wantItems []interface{}, mapper func(gjson.Result) interface{}, fn func(interface{}, gjson.Result) error) JSON {
return jsonCheckOffInternal(wantKey, wantItems, false, mapper, fn)
}
// JSONArrayEach returns a matcher which will check that `wantKey` is an array then loops over each
// item calling `fn`. If `fn` returns an error, iterating stops and an error is returned.
func JSONArrayEach(wantKey string, fn func(gjson.Result) error) JSON {
return func(body []byte) error {
var res gjson.Result
if wantKey == "" {
res = gjson.ParseBytes(body)
} else {
res = gjson.GetBytes(body, wantKey)
}
if !res.Exists() {
return fmt.Errorf("missing key '%s'", wantKey)
}
if !res.IsArray() {
return fmt.Errorf("key '%s' is not an array", wantKey)
}
var err error
res.ForEach(func(_, val gjson.Result) bool {
err = fn(val)
return err == nil
})
return err
}
}
// JSONMapEach returns a matcher which will check that `wantKey` is a map then loops over each
// item calling `fn`. If `fn` returns an error, iterating stops and an error is returned.
func JSONMapEach(wantKey string, fn func(k, v gjson.Result) error) JSON {
return func(body []byte) error {
res := gjson.GetBytes(body, wantKey)
if !res.Exists() {
return fmt.Errorf("missing key '%s'", wantKey)
}
if !res.IsObject() {
return fmt.Errorf("key '%s' is not an object", wantKey)
}
var err error
res.ForEach(func(key, val gjson.Result) bool {
err = fn(key, val)
return err == nil
})
return err
}
}