Merge pull request #8 from johandorland/master
Fix inheritance if the child's fragment is empty
diff --git a/reference.go b/reference.go
index d4d2eca..6457291 100644
--- a/reference.go
+++ b/reference.go
@@ -27,11 +27,12 @@
import (
"errors"
- "github.com/xeipuuv/gojsonpointer"
"net/url"
"path/filepath"
"runtime"
"strings"
+
+ "github.com/xeipuuv/gojsonpointer"
)
const (
@@ -124,16 +125,21 @@
// Creates a new reference from a parent and a child
// If the child cannot inherit from the parent, an error is returned
func (r *JsonReference) Inherits(child JsonReference) (*JsonReference, error) {
- childUrl := child.GetUrl()
- parentUrl := r.GetUrl()
- if childUrl == nil {
+ if child.GetUrl() == nil {
return nil, errors.New("childUrl is nil!")
}
- if parentUrl == nil {
+
+ if r.GetUrl() == nil {
return nil, errors.New("parentUrl is nil!")
}
- ref, err := NewJsonReference(parentUrl.ResolveReference(childUrl).String())
+ // Get a copy of the parent url to make sure we do not modify the original.
+ // URL reference resolving fails if the fragment of the child is empty, but the parent's is not.
+ // The fragment of the child must be used, so the fragment of the parent is manually removed.
+ parentUrl := *r.GetUrl()
+ parentUrl.Fragment = ""
+
+ ref, err := NewJsonReference(parentUrl.ResolveReference(child.GetUrl()).String())
if err != nil {
return nil, err
}
diff --git a/reference_test.go b/reference_test.go
index 4f6e773..7380473 100644
--- a/reference_test.go
+++ b/reference_test.go
@@ -245,6 +245,24 @@
}
}
+func TestInheritsEmptyFragment(t *testing.T) {
+ in1 := "#a"
+ in2 := ""
+
+ r1, _ := NewJsonReference(in1)
+ r2, _ := NewJsonReference(in2)
+
+ result, err := r1.Inherits(r2)
+
+ if err != nil {
+ t.Errorf("Inherits(%s,%s) should not fail. Error: %s", r1.String(), r2.String(), err.Error())
+ }
+
+ if result.String() != in2 {
+ t.Errorf("Inherits(%s,%s) should be empty but is %s", in1, in2, result)
+ }
+}
+
func TestFileScheme(t *testing.T) {
in1 := "file:///Users/mac/1.json#a"
@@ -266,7 +284,7 @@
}
if r1.IsCanonical() != true {
- t.Errorf("NewJsonReference(%v)::IsCanonical %v expect %v", in1, r1.IsCanonical, true)
+ t.Errorf("NewJsonReference(%v)::IsCanonical %v expect %v", in1, r1.IsCanonical(), true)
}
result, err := r1.Inherits(r2)