Skip to content

Commit

Permalink
Rename JsonRef.replace to JsonRef.replace_refs
Browse files Browse the repository at this point in the history
  • Loading branch information
gazpachoking committed May 17, 2013
1 parent fa8d0b2 commit d41cb40
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 35 deletions.
10 changes: 5 additions & 5 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ objects for Python (supporting 2.6+ including Python 3).
"reference": {"$ref": "#/data/1"}
}

# The JsonRef.replace class method will replace JSON references within the
# document
pprint(JsonRef.replace(document))
# The JsonRef.replace_refs class method will return a copy of the document
# with refs replaced by :class:`JsonRef` objects
pprint(JsonRef.replace_refs(document))

.. testoutput::

Expand All @@ -40,13 +40,13 @@ JSON reference objects have been substituted in your data structure, you can
use the data as if it does not contain references at all.

The primary interface to use :class:`JsonRef` objects is with the class method
:meth:`JsonRef.replace`. It will return a copy of an object you pass it, with
:meth:`JsonRef.replace_refs`. It will return a copy of an object you pass it, with
all JSON references contained replaced by :class:`JsonRef` objects. There are
several other options you can pass, seen below.

.. autoclass:: JsonRef(refobj, base_uri=None, loader=None, loader_kwargs=(), jsonschema=False, load_on_repr=True)

.. automethod:: replace(obj, base_uri=None, loader=None, loader_kwargs=(), jsonschema=False, load_on_repr=True)
.. automethod:: replace_refs(obj, base_uri=None, loader=None, loader_kwargs=(), jsonschema=False, load_on_repr=True)

:class:`JsonRef` instances proxy almost all operators and attributes to the
referent data, which will be loaded when first accessed. The following
Expand Down
20 changes: 10 additions & 10 deletions jsonref.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class JsonRef(LazyProxy):
__notproxied__ = ("__reference__",)

@classmethod
def replace(cls, obj, _recursive=False, **kwargs):
def replace_refs(cls, obj, _recursive=False, **kwargs):
"""
Returns a deep copy of `obj` with all contained JSON reference objects
replaced with :class:`JsonRef` instances.
Expand Down Expand Up @@ -112,12 +112,12 @@ def replace(cls, obj, _recursive=False, **kwargs):
path = list(kwargs.pop("_path", ()))
if isinstance(obj, Mapping):
obj = type(obj)(
(k, cls.replace(v, _path=path+[k], **kwargs))
(k, cls.replace_refs(v, _path=path+[k], **kwargs))
for k, v in iteritems(obj)
)
elif isinstance(obj, Sequence) and not isinstance(obj, basestring):
obj = type(obj)(
cls.replace(v, _path=path+[i], **kwargs) for i, v in enumerate(obj)
cls.replace_refs(v, _path=path+[i], **kwargs) for i, v in enumerate(obj)
)
if store_uri is not None:
store[store_uri] = obj
Expand Down Expand Up @@ -166,7 +166,7 @@ def callback(self):

kwargs = self._ref_kwargs
kwargs["base_uri"] = uri
base_doc = JsonRef.replace(base_doc, **kwargs)
base_doc = JsonRef.replace_refs(base_doc, **kwargs)
result = self.resolve_pointer(base_doc, fragment)
if hasattr(result, "__subject__"):
# TODO: Circular ref detection
Expand Down Expand Up @@ -309,15 +309,15 @@ def load(
:param fp: File-like object containing JSON document
:param **kwargs: This function takes any of the keyword arguments from
:meth:`JsonRef.replace`. Any other keyword arguments will be passed to
:meth:`JsonRef.replace_refs`. Any other keyword arguments will be passed to
:func:`json.load`
"""

if loader is None:
loader = functools.partial(jsonloader, **kwargs)

