-
Notifications
You must be signed in to change notification settings - Fork 54
/
traversal_test.go
106 lines (93 loc) · 2.06 KB
/
traversal_test.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
package jsonschema
import (
"context"
"io/ioutil"
"testing"
)
func TestSchemaDeref(t *testing.T) {
ctx := context.Background()
sch := []byte(`{
"$defs": {
"a": {"type": "integer"},
"b": {"$ref": "#/$defs/a"},
"c": {"$ref": "#/$defs/b"}
},
"$ref": "#/$defs/c"
}`)
rs := &Schema{}
if err := rs.UnmarshalJSON(sch); err != nil {
t.Errorf("unexpected unmarshal error: %s", err.Error())
return
}
got, err := rs.ValidateBytes(ctx, []byte(`"a"`))
if err != nil {
t.Errorf("error validating bytes: %s", err.Error())
return
}
if got == nil {
t.Errorf("expected error, got nil")
return
}
}
func TestReferenceTraversal(t *testing.T) {
sch, err := ioutil.ReadFile("testdata/draft2019-09_schema.json")
if err != nil {
t.Errorf("error reading file: %s", err.Error())
return
}
rs := &Schema{}
if err := rs.UnmarshalJSON(sch); err != nil {
t.Errorf("unexpected unmarshal error: %s", err.Error())
return
}
elements := 0
expectElements := 14
refs := 0
expectRefs := 6
walkJSON(rs, func(elem JSONPather) error {
elements++
if sch, ok := elem.(*Schema); ok {
if sch.HasKeyword("$ref") {
refs++
}
}
return nil
})
if elements != expectElements {
t.Errorf("expected %d elements, got: %d", expectElements, elements)
}
if refs != expectRefs {
t.Errorf("expected %d references, got: %d", expectRefs, refs)
}
cases := []struct {
input string
elements int
refs int
}{
{`{ "not" : { "$ref":"#" }}`, 2, 0},
}
for i, c := range cases {
rs := &Schema{}
if err := rs.UnmarshalJSON([]byte(c.input)); err != nil {
t.Errorf("unexpected unmarshal error: %s", err.Error())
return
}
elements := 0
refs := 0
walkJSON(rs, func(elem JSONPather) error {
elements++
if sch, ok := elem.(*Schema); ok {
if sch.HasKeyword("$ref") {
refs++
}
}
return nil
})
if elements != c.elements {
t.Errorf("case %d: expected %d elements, got: %d", i, c.elements, elements)
}
if refs != c.refs {
t.Errorf("case %d: expected %d references, got: %d", i, c.refs, refs)
}
}
}