-
-
Notifications
You must be signed in to change notification settings - Fork 239
/
canon.go
128 lines (118 loc) · 2.58 KB
/
canon.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
package httpexpect
import (
"encoding/json"
"errors"
"fmt"
"reflect"
)
func canonNumber(opChain *chain, in interface{}) (out float64, ok bool) {
ok = true
defer func() {
if err := recover(); err != nil {
opChain.fail(AssertionFailure{
Type: AssertValid,
Actual: &AssertionValue{in},
Errors: []error{
errors.New("expected: valid number"),
fmt.Errorf("%s", err),
},
})
ok = false
}
}()
out = reflect.ValueOf(in).Convert(reflect.TypeOf(float64(0))).Float()
return
}
func canonArray(opChain *chain, in interface{}) ([]interface{}, bool) {
var out []interface{}
data, ok := canonValue(opChain, in)
if ok {
out, ok = data.([]interface{})
if !ok {
opChain.fail(AssertionFailure{
Type: AssertValid,
Actual: &AssertionValue{in},
Errors: []error{
errors.New("expected: valid array"),
},
})
}
}
return out, ok
}
func canonMap(opChain *chain, in interface{}) (map[string]interface{}, bool) {
var out map[string]interface{}
data, ok := canonValue(opChain, in)
if ok {
out, ok = data.(map[string]interface{})
if !ok {
opChain.fail(AssertionFailure{
Type: AssertValid,
Actual: &AssertionValue{in},
Errors: []error{
errors.New("expected: valid map"),
},
})
}
}
return out, ok
}
func canonValue(opChain *chain, in interface{}) (interface{}, bool) {
b, err := json.Marshal(in)
if err != nil {
opChain.fail(AssertionFailure{
Type: AssertValid,
Actual: &AssertionValue{in},
Errors: []error{
errors.New("expected: marshalable value"),
err,
},
})
return nil, false
}
var out interface{}
if err := json.Unmarshal(b, &out); err != nil {
opChain.fail(AssertionFailure{
Type: AssertValid,
Actual: &AssertionValue{in},
Errors: []error{
errors.New("expected: unmarshalable value"),
err,
},
})
return nil, false
}
return out, true
}
func canonDecode(opChain *chain, value interface{}, target interface{}) {
if target == nil {
opChain.fail(AssertionFailure{
Type: AssertUsage,
Errors: []error{
errors.New("unexpected nil target argument"),
},
})
return
}
b, err := json.Marshal(value)
if err != nil {
opChain.fail(AssertionFailure{
Type: AssertValid,
Actual: &AssertionValue{value},
Errors: []error{
errors.New("expected: marshable value"),
},
})
return
}
if err := json.Unmarshal(b, target); err != nil {
opChain.fail(AssertionFailure{
Type: AssertValid,
Actual: &AssertionValue{target},
Errors: []error{
errors.New("expected: value can be unmarshaled into target argument"),
},
})
return
}
}