return JsonRef.replace(
return JsonRef.replace_refs(
json.load(fp, **kwargs),
base_uri=base_uri,
loader=loader,
Expand All @@ -336,15 +336,15 @@ def loads(
:param s: String containing JSON document
:param **kwargs: This function takes any of the keyword arguments from
:meth:`JsonRef.replace`. Any other keyword arguments will be passed to
:meth:`JsonRef.replace_refs`. Any other keyword arguments will be passed to
:func:`json.loads`
"""

if loader is None:
loader = functools.partial(jsonloader, **kwargs)

return JsonRef.replace(
return JsonRef.replace_refs(
json.loads(s, **kwargs),
base_uri=base_uri,
loader=loader,
Expand All @@ -362,7 +362,7 @@ def load_uri(
:param uri: URI to fetch the JSON from
:param **kwargs: This function takes any of the keyword arguments from
:meth:`JsonRef.replace`
:meth:`JsonRef.replace_refs`
"""

Expand All @@ -371,7 +371,7 @@ def load_uri(
if base_uri is None:
base_uri = uri

return JsonRef.replace(
return JsonRef.replace_refs(
loader(uri),
base_uri=base_uri,
loader=loader,
Expand Down
40 changes: 20 additions & 20 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,19 @@ def test_non_ref_object_throws_error(self):

def test_non_string_is_not_ref(self):
json = {"$ref": [1]}
assert JsonRef.replace(json) == json
assert JsonRef.replace_refs(json) == json

def test_local_object_ref(self):
json = {"a": 5, "b": {"$ref": "#/a"}}
assert JsonRef.replace(json)["b"] == json["a"]
assert JsonRef.replace_refs(json)["b"] == json["a"]

def test_local_array_ref(self):
json = [10, {"$ref": "#/0"}]
assert JsonRef.replace(json)[1] == json[0]
assert JsonRef.replace_refs(json)[1] == json[0]

def test_local_mixed_ref(self):
json = {"a": [5, 15], "b": {"$ref": "#/a/1"}}
assert JsonRef.replace(json)["b"] == json["a"][1]
assert JsonRef.replace_refs(json)["b"] == json["a"][1]

def test_local_nonexistent_ref(self):
json = {
Expand All @@ -54,7 +54,7 @@ def test_local_nonexistent_ref(self):
"c": {"$ref": "#/data/3"},
"d": {"$ref": "#/data/b"}
}
result = JsonRef.replace(json)
result = JsonRef.replace_refs(json)
for key in "abcd":
with pytest.raises(JsonRefError):
result[key].__subject__
Expand All @@ -66,35 +66,35 @@ def test_actual_references_not_copies(self):
"c": {"$ref": "#/a"},
"d": {"$ref": "#/c"}
}
result = JsonRef.replace(json)
result = JsonRef.replace_refs(json)
assert result["b"].__subject__ is result["a"]
assert result["c"].__subject__ is result["a"]
assert result["d"].__subject__ is result["a"]

def test_recursive_data_structures_local(self):
json = {"a": "foobar", "b": {"$ref": "#"}}
result = JsonRef.replace(json)
result = JsonRef.replace_refs(json)
assert result["b"].__subject__ is result

def test_recursive_data_structures_remote(self):
json1 = {"a": {"$ref": "/json2"}}
json2 = {"b": {"$ref": "/json1"}}
loader = mock.Mock(return_value=json2)
result = JsonRef.replace(json1, base_uri="/json1", loader=loader)
result = JsonRef.replace_refs(json1, base_uri="/json1", loader=loader)
assert result["a"]["b"].__subject__ is result
assert result["a"].__subject__ is result["a"]["b"]["a"].__subject__

def test_recursive_data_structures_remote_fragment(self):
json1 = {"a": {"$ref": "/json2#/b"}}
json2 = {"b": {"$ref": "/json1"}}
loader = mock.Mock(return_value=json2)
result = JsonRef.replace(json1, base_uri="/json1", loader=loader)
result = JsonRef.replace_refs(json1, base_uri="/json1", loader=loader)
assert result["a"].__subject__ is result

def test_custom_loader(self):
data = {"$ref": "foo"}
loader = mock.Mock(return_value=42)
result = JsonRef.replace(data, loader=loader)
result = JsonRef.replace_refs(data, loader=loader)
# Loading should not occur until we do something with result
assert loader.call_count == 0
# Make sure we got the right result
Expand All @@ -109,7 +109,7 @@ def test_custom_loader(self):
def test_base_uri_resolution(self):
json = {"$ref": "foo"}
loader = mock.Mock(return_value=17)
result = JsonRef.replace(
result = JsonRef.replace_refs(
json, base_uri="http://bar.com", loader=loader
)
assert result == 17
Expand All @@ -119,12 +119,12 @@ def test_repr_does_not_loop(self):
json = {"a": ["aoeu", {"$ref": "#/a"}]}
# By default python repr recursion detection should handle it
assert (
repr(JsonRef.replace(json)) ==
repr(JsonRef.replace_refs(json)) ==
"{'a': ['aoeu', [...]]}"
)
# If we turn of load_on_repr we should get a different representation
assert (
repr(JsonRef.replace(json, load_on_repr=False)) ==
repr(JsonRef.replace_refs(json, load_on_repr=False)) ==
"{'a': ['aoeu', JsonRef({'$ref': '#/a'})]}"
)

Expand All @@ -134,12 +134,12 @@ def test_repr_expands_deep_refs_by_default(self):
"d": {"$ref": "#/c"}, "e": {"$ref": "#/d"}, "f": {"$ref": "#/e"}
}
assert (
repr(sorted(JsonRef.replace(json).items())) ==
repr(sorted(JsonRef.replace_refs(json).items())) ==
"[('a', 'string'), ('b', 'string'), ('c', 'string'), "
"('d', 'string'), ('e', 'string'), ('f', 'string')]"
)
# Should not expand when set to False explicitly
result = JsonRef.replace(json, load_on_repr=False)
result = JsonRef.replace_refs(json, load_on_repr=False)
assert (
repr(sorted(result.items())) ==
"[('a', 'string'), ('b', JsonRef({'$ref': '#/a'})), "
Expand All @@ -157,7 +157,7 @@ def test_jsonschema_mode_local(self):
"c": {"$ref": "#/b"}
}
}
result = JsonRef.replace(json, jsonschema=True)
result = JsonRef.replace_refs(json, jsonschema=True)
assert result["a"]["c"] == json["a"]["b"]

def test_jsonschema_mode_remote(self):
Expand All @@ -176,7 +176,7 @@ def test_jsonschema_mode_remote(self):
}
counter = itertools.count()
loader = mock.Mock(side_effect=lambda uri: next(counter))
result = JsonRef.replace(json, loader=loader, base_uri=base_uri, jsonschema=True)
result = JsonRef.replace_refs(json, loader=loader, base_uri=base_uri, jsonschema=True)
assert result["a"] == 0
loader.assert_called_once_with("http://foo.com/otherSchema")
loader.reset_mock()
Expand All @@ -196,7 +196,7 @@ def test_jsonref_mode_non_string_is_not_id(self):
"$ref": "other"
}
loader = mock.Mock(return_value="aoeu")
result = JsonRef.replace(json, base_uri=base_uri, loader=loader)
result = JsonRef.replace_refs(json, base_uri=base_uri, loader=loader)
assert result == "aoeu"
loader.assert_called_once_with("http://foo.com/other")

Expand All @@ -205,7 +205,7 @@ class TestJsonRefErrors(object):

def test_basic_error_properties(self):
json = [{"$ref": "#/x"}]
result = JsonRef.replace(json)
result = JsonRef.replace_refs(json)
with pytest.raises(JsonRefError) as excinfo:
result[0].__subject__
e = excinfo.value
Expand All @@ -221,7 +221,7 @@ def test_nested_refs(self):
"b": {"$ref": "#/c"},
"c": {"$ref": "#/foo"},
}
result = JsonRef.replace(json)
result = JsonRef.replace_refs(json)
with pytest.raises(JsonRefError) as excinfo:
print(result["a"])
e = excinfo.value
Expand Down

0 comments on commit d41cb40

Please sign in to comment.