Skip to content

Commit 5eccc03

Browse files
Mapheyclaude
andcommitted
Attach failing operation to JsonPatchException as op
Brings #126 up to date with current master. JsonPatchException now accepts an optional `op` keyword argument, and all exceptions raised while constructing or applying a patch operation carry the failing operation (the PatchOperation instance, or the raw operation dict if it could not be constructed). Compared to the original PR, the constructor now forwards the message to Exception, which fixes a TypeError ("got multiple values for argument 'op'") when raising with both a message and op. Tests added. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PewzpkvyJUvFMnnjKxmyNd
1 parent 152919e commit 5eccc03

2 files changed

Lines changed: 69 additions & 25 deletions

File tree

‎jsonpatch.py‎

Lines changed: 38 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,19 @@
6363
class JsonPatchException(Exception):
6464
"""Base Json Patch exception"""
6565

66+
def __init__(self, *args, **kwargs):
67+
"""Initialize a new instance of a JsonPatchException
68+
69+
:param op: The operation that failed. It is attached to the exception
70+
so that callers can inspect (or modify) the failing patch
71+
operation. This is either a :class:`PatchOperation`
72+
instance or, if the operation could not be constructed,
73+
the raw operation object.
74+
:type op: PatchOperation or dict or None
75+
"""
76+
self.op = kwargs.pop('op', None)
77+
super(JsonPatchException, self).__init__(*args, **kwargs)
78+
6679

6780
class InvalidJsonPatch(JsonPatchException):
6881
""" Raised if an invalid JSON Patch is created """
@@ -173,7 +186,7 @@ def __init__(self, operation, pointer_cls=JsonPointer):
173186
self.pointer_cls = pointer_cls
174187

175188
if not operation.__contains__('path'):
176-
raise InvalidJsonPatch("Operation must have a 'path' member")
189+
raise InvalidJsonPatch("Operation must have a 'path' member", op=operation)
177190

178191
if isinstance(operation['path'], self.pointer_cls):
179192
self.location = operation['path'].path
@@ -183,7 +196,7 @@ def __init__(self, operation, pointer_cls=JsonPointer):
183196
try:
184197
self.pointer = self.pointer_cls(self.location)
185198
except TypeError:
186-
raise InvalidJsonPatch("Invalid 'path'")
199+
raise InvalidJsonPatch("Invalid 'path'", op=operation)
187200

188201
self.operation = operation
189202

@@ -194,15 +207,15 @@ def _from_pointer(self):
194207
from_ptr = self.operation['from']
195208
except KeyError:
196209
raise InvalidJsonPatch(
197-
"The operation does not contain a 'from' member")
210+
"The operation does not contain a 'from' member", op=self)
198211

199212
if isinstance(from_ptr, self.pointer_cls):
200213
return from_ptr
201214

202215
try:
203216
return self.pointer_cls(from_ptr)
204217
except TypeError:
205-
raise InvalidJsonPatch("Invalid 'from'")
218+
raise InvalidJsonPatch("Invalid 'from'", op=self)
206219

207220
def apply(self, obj):
208221
"""Abstract method that applies a patch operation to the specified object."""
@@ -253,7 +266,7 @@ def apply(self, obj):
253266
subobj, part = self.pointer.to_last(obj)
254267

255268
if part is None:
256-
raise JsonPatchConflict("can't remove the whole document")
269+
raise JsonPatchConflict("can't remove the whole document", op=self)
257270

258271
if isinstance(subobj, Sequence) and not isinstance(part, int):
259272
raise JsonPointerException("invalid array index '{0}'".format(part))
@@ -262,9 +275,9 @@ def apply(self, obj):
262275
del subobj[part]
263276
except (KeyError, IndexError):
264277
msg = "can't remove a non-existent object '{0}'".format(part)
265-
raise JsonPatchConflict(msg)
278+
raise JsonPatchConflict(msg, op=self)
266279
except TypeError as ex:
267-
raise JsonPatchConflict(str(ex))
280+
raise JsonPatchConflict(str(ex), op=self)
268281

269282
return obj
270283

