Skip to content

Commit

Permalink
fix(jsonschema): Handle empty url fragment "#", add unit tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
dustmop committed Mar 1, 2019
1 parent 6e3faa5 commit ca0e82f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 7 deletions.
13 changes: 6 additions & 7 deletions schema.go
Expand Up @@ -12,7 +12,6 @@ import (
"fmt"
"net/http"
"net/url"
"strings"

"github.com/qri-io/jsonpointer"
)
Expand Down Expand Up @@ -91,13 +90,13 @@ func (rs *RootSchema) UnmarshalJSON(data []byte) error {
ids[sch.ID] = sch
// For the record, I think this is ridiculous.
if u, err := url.Parse(sch.ID); err == nil {
// This is if the identifier is defined as a reference (with #)
// i.e. #/properties/firstName
// in this case, u.Fragment will have /properties/firstName
if strings.HasPrefix(sch.ID, "#") {
ids[u.Fragment[1:]] = sch
} else {
if len(u.Path) >= 1 {
ids[u.Path[1:]] = sch
} else if len(u.Fragment) >= 1 {
// This handles if the identifier is defined as only a fragment (with #)
// i.e. #/properties/firstName
// in this case, u.Fragment will have /properties/firstName
ids[u.Fragment[1:]] = sch
}
}
}
Expand Down
35 changes: 35 additions & 0 deletions schema_test.go
Expand Up @@ -125,6 +125,41 @@ func TestTopLevelType(t *testing.T) {
}
}

func TestParseUrl(t *testing.T) {
// Easy case, id is a standard URL
schemaObject := []byte(`{
"title": "Car",
"type": "object",
"$id": "http://example.com/root.json"
}`)
rs := &RootSchema{}
if err := json.Unmarshal(schemaObject, rs); err != nil {
panic("unmarshal schema: " + err.Error())
}

// Tricky case, id is only a URL fragment
schemaObject = []byte(`{
"title": "Car",
"type": "object",
"$id": "#/properites/firstName"
}`)
rs = &RootSchema{}
if err := json.Unmarshal(schemaObject, rs); err != nil {
panic("unmarshal schema: " + err.Error())
}

// Another tricky case, id is only an empty fragment
schemaObject = []byte(`{
"title": "Car",
"type": "object",
"$id": "#"
}`)
rs = &RootSchema{}
if err := json.Unmarshal(schemaObject, rs); err != nil {
panic("unmarshal schema: " + err.Error())
}
}

func TestMust(t *testing.T) {
defer func() {
if r := recover(); r != nil {
Expand Down

0 comments on commit ca0e82f

Please sign in to comment.