-
Notifications
You must be signed in to change notification settings - Fork 8
/
match_json.go
71 lines (58 loc) · 1.41 KB
/
match_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
package matchers
import (
"encoding/json"
"fmt"
"reflect"
)
// MatchJSONMatcher converts both expected and actual to a map[string]any
// and does a reflect.DeepEqual between them
type MatchJSONMatcher struct {
expected any
}
// MatchJSON returns an MatchJSONMatcher with the expected value
func MatchJSON(expected any) MatchJSONMatcher {
return MatchJSONMatcher{
expected: expected,
}
}
func (m MatchJSONMatcher) Match(actual any) (any, error) {
a, sa, err := m.unmarshal(actual)
if err != nil {
return nil, fmt.Errorf("Error with %s: %s", sa, err)
}
e, se, err := m.unmarshal(m.expected)
if err != nil {
return nil, fmt.Errorf("Error with %s: %s", se, err)
}
if !reflect.DeepEqual(a, e) {
return nil, fmt.Errorf("expected %s to equal %s", sa, se)
}
return actual, nil
}
func (m MatchJSONMatcher) unmarshal(x any) (any, string, error) {
var result any
var s string
switch x := x.(type) {
case []byte:
if err := json.Unmarshal(x, &result); err != nil {
return nil, string(x), err
}
s = string(x)
case string:
if err := json.Unmarshal([]byte(x), &result); err != nil {
return nil, x, err
}
s = x
case *string:
if x == nil {
return nil, "", fmt.Errorf("*string cannot be nil")
}
s = *x
if err := json.Unmarshal([]byte(s), &result); err != nil {
return nil, s, err
}
default:
return nil, "", fmt.Errorf("must be a []byte, *string, or string")
}
return result, s, nil
}