Skip to content

Commit

Permalink
preserve extra sibling attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
pkarman committed Oct 20, 2022
1 parent fc40b5d commit 6482e3a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
10 changes: 9 additions & 1 deletion jsonref.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import functools
import json
import warnings
import copy

try:
from collections.abc import Mapping, MutableMapping, Sequence
Expand Down Expand Up @@ -134,6 +135,10 @@ def __init__(
self.store = _store # Use the same object to be shared with children
if self.store is None:
self.store = _URIDict()
self.extra = None
if isinstance(refobj, Mapping) and len(refobj.keys()) > 1:
self.extra = copy.deepcopy(refobj)
del self.extra["$ref"]

@property
def _ref_kwargs(self):
Expand Down Expand Up @@ -192,7 +197,10 @@ def resolve_pointer(self, document, pointer):
except ValueError:
pass
try:
document = document[part]
if self.extra:
document = {**document[part], **self.extra}
else:
document = document[part]
except (TypeError, LookupError) as e:
self._error("Unresolvable JSON pointer: %r" % pointer, cause=e)
return document
Expand Down
28 changes: 26 additions & 2 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,38 @@ def test_actual_references_not_copies(self):
def test_ignored_sibling_attributes(self):
json = {
"a": {"type": "object", "properties": {"foo": {"type": "string"}}},
"b": {"extra": "foobar", "$ref": "#/a"},
"b": {"extra": "foobar", "$ref": "#/a"},
"c": {"extra": { "more": "bar", "$ref": "#/a"} },
}
result = JsonRef.replace_refs(json)
assert result["b"].__subject__ is {
# because we deepcopy, use '==' instead of 'is"
assert result["b"] == {
"extra": "foobar",
"type": "object",
"properties": {"foo": {"type": "string"}},
}
assert result["c"] == {
"extra": {
"more": "bar",
"type": "object",
"properties": {"foo": {"type": "string"}}
}
}

def test_extra_sibling_attributes_list_ref(self):
json = {
"a": ["target"],
"b": {"extra": "foobar", "$ref": "#/a"},
}
result = JsonRef.replace_refs(json)
with pytest.raises(JsonRefError) as excinfo:
result["b"].__subject__
e = excinfo.value
assert e.reference == json["b"]
assert e.uri == "#/a"
assert e.base_uri == ""
assert e.path == ["b"]
assert type(e.cause) == TypeError

def test_recursive_data_structures_local(self):
json = {"a": "foobar", "b": {"$ref": "#"}}
Expand Down

0 comments on commit 6482e3a

Please sign in to comment.