Skip to content

Commit 890096f

Browse files
authored
feat: Allow testing JSON schema error message (#193)
This is related to cloudquery/cloudquery-issues#1526. It should allow us to validate how the error message is returned from the validator ---
1 parent fec6174 commit 890096f

File tree

2 files changed

+47
-4
lines changed

2 files changed

+47
-4
lines changed

Diff for: jsonschema/testing.go

+6-4
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,10 @@ import (
99
)
1010

1111
type TestCase struct {
12-
Name string
13-
Spec string
14-
Err bool
12+
Name string
13+
Spec string
14+
Err bool
15+
ErrorMessage string
1516
}
1617

1718
func TestJSONSchema(t *testing.T, schema string, cases []TestCase) {
@@ -25,8 +26,9 @@ func TestJSONSchema(t *testing.T, schema string, cases []TestCase) {
2526
var v any
2627
require.NoErrorf(t, json.Unmarshal([]byte(tc.Spec), &v), "failed input:\n%s\n", tc.Spec)
2728
err := validator.Validate(v)
28-
if tc.Err {
29+
if tc.Err || tc.ErrorMessage != "" {
2930
require.Errorf(t, err, "failed input:\n%s\n", tc.Spec)
31+
require.ErrorContains(t, err, tc.ErrorMessage)
3032
} else {
3133
require.NoErrorf(t, err, "failed input:\n%s\n", tc.Spec)
3234
}

Diff for: jsonschema/testing_test.go

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package jsonschema
2+
3+
import (
4+
"testing"
5+
)
6+
7+
type schemaTestCase struct {
8+
name string
9+
schema string
10+
cases []TestCase
11+
}
12+
13+
func TestJSONSchemaCases(t *testing.T) {
14+
tests := []schemaTestCase{
15+
{
16+
name: "simple",
17+
schema: `{ "type": "object", "properties": { "name": { "type": "string" } } }`,
18+
cases: []TestCase{
19+
{
20+
Name: "valid",
21+
Spec: `{ "name": "test" }`,
22+
},
23+
{
24+
Name: "invalid",
25+
Spec: `{ "name": 1 }`,
26+
Err: true,
27+
},
28+
{
29+
Name: "invalid with error message",
30+
Spec: `{ "name": 1 }`,
31+
ErrorMessage: "expected string, but got number",
32+
},
33+
},
34+
},
35+
}
36+
for _, tt := range tests {
37+
t.Run(tt.name, func(t *testing.T) {
38+
TestJSONSchema(t, tt.schema, tt.cases)
39+
})
40+
}
41+
}

0 commit comments

Comments
 (0)