diff --git a/schema.go b/schema.go index 5cc80b2..fe13f39 100644 --- a/schema.go +++ b/schema.go @@ -15,6 +15,16 @@ import ( "net/url" ) +// Must turns a JSON string into a *RootSchema, panicing if parsing fails. +// Useful for declaring Schemas in Go code. +func Must(jsonString string) *RootSchema { + rs := &RootSchema{} + if err := rs.UnmarshalJSON([]byte(jsonString)); err != nil { + panic(err) + } + return rs +} + // DefaultSchemaPool is a package level map of schemas by identifier // remote references are cached here. var DefaultSchemaPool = Definitions{} diff --git a/schema_test.go b/schema_test.go index 1c47aa3..83e77ef 100644 --- a/schema_test.go +++ b/schema_test.go @@ -69,6 +69,32 @@ func ExampleBasic() { // "friends" property ["lastName" value is required] } +func TestMust(t *testing.T) { + defer func() { + if r := recover(); r != nil { + if err, ok := r.(error); ok { + if err.Error() != "unexpected end of JSON input" { + t.Errorf("expected panic error to equal: %s", "unexpected end of JSON input") + } + } else { + t.Errorf("must paniced with a non-error") + } + } else { + t.Errorf("expected invalid call to Must to panic") + } + }() + + // Valid call to Must shouldn't panic + rs := Must(`{}`) + if rs == nil { + t.Errorf("expected parse of empty schema to return *RootSchema, got nil") + return + } + + // This should panic, checked in defer above + Must(``) +} + func TestDraft3(t *testing.T) { runJSONTests(t, []string{ "testdata/draft3/additionalItems.json",