@@ -277,7 +290,7 @@ def apply(self, obj):
277290
value = self.operation["value"]
278291
except KeyError:
279292
raise InvalidJsonPatch(
280-
"The operation does not contain a 'value' member")
293+
"The operation does not contain a 'value' member", op=self)
281294

282295
# Insert a copy so the document does not share mutable values with
283296
# the patch; otherwise later operations would modify the patch itself.
@@ -294,7 +307,7 @@ def _add(self, obj, value):
294307
subobj.append(value) # pylint: disable=E1103
295308

296309
elif part > len(subobj) or part < 0:
297-
raise JsonPatchConflict("can't insert outside of list")
310+
raise JsonPatchConflict("can't insert outside of list", op=self)
298311

299312
else:
300313
subobj.insert(part, value) # pylint: disable=E1103
@@ -303,7 +316,7 @@ def _add(self, obj, value):
303316
subobj[part] = value
304317

305318
else:
306-
raise JsonPatchConflict("unable to fully resolve json pointer {0}, part {1}".format(self.location, part))
319+
raise JsonPatchConflict("unable to fully resolve json pointer {0}, part {1}".format(self.location, part), op=self)
307320
return obj
308321

309322

@@ -315,7 +328,7 @@ def apply(self, obj):
315328
value = self.operation["value"]
316329
except KeyError:
317330
raise InvalidJsonPatch(
318-
"The operation does not contain a 'value' member")
331+
"The operation does not contain a 'value' member", op=self)
319332

320333
# copied for the same reason as in AddOperation.apply
321334
value = copy.deepcopy(value)
@@ -329,17 +342,17 @@ def apply(self, obj):
329342
# '-' only refers to the (nonexistent) element after the end of
330343
# an array; for an object it is an ordinary member name
331344
if part == "-":
332-
raise InvalidJsonPatch("'path' with '-' can't be applied to 'replace' operation")
345+
raise InvalidJsonPatch("'path' with '-' can't be applied to 'replace' operation", op=self)
333346

334347
if part >= len(subobj) or part < 0:
335-
raise JsonPatchConflict("can't replace outside of list")
348+
raise JsonPatchConflict("can't replace outside of list", op=self)
336349

337350
elif isinstance(subobj, MutableMapping):
338351
if part not in subobj:
339352
msg = "can't replace a non-existent object '{0}'".format(part)
340-
raise JsonPatchConflict(msg)
353+
raise JsonPatchConflict(msg, op=self)
341354
else:
342-
raise JsonPatchConflict("unable to fully resolve json pointer {0}, part {1}".format(self.location, part))
355+
raise JsonPatchConflict("unable to fully resolve json pointer {0}, part {1}".format(self.location, part), op=self)
343356

344357
subobj[part] = value
345358
return obj
@@ -355,7 +368,7 @@ def apply(self, obj):
355368
# shifts its siblings, so the target would resolve to a different
356369
# location. This also covers moving the whole document ('from' is "").
357370
if self.pointer != from_ptr and self.pointer.contains(from_ptr):
358-
raise JsonPatchConflict('Cannot move values into their own children')
371+
raise JsonPatchConflict('Cannot move values into their own children', op=self)
359372

360373
subobj, part = _to_existing_last(from_ptr, obj)
361374

@@ -366,7 +379,7 @@ def apply(self, obj):
366379
try:
367380
value = subobj[part]
368381
except (KeyError, IndexError) as ex:
369-
raise JsonPatchConflict(str(ex))
382+
raise JsonPatchConflict(str(ex), op=self)
370383

371384
# If source and target are equal, this is a no-op
372385
if self.pointer == from_ptr:
@@ -422,18 +435,18 @@ def apply(self, obj):
422435
else:
423436
val = self.pointer.walk(subobj, part)
424437
except JsonPointerException as ex:
425-
raise JsonPatchTestFailed(str(ex))
438+
raise JsonPatchTestFailed(str(ex), op=self)
426439

427440
try:
428441
value = self.operation['value']
429442
except KeyError:
430443
raise InvalidJsonPatch(
431-
"The operation does not contain a 'value' member")
444+
"The operation does not contain a 'value' member", op=self)
432445

