forked from gavv/httpexpect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
109 lines (96 loc) · 2.3 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
package httpexpect
import (
"errors"
"fmt"
"reflect"
"regexp"
"github.com/xeipuuv/gojsonschema"
"github.com/yalp/jsonpath"
)
func jsonPath(opChain *chain, value interface{}, path string) *Value {
if opChain.failed() {
return newValue(opChain, nil)
}
filterFn, err := jsonpath.Prepare(path)
if err != nil {
opChain.fail(AssertionFailure{
Type: AssertValid,
Actual: &AssertionValue{path},
Errors: []error{
errors.New("expected: valid json path"),
err,
},
})
return newValue(opChain, nil)
}
result, err := filterFn(value)
if err != nil {
opChain.fail(AssertionFailure{
Type: AssertMatchPath,
Actual: &AssertionValue{value},
Expected: &AssertionValue{path},
Errors: []error{
errors.New("expected: value matches given json path"),
err,
},
})
return newValue(opChain, nil)
}
return newValue(opChain, result)
}
func jsonSchema(opChain *chain, value, schema interface{}) {
if opChain.failed() {
return
}
getString := func(in interface{}) (out string, ok bool) {
ok = true
defer func() {
if err := recover(); err != nil {
ok = false
}
}()
out = reflect.ValueOf(in).Convert(reflect.TypeOf("")).String()
return
}
var schemaLoader gojsonschema.JSONLoader
var schemaData interface{}
if str, ok := getString(schema); ok {
if ok, _ := regexp.MatchString(`^\w+://`, str); ok {
schemaLoader = gojsonschema.NewReferenceLoader(str)
schemaData = str
} else {
schemaLoader = gojsonschema.NewStringLoader(str)
schemaData, _ = schemaLoader.LoadJSON()
}
} else {
schemaLoader = gojsonschema.NewGoLoader(schema)
schemaData = schema
}
valueLoader := gojsonschema.NewGoLoader(value)
result, err := gojsonschema.Validate(schemaLoader, valueLoader)
if err != nil {
opChain.fail(AssertionFailure{
Type: AssertValid,
Actual: &AssertionValue{schema},
Errors: []error{
errors.New("expected: valid json schema"),
err,
},
})
return
}
if !result.Valid() {
errors := []error{
errors.New("expected: value matches given json schema"),
}
for _, err := range result.Errors() {
errors = append(errors, fmt.Errorf("%s", err))
}
opChain.fail(AssertionFailure{
Type: AssertMatchSchema,
Actual: &AssertionValue{value},
Expected: &AssertionValue{schemaData},
Errors: errors,
})
}
}