Skip to content

Commit fed17ad

Browse files
committed
Better exception messages.
1 parent 177d01a commit fed17ad

3 files changed

Lines changed: 131 additions & 61 deletions

File tree

‎jsonpath/patch.py‎

Lines changed: 121 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import json
66
from abc import ABC
77
from abc import abstractmethod
8-
from functools import reduce
98
from io import IOBase
109
from typing import Iterable
1110
from typing import List
@@ -18,15 +17,18 @@
1817
from .exceptions import JSONPatchError
1918
from .exceptions import JSONPatchTestFailure
2019
from .exceptions import JSONPointerError
20+
from .exceptions import JSONPointerIndexError
21+
from .exceptions import JSONPointerKeyError
22+
from .exceptions import JSONPointerTypeError
2123
from .pointer import UNDEFINED
2224
from .pointer import JSONPointer
2325

24-
# TODO: review all error messages
25-
2626

2727
class Op(ABC):
2828
"""One of the JSON Patch operations."""
2929

30+
name = "base"
31+
3032
@abstractmethod
3133
def apply(
3234
self, data: Union[MutableSequence[object], MutableMapping[str, object]]
@@ -39,6 +41,8 @@ class OpAdd(Op):
3941

4042
__slots__ = ("path", "value")
4143

44+
name = "add"
45+
4246
def __init__(self, path: JSONPointer, value: object) -> None:
4347
self.path = path
4448
self.value = value
@@ -66,7 +70,7 @@ def apply(
6670
parent[target] = self.value
6771
else:
6872
raise JSONPatchError(
69-
f"unexpected add operation on {parent.__class__.__name__!r}"
73+
f"unexpected operation on {parent.__class__.__name__!r}"
7074
)
7175
return data
7276

@@ -76,6 +80,8 @@ class OpRemove(Op):
7680

7781
__slots__ = ("path",)
7882

83+
name = "remove"
84+
7985
def __init__(self, path: JSONPointer) -> None:
8086
self.path = path
8187

@@ -96,9 +102,7 @@ def apply(
96102
raise JSONPatchError("can't remove nonexistent property")
97103
del parent[self.path.parts[-1]]
98104
else:
99-
raise JSONPatchError(
100-
f"unexpected remove operation on {parent.__class__.__name__}"
101-
)
105+
raise JSONPatchError(f"unexpected operation on {parent.__class__.__name__}")
102106
return data
103107

104108

@@ -107,6 +111,8 @@ class OpReplace(Op):
107111

108112
__slots__ = ("path", "value")
109113

114+
name = "replace"
115+
110116
def __init__(self, path: JSONPointer, value: object) -> None:
111117
self.path = path
112118
self.value = value
@@ -121,16 +127,14 @@ def apply(
121127

122128
if isinstance(parent, MutableSequence):
123129
if obj is UNDEFINED:
124-
raise JSONPatchError("can't remove nonexistent item")
130+
raise JSONPatchError("can't replace nonexistent item")
125131
parent[int(self.path.parts[-1])] = self.value
126132
elif isinstance(parent, MutableMapping):
127133
if obj is UNDEFINED:
128-
raise JSONPatchError("can't remove nonexistent property")
134+
raise JSONPatchError("can't replace nonexistent property")
129135
parent[self.path.parts[-1]] = self.value
130136
else:
131-
raise JSONPatchError(
132-
f"unexpected remove operation on {parent.__class__.__name__}"
133-
)
137+
raise JSONPatchError(f"unexpected operation on {parent.__class__.__name__}")
134138
return data
135139

136140

@@ -139,6 +143,8 @@ class OpMove(Op):
139143

140144
__slots__ = ("source", "dest")
141145

146+
name = "move"
147+
142148
def __init__(self, from_: JSONPointer, path: JSONPointer) -> None:
143149
self.source = from_
144150
self.dest = path
@@ -172,7 +178,7 @@ def apply(
172178
dest_parent[self.dest.parts[-1]] = source_obj
173179
else:
174180
raise JSONPatchError(
175-
f"unexpected move operation on {dest_parent.__class__.__name__!r}"
181+
f"unexpected operation on {dest_parent.__class__.__name__!r}"
176182
)
177183

178184
return data
@@ -183,6 +189,8 @@ class OpCopy(Op):
183189

184190
__slots__ = ("source", "dest")
185191

192+
name = "copy"
193+
186194
def __init__(self, from_: JSONPointer, path: JSONPointer) -> None:
187195
self.source = from_
188196
self.dest = path
@@ -208,7 +216,7 @@ def apply(
208216
dest_parent[self.dest.parts[-1]] = copy.deepcopy(source_obj)
209217
else:
210218
raise JSONPatchError(
211-
f"unexpected copy operation on {dest_parent.__class__.__name__!r}"
219+
f"unexpected operation on {dest_parent.__class__.__name__!r}"
212220
)
213221

214222
return data
@@ -219,6 +227,8 @@ class OpTest(Op):
219227

220228
__slots__ = ("path", "value")
221229

230+
name = "test"
231+
222232
def __init__(self, path: JSONPointer, value: object) -> None:
223233
self.path = path
224234
self.value = value
@@ -240,7 +250,23 @@ def apply(
240250

241251

242252
class JSONPatch:
243-
"""A JSON Patch, as per RFC 6902."""
253+
"""Modify JSON-like data with JSON Patch.
254+
255+
RFC 6902 defines operations to manipulate a JSON document. `JSONPatch`
256+
supports parsing and applying standard JSON Patch formatted operations,
257+
and provides a Python builder API following the same semantics as RFC 6902.
258+
259+
Arguments:
260+
ops: A JSON Patch formatted document or equivalent Python objects.
261+
unicode_escape: If `True`, UTF-16 escape sequences will be decoded
262+
before parsing JSON pointers.
263+
uri_decode: If `True`, JSON pointers will be unescaped using _urllib_
264+
before being parsed.
265+
266+
Raises:
267+
JSONPatchError: If _ops_ is given and any of the provided operations
268+
is malformed.
269+
"""
244270

245271
def __init__(
246272
self,
@@ -263,7 +289,7 @@ def _load(
263289
elif isinstance(patch, str):
264290
_patch = json.loads(patch)
265291
else:
266-
_patch = patch
292+
_patch = list(patch)
267293

268294
if not isinstance(_patch, list):
269295
raise JSONPatchError(
@@ -310,7 +336,7 @@ def _build(self, patch: Iterable[Mapping[str, object]]) -> None:
310336
else:
311337
raise JSONPatchError(
312338
"expected 'op' to be one of 'add', 'remove', 'replace', "
313-
f"'move', 'copy' or 'test' at op {i}, found {op!r}"
339+
f"'move', 'copy' or 'test' ({op}:{i})"
314340
)
315341

316342
def _op_pointer(
@@ -319,14 +345,13 @@ def _op_pointer(
319345
try:
320346
pointer = operation[key]
321347
except KeyError as err:
322-
raise JSONPatchError(
323-
f"missing property {op!r} for op {op!r} at {i}"
324-
) from err
348+
raise JSONPatchError(f"missing property {key!r} ({op}:{i})") from err
325349

326350
if not isinstance(pointer, str):
327351
raise JSONPatchError(
328-
f"expected a JSON Pointer string for op {op!r} at {i}, "
329-
f"found {pointer.__class__.__name__}"
352+
"expected a JSON Pointer string,"
353+
f"found {pointer.__class__.__name__} "
354+
f"({op}:{i})"
330355
)
331356

332357
return JSONPointer(
@@ -339,9 +364,7 @@ def _op_value(
339364
try:
340365
return operation[key]
341366
except KeyError as err:
342-
raise JSONPatchError(
343-
f"missing property {op!r} for op {op!r} at {i}"
344-
) from err
367+
raise JSONPatchError(f"missing property {op!r} ({op}:{i})") from err
345368

346369
def _ensure_pointer(self, path: Path) -> JSONPointer:
347370
if isinstance(path, str):
@@ -354,15 +377,7 @@ def _ensure_pointer(self, path: Path) -> JSONPointer:
354377
return path
355378

356379
def add(self: Self, path: Path, value: object) -> Self:
357-
"""Add _value_ to _path_.
358-
359-
If _path_ specifies an index into an array-like object, _value_ will
360-
be inserted into the array at that index. All other items in the array
361-
will be shifted to the right.
362-
363-
If _path_ specifies a JSON object property, _value_ will be assigned to
364-
that property, potentially overwriting a value if the property already
365-
exists.
380+
"""Append an _add_ operation to this patch.
366381
367382
Arguments:
368383
path: A string representation of a JSON Pointer, or one that has
@@ -378,7 +393,7 @@ def add(self: Self, path: Path, value: object) -> Self:
378393
return self
379394

380395
def remove(self: Self, path: Path) -> Self:
381-
"""Remove the value at _path_.
396+
"""Append a _remove_ operation to this patch.
382397
383398
Arguments:
384399
path: A string representation of a JSON Pointer, or one that has
@@ -393,7 +408,7 @@ def remove(self: Self, path: Path) -> Self:
393408
return self
394409

395410
def replace(self: Self, path: Path, value: object) -> Self:
396-
"""Replace the object at _path_ with _value_.
411+
"""Append a _replace_ operation to this patch.
397412
398413
Arguments:
399414
path: A string representation of a JSON Pointer, or one that has
@@ -409,7 +424,7 @@ def replace(self: Self, path: Path, value: object) -> Self:
409424
return self
410425

411426
def move(self: Self, from_: Path, path: Path) -> Self:
412-
"""Move the object at _source_ to _dest_.
427+
"""Append a _move_ operation to this patch.
413428
414429
Arguments:
415430
from_: A string representation of a JSON Pointer, or one that has
@@ -427,7 +442,7 @@ def move(self: Self, from_: Path, path: Path) -> Self:
427442
return self
428443

429444
def copy(self: Self, from_: Path, path: Path) -> Self:
430-
"""Copy the object from _source_ to _dest_.
445+
"""Append a _copy_ operation to this patch.
431446
432447
Arguments:
433448
from_: A string representation of a JSON Pointer, or one that has
@@ -445,7 +460,7 @@ def copy(self: Self, from_: Path, path: Path) -> Self:
445460
return self
446461

447462
def test(self: Self, path: Path, value: object) -> Self:
448-
"""Check that the object at _path_ is equal to _value_.
463+
"""Append a test operation to this patch.
449464
450465
Arguments:
451466
path: A string representation of a JSON Pointer, or one that has
@@ -466,12 +481,13 @@ def apply(
466481
) -> Union[MutableSequence[object], MutableMapping[str, object]]:
467482
"""Apply all operations from this patch to _data_.
468483
469-
_data_ is modified in-place. You should make a copy before calling
470-
_apply()_ if you need to retain original data.
484+
If _data_ is a string or file-like object, it will be loaded with
485+
_json.loads_. Otherwise _data_ should be a JSON-like data structure and
486+
will be modified in-place.
471487
472-
Even though _data_ is modified in-place, we return modified data too.
473-
This is to allow for replacing _data's_ root element, which is allowed
474-
by some patch operations.
488+
When modifying _data_ in-place, we return modified data too. This is
489+
to allow for replacing _data's_ root element, which is allowed by some
490+
patch operations.
475491
476492
Arguments:
477493
data: The target JSON "document" or equivalent Python objects.
@@ -493,13 +509,64 @@ def apply(
493509
else:
494510
_data = data
495511

496-
def _apply(
497-
_dat: Union[MutableSequence[object], MutableMapping[str, object]],
498-
op: Op,
499-
) -> Union[MutableSequence[object], MutableMapping[str, object]]:
500-
return op.apply(_dat)
501-
502-
try:
503-
return reduce(_apply, self.ops, _data)
504-
except JSONPointerError as err:
505-
raise JSONPatchError(str(err)) from err
512+
for i, op in enumerate(self.ops):
513+
try:
514+
_data = op.apply(_data)
515+
except JSONPatchTestFailure as err:
516+
raise JSONPatchTestFailure(f"test failed ({op.name}:{i})") from err
517+
except JSONPointerKeyError as err:
518+
raise JSONPatchError(
519+
f"pointer key error {err} ({op.name}:{i})"
520+
) from err
521+
except JSONPointerIndexError as err:
522+
raise JSONPatchError(
523+
f"pointer index error {err} ({op.name}:{i})"
524+
) from err
525+
except JSONPointerTypeError as err:
526+
raise JSONPatchError(
527+
f"pointer type error {err} ({op.name}:{i})"
528+
) from err
529+
except (JSONPointerError, JSONPatchError) as err:
530+
raise JSONPatchError(f"{err} ({op.name}:{i})") from err
531+
return _data
532+
533+
534+
def apply(
535+
patch: Union[str, IOBase, Iterable[Mapping[str, object]], None],
536+
data: Union[str, IOBase, MutableSequence[object], MutableMapping[str, object]],
537+
*,
538+
unicode_escape: bool = True,
539+
uri_decode: bool = False,
540+
) -> object:
541+
"""Apply the JSON Patch _patch_ to _data_.
542+
543+
If _data_ is a string or file-like object, it will be loaded with
544+
_json.loads_. Otherwise _data_ should be a JSON-like data structure and
545+
will be **modified in-place**.
546+
547+
When modifying _data_ in-place, we return modified data too. This is
548+
to allow for replacing _data's_ root element, which is allowed by some
549+
patch operations.
550+
551+
Arguments:
552+
patch: A JSON Patch formatted document or equivalent Python objects.
553+
data: The target JSON "document" or equivalent Python objects.
554+
unicode_escape: If `True`, UTF-16 escape sequences will be decoded
555+
before parsing JSON pointers.
556+
uri_decode: If `True`, JSON pointers will be unescaped using _urllib_
557+
before being parsed.
558+
559+
Returns:
560+
Modified input data.
561+
562+
Raises:
563+
JSONPatchError: When a patch operation fails.
564+
JSONPatchTestFailure: When a _test_ operation does not pass.
565+
`JSONPatchTestFailure` is a subclass of `JSONPatchError`.
566+
567+
"""
568+
return JSONPatch(
569+
patch,
570+
unicode_escape=unicode_escape,
571+
uri_decode=uri_decode,
572+
).apply(data)

0 commit comments

Comments
 (0)