/
schema_checker.go
82 lines (61 loc) · 1.63 KB
/
schema_checker.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
package testutil
import (
"errors"
"fmt"
"strings"
"testing"
"ecsdeployer.com/ecsdeployer/internal/configschema"
"ecsdeployer.com/ecsdeployer/internal/util"
"ecsdeployer.com/ecsdeployer/internal/yaml"
"github.com/xeipuuv/gojsonschema"
)
type SchemaChecker struct {
schema *gojsonschema.Schema
}
var ErrSchemaViolation = errors.New("JsonSchemaViolation")
func NewSchemaChecker(v any) *SchemaChecker {
schema := configschema.GenerateSchema(v)
schemaJson, err := util.Jsonify(schema)
if err != nil {
panic(err)
}
jsonSchema, err := gojsonschema.NewSchema(gojsonschema.NewStringLoader(schemaJson))
if err != nil {
panic(err)
}
return &SchemaChecker{
schema: jsonSchema,
}
}
// Validates that the YAML provided adheres to the Schema (when converted to json)
func (obj *SchemaChecker) CheckYAML(t *testing.T, val string) error {
t.Helper()
var tmp interface{}
if err := yaml.Unmarshal([]byte(val), &tmp); err != nil {
panic(err)
}
jsonData, err := util.Jsonify(tmp)
if err != nil {
panic(err)
}
return obj.CheckJSON(t, jsonData)
}
// Validates that the JSON provided adheres to the Schema
func (obj *SchemaChecker) CheckJSON(t *testing.T, val string) error {
t.Helper()
valLoader := gojsonschema.NewStringLoader(val)
result, err := obj.schema.Validate(valLoader)
if err != nil {
panic(err)
}
if result.Valid() {
return nil
}
schemaErrs := result.Errors()
errList := make([]string, 0, len(schemaErrs)+1)
errList = append(errList, "SchemaFailure")
for _, err := range schemaErrs {
errList = append(errList, err.String())
}
return fmt.Errorf("%w: %s", ErrSchemaViolation, strings.Join(errList, "\n"))
}