Skip to content

Commit 21cf431

Browse files
committed
Test coverage.
1 parent fed17ad commit 21cf431

3 files changed

Lines changed: 274 additions & 18 deletions

File tree

‎jsonpath/patch.py‎

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
from .pointer import UNDEFINED
2424
from .pointer import JSONPointer
2525

26+
# TODO: to_json()
27+
2628

2729
class Op(ABC):
2830
"""One of the JSON Patch operations."""
@@ -102,7 +104,9 @@ def apply(
102104
raise JSONPatchError("can't remove nonexistent property")
103105
del parent[self.path.parts[-1]]
104106
else:
105-
raise JSONPatchError(f"unexpected operation on {parent.__class__.__name__}")
107+
raise JSONPatchError(
108+
f"unexpected operation on {parent.__class__.__name__!r}"
109+
)
106110
return data
107111

108112

@@ -134,7 +138,9 @@ def apply(
134138
raise JSONPatchError("can't replace nonexistent property")
135139
parent[self.path.parts[-1]] = self.value
136140
else:
137-
raise JSONPatchError(f"unexpected operation on {parent.__class__.__name__}")
141+
raise JSONPatchError(
142+
f"unexpected operation on {parent.__class__.__name__!r}"
143+
)
138144
return data
139145

140146

@@ -159,7 +165,7 @@ def apply(
159165
source_parent, source_obj = self.source.resolve_parent(data)
160166

161167
if source_obj is UNDEFINED:
162-
raise JSONPatchError("source does not exist")
168+
raise JSONPatchError("source object does not exist")
163169

164170
if isinstance(source_parent, MutableSequence):
165171
del source_parent[int(self.source.parts[-1])]
@@ -202,7 +208,7 @@ def apply(
202208
source_parent, source_obj = self.source.resolve_parent(data)
203209

204210
if source_obj is UNDEFINED:
205-
raise JSONPatchError("source does not exist")
211+
raise JSONPatchError("source object does not exist")
206212

207213
dest_parent, dest_obj = self.dest.resolve_parent(data)
208214

@@ -279,25 +285,23 @@ def __init__(
279285
self.unicode_escape = unicode_escape
280286
self.uri_decode = uri_decode
281287
if ops:
282-
self._build(self._load(ops))
288+
self._load(ops)
283289

284-
def _load(
285-
self, patch: Union[str, IOBase, Iterable[Mapping[str, object]]]
286-
) -> List[Mapping[str, object]]:
290+
def _load(self, patch: Union[str, IOBase, Iterable[Mapping[str, object]]]) -> None:
287291
if isinstance(patch, IOBase):
288292
_patch = json.loads(patch.read())
289293
elif isinstance(patch, str):
290294
_patch = json.loads(patch)
291295
else:
292-
_patch = list(patch)
296+
_patch = patch
293297

294-
if not isinstance(_patch, list):
298+
try:
299+
self._build(_patch)
300+
except TypeError as err:
295301
raise JSONPatchError(
296-
"expected an array of patch operations, "
297-
f"found {_patch.__class__.__name__}"
298-
)
299-
300-
return _patch
302+
"expected a sequence of patch operations, "
303+
f"found {_patch.__class__.__name__!r}"
304+
) from err
301305

302306
def _build(self, patch: Iterable[Mapping[str, object]]) -> None:
303307
for i, operation in enumerate(patch):
@@ -349,8 +353,8 @@ def _op_pointer(
349353

350354
if not isinstance(pointer, str):
351355
raise JSONPatchError(
352-
"expected a JSON Pointer string,"
353-
f"found {pointer.__class__.__name__} "
356+
f"expected a JSON Pointer string for {key!r}, "
357+
f"found {pointer.__class__.__name__!r} "
354358
f"({op}:{i})"
355359
)
356360

@@ -364,7 +368,7 @@ def _op_value(
364368
try:
365369
return operation[key]
366370
except KeyError as err:
367-
raise JSONPatchError(f"missing property {op!r} ({op}:{i})") from err
371+
raise JSONPatchError(f"missing property {key!r} ({op}:{i})") from err
368372

369373
def _ensure_pointer(self, path: Path) -> JSONPointer:
370374
if isinstance(path, str):

‎jsonpath/pointer.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,8 +144,10 @@ def _getitem(self, obj: Any, key: Any) -> Any: # noqa: PLR0912
144144
return getitem(obj, int(key))
145145
except IndexError as index_err:
146146
raise JSONPointerIndexError(int(key)) from index_err
147+
# TODO: include key and truncated obj
147148
raise JSONPointerTypeError(str(err)) from err
148149
except IndexError as err:
150+
# TODO: include obj name/type
149151
raise JSONPointerIndexError(int(key)) from err
150152

151153
def resolve(

‎tests/test_json_patch.py‎

Lines changed: 250 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,250 @@
1+
"""JSON Patch test cases."""
2+
3+
import json
4+
import re
5+
from collections.abc import Mapping
6+
from io import StringIO
7+
from typing import Any
8+
from typing import Iterator
9+
10+
import pytest
11+
12+
from jsonpath import JSONPatch
13+
from jsonpath import patch
14+
from jsonpath.exceptions import JSONPatchError
15+
16+
17+
class MockMapping(Mapping[str, str]):
18+
def __getitem__(self, __key: Any) -> Any:
19+
return "foo"
20+
21+
def __iter__(self) -> Iterator[str]:
22+
return iter(["foo"])
23+
24+
def __len__(self) -> int:
25+
return 1
26+
27+
28+
def test_add_to_immutable_mapping() -> None:
29+
patch = JSONPatch().add("/foo/bar", "baz")
30+
with pytest.raises(
31+
JSONPatchError, match=re.escape("unexpected operation on 'MockMapping' (add:0)")
32+
):
33+
patch.apply({"foo": MockMapping()})
34+
35+
36+
def test_remove_root() -> None:
37+
patch = JSONPatch().remove("")
38+
with pytest.raises(JSONPatchError, match=re.escape("can't remove root (remove:0)")):
39+
patch.apply({"foo": "bar"})
40+
41+
42+
def test_remove_nonexistent_value() -> None:
43+
patch = JSONPatch().remove("/baz")
44+
with pytest.raises(
45+
JSONPatchError, match=re.escape("can't remove nonexistent property (remove:0)")
46+
):
47+
patch.apply({"foo": "bar"})
48+
49+
50+
def test_remove_array_end() -> None:
51+
patch = JSONPatch().remove("/foo/-")
52+
with pytest.raises(
53+
JSONPatchError, match=re.escape("can't remove nonexistent item (remove:0)")
54+
):
55+
patch.apply({"foo": [1, 2, 3]})
56+
57+
58+
def test_remove_from_immutable_mapping() -> None:
59+
patch = JSONPatch().remove("/bar/foo")
60+
with pytest.raises(
61+
JSONPatchError,
62+
match=re.escape("unexpected operation on 'MockMapping' (remove:0)"),
63+
):
64+
patch.apply({"bar": MockMapping()})
65+
66+
67+
def test_replace_root() -> None:
68+
assert patch.apply(
69+
[{"op": "replace", "path": "", "value": [1, 2, 3]}], {"foo": "bar"}
70+
) == [1, 2, 3]
71+
72+
73+
def test_replace_a_nonexistent_item() -> None:
74+
with pytest.raises(
75+
JSONPatchError, match=re.escape("can't replace nonexistent item (replace:0)")
76+
):
77+
patch.apply(
78+
[{"op": "replace", "path": "/foo/99", "value": 5}], {"foo": [1, 2, 3]}
79+
)
80+
81+
82+
def test_replace_a_nonexistent_value() -> None:
83+
with pytest.raises(
84+
JSONPatchError,
85+
match=re.escape("can't replace nonexistent property (replace:0)"),
86+
):
87+
patch.apply(
88+
[{"op": "replace", "path": "/foo/bar", "value": 5}], {"foo": {"baz": 10}}
89+
)
90+
91+
92+
def test_replace_immutable_mapping() -> None:
93+
with pytest.raises(
94+
JSONPatchError,
95+
match=re.escape("unexpected operation on 'MockMapping' (replace:0)"),
96+
):
97+
patch.apply(
98+
[{"op": "replace", "path": "/bar/foo", "value": "baz"}],
99+
{"bar": MockMapping()},
100+
)
101+
102+
103+
def test_move_to_child() -> None:
104+
with pytest.raises(
105+
JSONPatchError,
106+
match=re.escape("can't move object to one of its own children (move:0)"),
107+
):
108+
patch.apply(
109+
[{"op": "move", "from": "/foo/bar", "path": "/foo/bar/baz"}],
110+
{"foo": {"bar": {"baz": [1, 2, 3]}}},
111+
)
112+
113+
114+
def test_move_nonexistent_value() -> None:
115+
with pytest.raises(
116+
JSONPatchError, match=re.escape("source object does not exist (move:0)")
117+
):
118+
JSONPatch().move(from_="/foo/bar", path="/bar").apply({"foo": {"baz": 1}})
119+
120+
121+
def test_move_to_root() -> None:
122+
patch = JSONPatch().move(from_="/foo", path="")
123+
assert patch.apply({"foo": {"bar": "baz"}}) == {"bar": "baz"}
124+
125+
126+
def test_move_to_immutable_mapping() -> None:
127+
patch = JSONPatch().move(from_="/foo/bar", path="/baz/bar")
128+
with pytest.raises(
129+
JSONPatchError,
130+
match=re.escape("unexpected operation on 'MockMapping' (move:0)"),
131+
):
132+
patch.apply({"foo": {"bar": "hello"}, "baz": MockMapping()})
133+
134+
135+
def test_copy_nonexistent_value() -> None:
136+
with pytest.raises(
137+
JSONPatchError, match=re.escape("source object does not exist (copy:0)")
138+
):
139+
JSONPatch().copy(from_="/foo/bar", path="/bar").apply({"foo": {"baz": "hello"}})
140+
141+
142+
def test_copy_to_root() -> None:
143+
patch = JSONPatch().copy(from_="/foo/bar", path="")
144+
assert patch.apply({"foo": {"bar": [1, 2, 3]}}) == [1, 2, 3]
145+
146+
147+
def test_copy_to_immutable_mapping() -> None:
148+
with pytest.raises(
149+
JSONPatchError,
150+
match=re.escape("unexpected operation on 'MockMapping' (copy:0)"),
151+
):
152+
JSONPatch().copy(from_="/foo/bar", path="/baz/bar").apply(
153+
{"foo": {"bar": [1, 2, 3]}, "baz": MockMapping()}
154+
)
155+
156+
157+
def test_patch_from_file_like() -> None:
158+
patch_doc = StringIO(
159+
json.dumps(
160+
[
161+
{"op": "add", "path": "", "value": {"foo": {}}},
162+
{"op": "add", "path": "/foo", "value": {"bar": []}},
163+
{"op": "add", "path": "/foo/bar/-", "value": 1},
164+
]
165+
)
166+
)
167+
168+
patch = JSONPatch(patch_doc)
169+
assert patch.apply({}) == {"foo": {"bar": [1]}}
170+
171+
172+
def test_patch_from_string() -> None:
173+
patch_doc = json.dumps(
174+
[
175+
{"op": "add", "path": "", "value": {"foo": {}}},
176+
{"op": "add", "path": "/foo", "value": {"bar": []}},
177+
{"op": "add", "path": "/foo/bar/-", "value": 1},
178+
]
179+
)
180+
181+
patch = JSONPatch(patch_doc)
182+
assert patch.apply({}) == {"foo": {"bar": [1]}}
183+
184+
185+
def test_unexpected_patch_ops() -> None:
186+
with pytest.raises(
187+
JSONPatchError,
188+
match=re.escape("expected a sequence of patch operations, found 'MockMapping'"),
189+
):
190+
JSONPatch(MockMapping()) # type: ignore
191+
192+
193+
def test_construct_missing_op() -> None:
194+
with pytest.raises(JSONPatchError, match=re.escape("missing 'op' member at op 0")):
195+
JSONPatch([{}])
196+
197+
198+
def test_construct_unknown_op() -> None:
199+
msg = (
200+
"expected 'op' to be one of 'add', 'remove', 'replace', "
201+
"'move', 'copy' or 'test' (foo:0)"
202+
)
203+
with pytest.raises(JSONPatchError, match=re.escape(msg)):
204+
JSONPatch([{"op": "foo"}])
205+
206+
207+
def test_construct_missing_pointer() -> None:
208+
msg = "missing property 'path' (add:0)"
209+
with pytest.raises(JSONPatchError, match=re.escape(msg)):
210+
JSONPatch([{"op": "add", "value": "foo"}])
211+
212+
213+
def test_construct_missing_value() -> None:
214+
msg = "missing property 'value' (add:0)"
215+
with pytest.raises(JSONPatchError, match=re.escape(msg)):
216+
JSONPatch([{"op": "add", "path": "/foo"}])
217+
218+
219+
def test_construct_pointer_not_a_string() -> None:
220+
msg = "expected a JSON Pointer string for 'path', found 'int' (add:0)"
221+
with pytest.raises(JSONPatchError, match=re.escape(msg)):
222+
JSONPatch([{"op": "add", "path": 5, "value": "foo"}])
223+
224+
225+
def test_apply_to_str() -> None:
226+
patch_doc = json.dumps(
227+
[
228+
{"op": "add", "path": "", "value": {"foo": {}}},
229+
{"op": "add", "path": "/foo", "value": {"bar": []}},
230+
{"op": "add", "path": "/foo/bar/-", "value": 1},
231+
]
232+
)
233+
234+
data_doc = json.dumps({})
235+
assert patch.apply(patch_doc, data_doc) == {"foo": {"bar": [1]}}
236+
237+
238+
def test_apply_to_file_like() -> None:
239+
patch_doc = StringIO(
240+
json.dumps(
241+
[
242+
{"op": "add", "path": "", "value": {"foo": {}}},
243+
{"op": "add", "path": "/foo", "value": {"bar": []}},
244+
{"op": "add", "path": "/foo/bar/-", "value": 1},
245+
]
246+
)
247+
)
248+
249+
data_doc = StringIO(json.dumps({}))
250+
assert patch.apply(patch_doc, data_doc) == {"foo": {"bar": [1]}}

0 commit comments

Comments
 (0)