-
Notifications
You must be signed in to change notification settings - Fork 18
/
jsonschema.go
78 lines (62 loc) · 1.97 KB
/
jsonschema.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
package cute
import (
"fmt"
"github.com/ozontech/cute/errors"
"github.com/xeipuuv/gojsonschema"
)
// Validate is a function to validate json by json schema.
// Automatically add information about validation to allure.
func (it *Test) validateJSONSchema(t internalT, body []byte) []error {
var (
expect gojsonschema.JSONLoader
)
switch {
case it.Expect.JSONSchema.String != "":
expect = gojsonschema.NewStringLoader(it.Expect.JSONSchema.String)
case it.Expect.JSONSchema.Byte != nil:
expect = gojsonschema.NewBytesLoader(it.Expect.JSONSchema.Byte)
case it.Expect.JSONSchema.File != "":
expect = gojsonschema.NewReferenceLoader(it.Expect.JSONSchema.File)
default:
return nil
}
return it.executeWithStep(t, "Validate body by JSON schema", func(_ T) []error {
return checkJSONSchema(expect, body)
})
}
func checkJSONSchema(expect gojsonschema.JSONLoader, data []byte) []error {
scope := make([]error, 0)
validateResult, err := gojsonschema.Validate(expect, gojsonschema.NewBytesLoader(data))
if err != nil {
return []error{errors.NewEmptyAssertError("could not validate json schema", err.Error())}
}
if !validateResult.Valid() && len(validateResult.Errors()) > 0 {
for _, resultError := range validateResult.Errors() {
scope = append(
scope,
createJSONSchemaError(resultError),
)
}
}
return scope
}
func createJSONSchemaError(err gojsonschema.ResultError) error {
fields := make(map[string]interface{})
textError := ""
if v, ok := err.Details()["context"]; ok {
textError = fmt.Sprintf("On path: %v.", v)
fields["Path"] = v
}
if v, ok := err.Details()["field"]; ok {
textError = fmt.Sprintf("%v Error field: %v.", textError, v)
fields["Field"] = v
}
textError = fmt.Sprintf("%v Error: %v.", textError, err.String())
assertError := errors.NewAssertError(
fmt.Sprintf("Error \"%v\"", err.Type()),
textError,
err.Details()["given"],
err.Details()["expected"])
assertError.(errors.WithFields).PutFields(fields)
return assertError
}