Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions jsonschema/testing.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import (
)

type TestCase struct {
Name string
Spec string
Err bool
Name string
Spec string
Err bool
ErrorMessage string
}

func TestJSONSchema(t *testing.T, schema string, cases []TestCase) {
Expand All @@ -25,8 +26,9 @@ func TestJSONSchema(t *testing.T, schema string, cases []TestCase) {
var v any
require.NoErrorf(t, json.Unmarshal([]byte(tc.Spec), &v), "failed input:\n%s\n", tc.Spec)
err := validator.Validate(v)
if tc.Err {
if tc.Err || tc.ErrorMessage != "" {
require.Errorf(t, err, "failed input:\n%s\n", tc.Spec)
require.ErrorContains(t, err, tc.ErrorMessage)
} else {
require.NoErrorf(t, err, "failed input:\n%s\n", tc.Spec)
}
Expand Down
41 changes: 41 additions & 0 deletions jsonschema/testing_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package jsonschema

import (
"testing"
)

type schemaTestCase struct {
name string
schema string
cases []TestCase
}

func TestJSONSchemaCases(t *testing.T) {
tests := []schemaTestCase{
{
name: "simple",
schema: `{ "type": "object", "properties": { "name": { "type": "string" } } }`,
cases: []TestCase{
{
Name: "valid",
Spec: `{ "name": "test" }`,
},
{
Name: "invalid",
Spec: `{ "name": 1 }`,
Err: true,
},
{
Name: "invalid with error message",
Spec: `{ "name": 1 }`,
ErrorMessage: "expected string, but got number",
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
TestJSONSchema(t, tt.schema, tt.cases)
})
}
}