Skip to content

Commit 20bfe05

Browse files
authored
Merge pull request #247 from stefankoegl/claude/confident-curie-9x5ahd
Attach failing operation to JsonPatchException as `op`
2 parents 1a53dd3 + bafa36c commit 20bfe05

2 files changed

Lines changed: 129 additions & 40 deletions

File tree

‎jsonpatch.py‎

Lines changed: 67 additions & 40 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,22 +379,29 @@ 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:
373386
return obj
374387

375-
obj = RemoveOperation({
376-
'op': 'remove',
377-
'path': self.operation['from']
378-
}, pointer_cls=self.pointer_cls).apply(obj)
379-
380-
# the value has been detached from its old location, so no copy needed
381-
obj = AddOperation({
382-
'op': 'add',
383-
'path': self.location,
384-
}, pointer_cls=self.pointer_cls)._add(obj, value)
388+
try:
389+
obj = RemoveOperation({
390+
'op': 'remove',
391+
'path': self.operation['from']
392+
}, pointer_cls=self.pointer_cls).apply(obj)
393+
394+
# the value has been detached from its old location, so no copy
395+
# needed
396+
obj = AddOperation({
397+
'op': 'add',
398+
'path': self.location,
399+
}, pointer_cls=self.pointer_cls)._add(obj, value)
400+
except JsonPatchException as ex:
401+
# report the failure against this operation rather than the
402+
# internal, synthetic remove / add operations
403+
ex.op = self
404+
raise
385405

386406
return obj
387407

@@ -422,18 +442,18 @@ def apply(self, obj):
422442
else:
423443
val = self.pointer.walk(subobj, part)
424444
except JsonPointerException as ex:
425-
raise JsonPatchTestFailed(str(ex))
445+
raise JsonPatchTestFailed(str(ex), op=self)
426446

427447
try:
428448
value = self.operation['value']
429449
except KeyError:
430450
raise InvalidJsonPatch(
431-
"The operation does not contain a 'value' member")
451+
"The operation does not contain a 'value' member", op=self)
432452

433453
if not _json_equal(val, value):
434454
msg = '{0} ({1}) is not equal to tested value {2} ({3})'
435455
raise JsonPatchTestFailed(msg.format(val, type(val),
436-
value, type(value)))
456+
value, type(value)), op=self)
437457

438458
return obj
439459

@@ -448,13 +468,19 @@ def apply(self, obj):
448468
try:
449469
value = copy.deepcopy(subobj if part is None else subobj[part])
450470
except (KeyError, IndexError) as ex:
451-
raise JsonPatchConflict(str(ex))
471+
raise JsonPatchConflict(str(ex), op=self)
452472

453473
# value is already a deep copy, no need to copy it again
454-
obj = AddOperation({
455-
'op': 'add',
456-
'path': self.location,
457-
}, pointer_cls=self.pointer_cls)._add(obj, value)
474+
try:
475+
obj = AddOperation({
476+
'op': 'add',
477+
'path': self.location,
478+
}, pointer_cls=self.pointer_cls)._add(obj, value)
479+
except JsonPatchException as ex:
480+
# report the failure against this operation rather than the
481+
# internal, synthetic add operation
482+
ex.op = self
483+
raise
458484

459485
return obj
460486

@@ -547,7 +573,8 @@ def __init__(self, patch, pointer_cls=JsonPointer):
547573
# of mappings, this won't raise.
548574
if isinstance(op, (str, bytes)):
549575
raise InvalidJsonPatch("Document is expected to be sequence of "
550-
"operations, got a sequence of strings.")
576+
"operations, got a sequence of strings.",
577+
op=op)
551578

552579
self._get_operation(op)
553580

@@ -671,18 +698,18 @@ def apply(self, obj, in_place=False):
671698

672699
def _get_operation(self, operation):
673700
if not isinstance(operation, Mapping):
674-
raise InvalidJsonPatch("Operation must be an object")
701+
raise InvalidJsonPatch("Operation must be an object", op=operation)
675702

676703
if 'op' not in operation:
677-
raise InvalidJsonPatch("Operation does not contain 'op' member")
704+
raise InvalidJsonPatch("Operation does not contain 'op' member", op=operation)
678705

679706
op = operation['op']
680707

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

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

687714
cls = self.operations[op]
688715
return cls(operation, pointer_cls=self.pointer_cls)

‎tests.py‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1961,6 +1961,67 @@ 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_move_failed_add_reports_move_operation(self):
1989+
patch = jsonpatch.JsonPatch(
1990+
[{'op': 'move', 'from': '/foo', 'path': '/bar/5'}])
1991+
with self.assertRaises(jsonpatch.JsonPatchConflict) as cm:
1992+
patch.apply({'foo': 1, 'bar': []})
1993+
self.assertIsInstance(cm.exception.op, jsonpatch.MoveOperation)
1994+
self.assertIs(cm.exception.op.operation, patch.patch[0])
1995+
1996+
def test_move_failed_remove_reports_move_operation(self):
1997+
# the value can be read from the immutable tuple, but the internal
1998+
# remove operation fails
1999+
patch = jsonpatch.JsonPatch(
2000+
[{'op': 'move', 'from': '/foo/0', 'path': '/bar'}])
2001+
with self.assertRaises(jsonpatch.JsonPatchConflict) as cm:
2002+
patch.apply({'foo': (1, 2)})
2003+
self.assertIsInstance(cm.exception.op, jsonpatch.MoveOperation)
2004+
self.assertIs(cm.exception.op.operation, patch.patch[0])
2005+
2006+
def test_copy_failed_add_reports_copy_operation(self):
2007+
patch = jsonpatch.JsonPatch(
2008+
[{'op': 'copy', 'from': '/foo', 'path': '/bar/5'}])
2009+
with self.assertRaises(jsonpatch.JsonPatchConflict) as cm:
2010+
patch.apply({'foo': 1, 'bar': []})
2011+
self.assertIsInstance(cm.exception.op, jsonpatch.CopyOperation)
2012+
self.assertIs(cm.exception.op.operation, patch.patch[0])
2013+
2014+
def test_string_entry_has_raw_operation(self):
2015+
with self.assertRaises(jsonpatch.InvalidJsonPatch) as cm:
2016+
jsonpatch.JsonPatch(['invalid operation'])
2017+
self.assertEqual(cm.exception.op, 'invalid operation')
2018+
2019+
def test_op_defaults_to_none(self):
2020+
ex = jsonpatch.JsonPatchException('message')
2021+
self.assertIsNone(ex.op)
2022+
self.assertEqual(str(ex), 'message')
2023+
2024+
19642025
class CustomOperationTests(unittest.TestCase):
19652026

19662027
def test_custom_operation(self):
@@ -2448,6 +2509,7 @@ def get_suite():
24482509
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(OperationLocationTests))
24492510
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(CustomJsonPointerTests))
24502511
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(CustomOperationTests))
2512+
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(ExceptionOperationTests))
24512513
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(CommandLineTests))
24522514
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(DocumentationTests))
24532515
return suite

0 commit comments

Comments
 (0)