Skip to content

Commit

Permalink
feat: added Must func for easier schema declaration in Go.
Browse files Browse the repository at this point in the history
declaring Schemas with go structs is cumbersome & painful, so I've
added this Must function that follows a pattern set forth in
regexp.MustCompile.
Must accepts a string representation of a json schema, returns
a *RootSchema on successful parse, and panics if there's an error.
  • Loading branch information
b5 committed Jan 22, 2018
1 parent 6bed992 commit 2874aff
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
10 changes: 10 additions & 0 deletions schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}
Expand Down
26 changes: 26 additions & 0 deletions schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down

0 comments on commit 2874aff

Please sign in to comment.