From ca0e82f6c18e0bba05fd5c25cb92b33dc9f679fb Mon Sep 17 00:00:00 2001 From: Dustin Long Date: Fri, 1 Mar 2019 15:53:06 -0500 Subject: [PATCH] fix(jsonschema): Handle empty url fragment "#", add unit tests. --- schema.go | 13 ++++++------- schema_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 7 deletions(-) diff --git a/schema.go b/schema.go index 4de0351..ee1f939 100644 --- a/schema.go +++ b/schema.go @@ -12,7 +12,6 @@ import ( "fmt" "net/http" "net/url" - "strings" "github.com/qri-io/jsonpointer" ) @@ -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 } } } diff --git a/schema_test.go b/schema_test.go index 7e377cf..cecad8d 100644 --- a/schema_test.go +++ b/schema_test.go @@ -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 {