-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsonschema_test.go
120 lines (97 loc) · 2.6 KB
/
jsonschema_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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package expose
import (
"fmt"
"slices"
"testing"
"github.com/getkin/kin-openapi/openapi3"
"github.com/ysmood/got"
)
func TestWalkSchema(t *testing.T) {
g := got.T(t)
schemaJson := `{
"$id": "root",
"allOf": [
{ "$id": "allOf1" },
{
"$id": "allOfNested",
"anyOf": [
{ "$id": "anyOf1" }
]
}
],
"oneOf": [
{ "$id": "oneOf1" },
{ "$id": "oneOf2" }
],
"properties": {
"prop1": {
"$id": "prop1",
"type": "array",
"items": { "$id": "item1" }
},
"prop2": {
"$id": "prop2",
"properties": {
"prop3": { "$id": "nestedProp" }
}
}
}
}`
t.Run("traversal", func(t *testing.T) {
var schema openapi3.Schema
g.Must().Nil(schema.UnmarshalJSON([]byte(schemaJson)))
var actual []string
expected := []string{
"allOf1", "anyOf1", "allOfNested", "oneOf1", "oneOf2",
"nestedProp", "prop2", "item1", "prop1", "root",
}
g.Must().Nil(walkSchema(openapi3.NewSchemaRef("", &schema), func(s *openapi3.SchemaRef) (*openapi3.SchemaRef, error) {
actual = append(actual, s.Value.Extensions["$id"].(string))
return nil, nil
}))
slices.Sort(actual)
slices.Sort(expected)
g.Eq(actual, expected)
})
t.Run("replace", func(t *testing.T) {
var schema openapi3.Schema
g.Must().Nil(schema.UnmarshalJSON([]byte(schemaJson)))
g.Must().Nil(walkSchema(openapi3.NewSchemaRef("", &schema), func(s *openapi3.SchemaRef) (*openapi3.SchemaRef, error) {
id := s.Value.Extensions["$id"].(string)
if id == "nestedProp" {
return openapi3.NewSchemaRef("#/components/schemas/nestedProp", nil), nil
}
return nil, nil
}))
ref := schema.Properties["prop2"].Value.Properties["prop3"].Ref
g.Must().Eq(ref, "#/components/schemas/nestedProp")
})
t.Run("nil", func(t *testing.T) {
var schema openapi3.Schema
g.Must().Nil(schema.UnmarshalJSON([]byte(schemaJson)))
g.Must().Nil(walkSchema(openapi3.NewSchemaRef("", nil), func(s *openapi3.SchemaRef) (*openapi3.SchemaRef, error) {
return nil, nil
}))
})
t.Run("error", func(t *testing.T) {
var schema openapi3.Schema
g.Must().Nil(schema.UnmarshalJSON([]byte(schemaJson)))
expected := []string{
"allOf1", "anyOf1", "allOfNested", "oneOf1", "oneOf2",
"nestedProp", "prop2", "item1", "prop1", "root",
}
for _, failId := range expected {
t.Run(failId, func(t *testing.T) {
failId := failId
g := got.T(t)
g.Must().NotNil(walkSchema(openapi3.NewSchemaRef("", &schema), func(s *openapi3.SchemaRef) (*openapi3.SchemaRef, error) {
id := s.Value.Extensions["$id"].(string)
if id == failId {
return nil, fmt.Errorf("test")
}
return nil, nil
}))
})
}
})
}