433446
if not _json_equal(val, value):
434447
msg = '{0} ({1}) is not equal to tested value {2} ({3})'
435448
raise JsonPatchTestFailed(msg.format(val, type(val),
436-
value, type(value)))
449+
value, type(value)), op=self)
437450

438451
return obj
439452

@@ -448,7 +461,7 @@ def apply(self, obj):
448461
try:
449462
value = copy.deepcopy(subobj if part is None else subobj[part])
450463
except (KeyError, IndexError) as ex:
451-
raise JsonPatchConflict(str(ex))
464+
raise JsonPatchConflict(str(ex), op=self)
452465

453466
# value is already a deep copy, no need to copy it again
454467
obj = AddOperation({
@@ -671,18 +684,18 @@ def apply(self, obj, in_place=False):
671684

672685
def _get_operation(self, operation):
673686
if not isinstance(operation, Mapping):
674-
raise InvalidJsonPatch("Operation must be an object")
687+
raise InvalidJsonPatch("Operation must be an object", op=operation)
675688

676689
if 'op' not in operation:
677-
raise InvalidJsonPatch("Operation does not contain 'op' member")
690+
raise InvalidJsonPatch("Operation does not contain 'op' member", op=operation)
678691

679692
op = operation['op']
680693

681694
if not isinstance(op, (str, bytes)):
682-
raise InvalidJsonPatch("Operation's op must be a string")
695+
raise InvalidJsonPatch("Operation's op must be a string", op=operation)
683696

684697
if op not in self.operations:
685-
raise InvalidJsonPatch("Unknown operation {0!r}".format(op))
698+
raise InvalidJsonPatch("Unknown operation {0!r}".format(op), op=operation)
686699

687700
cls = self.operations[op]
688701
return cls(operation, pointer_cls=self.pointer_cls)

‎tests.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1961,6 +1961,36 @@ def test_json_patch_with_prefix_pointer(self):
19611961
self.assertEqual(res, {'foo': {'bar': {'baz': 'qux'}}})
19621962

19631963

1964+
class ExceptionOperationTests(unittest.TestCase):
1965+
""" The failing operation is attached to raised exceptions """
1966+
1967+
def test_conflict_has_operation(self):
1968+
patch = jsonpatch.JsonPatch([{'op': 'remove', 'path': '/missing'}])
1969+
with self.assertRaises(jsonpatch.JsonPatchConflict) as cm:
1970+
patch.apply({'foo': 1})
1971+
self.assertIsInstance(cm.exception.op, jsonpatch.RemoveOperation)
1972+
self.assertEqual(cm.exception.op.location, '/missing')
1973+
self.assertEqual(str(cm.exception),
1974+
"can't remove a non-existent object 'missing'")
1975+
1976+
def test_test_failed_has_operation(self):
1977+
patch = jsonpatch.JsonPatch([{'op': 'test', 'path': '/foo', 'value': 2}])
1978+
with self.assertRaises(jsonpatch.JsonPatchTestFailed) as cm:
1979+
patch.apply({'foo': 1})
1980+
self.assertIsInstance(cm.exception.op, jsonpatch.TestOperation)
1981+
1982+
def test_invalid_patch_has_raw_operation(self):
1983+
operation = {'op': 'frobnicate', 'path': '/foo'}
1984+
with self.assertRaises(jsonpatch.InvalidJsonPatch) as cm:
1985+
jsonpatch.apply_patch({}, [operation])
1986+
self.assertIs(cm.exception.op, operation)
1987+
1988+
def test_op_defaults_to_none(self):
1989+
ex = jsonpatch.JsonPatchException('message')
1990+
self.assertIsNone(ex.op)
1991+
self.assertEqual(str(ex), 'message')
1992+
1993+
19641994
class CustomOperationTests(unittest.TestCase):
19651995

19661996
def test_custom_operation(self):
@@ -2427,6 +2457,7 @@ def get_suite():
24272457
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(OperationLocationTests))
24282458
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(CustomJsonPointerTests))
24292459
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(CustomOperationTests))
2460+
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(ExceptionOperationTests))
24302461
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(CommandLineTests))
24312462
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(DocumentationTests))
24322463
return suite

0 commit comments

Comments
 (0)