jsonpatch 1.38__py3-none-any.whl → 1.40__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jsonpatch
3
- Version: 1.38
3
+ Version: 1.40
4
4
  Summary: Apply JSON-Patches (RFC 6902)
5
5
  Home-page: https://github.com/stefankoegl/python-json-patch
6
6
  Author: Stefan Kögl
@@ -0,0 +1,9 @@
1
+ jsonpatch.py,sha256=nBwD-qjBsmCmxqudmG8hfFMRb1Qd7RuqRWWD3ywSfCA,47675
2
+ jsonpatch_cli.py,sha256=ooxDB62_Vcx6ryCbyMHItkNgmZjp73ZOyxgV1IAcdVI,6274
3
+ jsonpatch-1.40.dist-info/licenses/AUTHORS,sha256=hOtEnBGbfDegKjzMDEl5vuVJyczbI2PlYE2ho4LjGNQ,140
4
+ jsonpatch-1.40.dist-info/licenses/LICENSE,sha256=Q5PrZzP6HjZ_QXabOC9PG-e_Da6x4kPtkrP12Lr9I28,1481
5
+ jsonpatch-1.40.dist-info/METADATA,sha256=-V0jnbQmTPNGNAkMXQR6I59RsVv09ORksXEv7fT8lYU,3672
6
+ jsonpatch-1.40.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ jsonpatch-1.40.dist-info/entry_points.txt,sha256=aY9ormBVRZHHDaAeMcdqTBwZ-ax7GvBTSQ33I75xtZM,98
8
+ jsonpatch-1.40.dist-info/top_level.txt,sha256=efUF341HUk8WcQKnFt8ZLKEKNrm1kFT76Flr38Fjno0,24
9
+ jsonpatch-1.40.dist-info/RECORD,,
jsonpatch.py CHANGED
@@ -55,7 +55,7 @@ _EXACT_MATCH_LIMIT = 500 ** 2
55
55
 
56
56
  # Will be parsed by setup.py to determine package metadata
57
57
  __author__ = 'Stefan Kögl <stefan@skoegl.net>'
58
- __version__ = '1.38'
58
+ __version__ = '1.40'
59
59
  __website__ = 'https://github.com/stefankoegl/python-json-patch'
60
60
  __license__ = 'BSD-3-Clause'
61
61
 
@@ -63,6 +63,19 @@ __license__ = 'BSD-3-Clause'
63
63
  class JsonPatchException(Exception):
64
64
  """Base Json Patch exception"""
65
65
 
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
+
66
79
 
67
80
  class InvalidJsonPatch(JsonPatchException):
68
81
  """ Raised if an invalid JSON Patch is created """
@@ -140,7 +153,7 @@ def apply_patch(doc, patch, in_place=False, pointer_cls=JsonPointer):
140
153
  return patch.apply(doc, in_place)
141
154
 
142
155
 
143
- def make_patch(src, dst, pointer_cls=JsonPointer):
156
+ def make_patch(src, dst, pointer_cls=JsonPointer, generate_test_ops=False):
144
157
  """Generates patch by comparing two document objects. Actually is
145
158
  a proxy to :meth:`JsonPatch.from_diff` method. The resulting patch
146
159
  transforms `src` into `dst`, so it has to be applied to `src` (or to a
@@ -155,6 +168,12 @@ def make_patch(src, dst, pointer_cls=JsonPointer):
155
168
  :param pointer_cls: JSON pointer class to use.
156
169
  :type pointer_cls: Type[JsonPointer]
157
170
 
171
+ :param generate_test_ops: Precede each ``remove`` and ``replace``
172
+ operation by a ``test`` operation that checks
173
+ the value it removes or replaces, so the patch
174
+ fails on documents that differ from `src` there.
175
+ :type generate_test_ops: bool
176
+
158
177
  >>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]}
159
178
  >>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]}
160
179
  >>> patch = make_patch(src, dst)
@@ -163,7 +182,8 @@ def make_patch(src, dst, pointer_cls=JsonPointer):
163
182
  True
164
183
  """
165
184
 
166
- return JsonPatch.from_diff(src, dst, pointer_cls=pointer_cls)
185
+ return JsonPatch.from_diff(src, dst, pointer_cls=pointer_cls,
186
+ generate_test_ops=generate_test_ops)
167
187
 
168
188
 
169
189
  class PatchOperation(object):
@@ -173,7 +193,7 @@ class PatchOperation(object):
173
193
  self.pointer_cls = pointer_cls
174
194
 
175
195
  if not operation.__contains__('path'):
176
- raise InvalidJsonPatch("Operation must have a 'path' member")
196
+ raise InvalidJsonPatch("Operation must have a 'path' member", op=operation)
177
197
 
178
198
  if isinstance(operation['path'], self.pointer_cls):
179
199
  self.location = operation['path'].path
@@ -183,7 +203,7 @@ class PatchOperation(object):
183
203
  try:
184
204
  self.pointer = self.pointer_cls(self.location)
185
205
  except TypeError:
186
- raise InvalidJsonPatch("Invalid 'path'")
206
+ raise InvalidJsonPatch("Invalid 'path'", op=operation)
187
207
 
188
208
  self.operation = operation
189
209
 
@@ -194,7 +214,7 @@ class PatchOperation(object):
194
214
  from_ptr = self.operation['from']
195
215
  except KeyError:
196
216
  raise InvalidJsonPatch(
197
- "The operation does not contain a 'from' member")
217
+ "The operation does not contain a 'from' member", op=self)
198
218
 
199
219
  if isinstance(from_ptr, self.pointer_cls):
200
220
  return from_ptr
@@ -202,7 +222,7 @@ class PatchOperation(object):
202
222
  try:
203
223
  return self.pointer_cls(from_ptr)
204
224
  except TypeError:
205
- raise InvalidJsonPatch("Invalid 'from'")
225
+ raise InvalidJsonPatch("Invalid 'from'", op=self)
206
226
 
207
227
  def apply(self, obj):
208
228
  """Abstract method that applies a patch operation to the specified object."""
@@ -253,7 +273,7 @@ class RemoveOperation(PatchOperation):
253
273
  subobj, part = self.pointer.to_last(obj)
254
274
 
255
275
  if part is None:
256
- raise JsonPatchConflict("can't remove the whole document")
276
+ raise JsonPatchConflict("can't remove the whole document", op=self)
257
277
 
258
278
  if isinstance(subobj, Sequence) and not isinstance(part, int):
259
279
  raise JsonPointerException("invalid array index '{0}'".format(part))
@@ -262,7 +282,9 @@ class RemoveOperation(PatchOperation):
262
282
  del subobj[part]
263
283
  except (KeyError, IndexError):
264
284
  msg = "can't remove a non-existent object '{0}'".format(part)
265
- raise JsonPatchConflict(msg)
285
+ raise JsonPatchConflict(msg, op=self)
286
+ except TypeError as ex:
287
+ raise JsonPatchConflict(str(ex), op=self)
266
288
 
267
289
  return obj
268
290
 
@@ -275,7 +297,7 @@ class AddOperation(PatchOperation):
275
297
  value = self.operation["value"]
276
298
  except KeyError:
277
299
  raise InvalidJsonPatch(
278
- "The operation does not contain a 'value' member")
300
+ "The operation does not contain a 'value' member", op=self)
279
301
 
280
302
  # Insert a copy so the document does not share mutable values with
281
303
  # the patch; otherwise later operations would modify the patch itself.
@@ -292,7 +314,7 @@ class AddOperation(PatchOperation):
292
314
  subobj.append(value) # pylint: disable=E1103
293
315
 
294
316
  elif part > len(subobj) or part < 0:
295
- raise JsonPatchConflict("can't insert outside of list")
317
+ raise JsonPatchConflict("can't insert outside of list", op=self)
296
318
 
297
319
  else:
298
320
  subobj.insert(part, value) # pylint: disable=E1103
@@ -301,7 +323,7 @@ class AddOperation(PatchOperation):
301
323
  subobj[part] = value
302
324
 
303
325
  else:
304
- raise JsonPatchConflict("unable to fully resolve json pointer {0}, part {1}".format(self.location, part))
326
+ raise JsonPatchConflict("unable to fully resolve json pointer {0}, part {1}".format(self.location, part), op=self)
305
327
  return obj
306
328
 
307
329
 
@@ -313,7 +335,7 @@ class ReplaceOperation(PatchOperation):
313
335
  value = self.operation["value"]
314
336
  except KeyError:
315
337
  raise InvalidJsonPatch(
316
- "The operation does not contain a 'value' member")
338
+ "The operation does not contain a 'value' member", op=self)
317
339
 
318
340
  # copied for the same reason as in AddOperation.apply
319
341
  value = copy.deepcopy(value)
@@ -327,17 +349,17 @@ class ReplaceOperation(PatchOperation):
327
349
  # '-' only refers to the (nonexistent) element after the end of
328
350
  # an array; for an object it is an ordinary member name
329
351
  if part == "-":
330
- raise InvalidJsonPatch("'path' with '-' can't be applied to 'replace' operation")
352
+ raise InvalidJsonPatch("'path' with '-' can't be applied to 'replace' operation", op=self)
331
353
 
332
354
  if part >= len(subobj) or part < 0:
333
- raise JsonPatchConflict("can't replace outside of list")
355
+ raise JsonPatchConflict("can't replace outside of list", op=self)
334
356
 
335
357
  elif isinstance(subobj, MutableMapping):
336
358
  if part not in subobj:
337
359
  msg = "can't replace a non-existent object '{0}'".format(part)
338
- raise JsonPatchConflict(msg)
360
+ raise JsonPatchConflict(msg, op=self)
339
361
  else:
340
- raise JsonPatchConflict("unable to fully resolve json pointer {0}, part {1}".format(self.location, part))
362
+ raise JsonPatchConflict("unable to fully resolve json pointer {0}, part {1}".format(self.location, part), op=self)
341
363
 
342
364
  subobj[part] = value
343
365
  return obj
@@ -353,7 +375,7 @@ class MoveOperation(PatchOperation):
353
375
  # shifts its siblings, so the target would resolve to a different
354
376
  # location. This also covers moving the whole document ('from' is "").
355
377
  if self.pointer != from_ptr and self.pointer.contains(from_ptr):
356
- raise JsonPatchConflict('Cannot move values into their own children')
378
+ raise JsonPatchConflict('Cannot move values into their own children', op=self)
357
379
 
358
380
  subobj, part = _to_existing_last(from_ptr, obj)
359
381
 
@@ -364,22 +386,29 @@ class MoveOperation(PatchOperation):
364
386
  try:
365
387
  value = subobj[part]
366
388
  except (KeyError, IndexError) as ex:
367
- raise JsonPatchConflict(str(ex))
389
+ raise JsonPatchConflict(str(ex), op=self)
368
390
 
369
391
  # If source and target are equal, this is a no-op
370
392
  if self.pointer == from_ptr:
371
393
  return obj
372
394
 
373
- obj = RemoveOperation({
374
- 'op': 'remove',
375
- 'path': self.operation['from']
376
- }, pointer_cls=self.pointer_cls).apply(obj)
377
-
378
- # the value has been detached from its old location, so no copy needed
379
- obj = AddOperation({
380
- 'op': 'add',
381
- 'path': self.location,
382
- }, pointer_cls=self.pointer_cls)._add(obj, value)
395
+ try:
396
+ obj = RemoveOperation({
397
+ 'op': 'remove',
398
+ 'path': self.operation['from']
399
+ }, pointer_cls=self.pointer_cls).apply(obj)
400
+
401
+ # the value has been detached from its old location, so no copy
402
+ # needed
403
+ obj = AddOperation({
404
+ 'op': 'add',
405
+ 'path': self.location,
406
+ }, pointer_cls=self.pointer_cls)._add(obj, value)
407
+ except JsonPatchException as ex:
408
+ # report the failure against this operation rather than the
409
+ # internal, synthetic remove / add operations
410
+ ex.op = self
411
+ raise
383
412
 
384
413
  return obj
385
414
 
@@ -420,18 +449,18 @@ class TestOperation(PatchOperation):
420
449
  else:
421
450
  val = self.pointer.walk(subobj, part)
422
451
  except JsonPointerException as ex:
423
- raise JsonPatchTestFailed(str(ex))
452
+ raise JsonPatchTestFailed(str(ex), op=self)
424
453
 
425
454
  try:
426
455
  value = self.operation['value']
427
456
  except KeyError:
428
457
  raise InvalidJsonPatch(
429
- "The operation does not contain a 'value' member")
458
+ "The operation does not contain a 'value' member", op=self)
430
459
 
431
460
  if not _json_equal(val, value):
432
461
  msg = '{0} ({1}) is not equal to tested value {2} ({3})'
433
462
  raise JsonPatchTestFailed(msg.format(val, type(val),
434
- value, type(value)))
463
+ value, type(value)), op=self)
435
464
 
436
465
  return obj
437
466
 
@@ -446,13 +475,19 @@ class CopyOperation(PatchOperation):
446
475
  try:
447
476
  value = copy.deepcopy(subobj if part is None else subobj[part])
448
477
  except (KeyError, IndexError) as ex:
449
- raise JsonPatchConflict(str(ex))
478
+ raise JsonPatchConflict(str(ex), op=self)
450
479
 
451
480
  # value is already a deep copy, no need to copy it again
452
- obj = AddOperation({
453
- 'op': 'add',
454
- 'path': self.location,
455
- }, pointer_cls=self.pointer_cls)._add(obj, value)
481
+ try:
482
+ obj = AddOperation({
483
+ 'op': 'add',
484
+ 'path': self.location,
485
+ }, pointer_cls=self.pointer_cls)._add(obj, value)
486
+ except JsonPatchException as ex:
487
+ # report the failure against this operation rather than the
488
+ # internal, synthetic add operation
489
+ ex.op = self
490
+ raise
456
491
 
457
492
  return obj
458
493
 
@@ -545,7 +580,8 @@ class JsonPatch(object):
545
580
  # of mappings, this won't raise.
546
581
  if isinstance(op, (str, bytes)):
547
582
  raise InvalidJsonPatch("Document is expected to be sequence of "
548
- "operations, got a sequence of strings.")
583
+ "operations, got a sequence of strings.",
584
+ op=op)
549
585
 
550
586
  self._get_operation(op)
551
587
 
@@ -595,7 +631,7 @@ class JsonPatch(object):
595
631
  @classmethod
596
632
  def from_diff(
597
633
  cls, src, dst, optimization=True, dumps=None,
598
- pointer_cls=JsonPointer,
634
+ pointer_cls=JsonPointer, generate_test_ops=False,
599
635
  ):
600
636
  """Creates JsonPatch instance based on comparison of two document
601
637
  objects. Json patch would be created for `src` argument against `dst`
@@ -619,6 +655,12 @@ class JsonPatch(object):
619
655
  :param pointer_cls: JSON pointer class to use.
620
656
  :type pointer_cls: Type[JsonPointer]
621
657
 
658
+ :param generate_test_ops: Precede each ``remove`` and ``replace``
659
+ operation by a ``test`` operation that checks
660
+ the value it removes or replaces, so the patch
661
+ fails on documents that differ from `src` there.
662
+ :type generate_test_ops: bool
663
+
622
664
  :return: :class:`JsonPatch` instance.
623
665
 
624
666
  >>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]}
@@ -630,7 +672,8 @@ class JsonPatch(object):
630
672
  """
631
673
  json_dumper = dumps or cls.json_dumper
632
674
  builder = DiffBuilder(src, dst, json_dumper, pointer_cls=pointer_cls,
633
- optimization=optimization)
675
+ optimization=optimization,
676
+ generate_test_ops=generate_test_ops)
634
677
  builder._compare_values((), None, src, dst)
635
678
  ops = list(builder.execute())
636
679
  return cls(ops, pointer_cls=pointer_cls)
@@ -669,18 +712,18 @@ class JsonPatch(object):
669
712
 
670
713
  def _get_operation(self, operation):
671
714
  if not isinstance(operation, Mapping):
672
- raise InvalidJsonPatch("Operation must be an object")
715
+ raise InvalidJsonPatch("Operation must be an object", op=operation)
673
716
 
674
717
  if 'op' not in operation:
675
- raise InvalidJsonPatch("Operation does not contain 'op' member")
718
+ raise InvalidJsonPatch("Operation does not contain 'op' member", op=operation)
676
719
 
677
720
  op = operation['op']
678
721
 
679
722
  if not isinstance(op, (str, bytes)):
680
- raise InvalidJsonPatch("Operation's op must be a string")
723
+ raise InvalidJsonPatch("Operation's op must be a string", op=operation)
681
724
 
682
725
  if op not in self.operations:
683
- raise InvalidJsonPatch("Unknown operation {0!r}".format(op))
726
+ raise InvalidJsonPatch("Unknown operation {0!r}".format(op), op=operation)
684
727
 
685
728
  cls = self.operations[op]
686
729
  return cls(operation, pointer_cls=self.pointer_cls)
@@ -689,10 +732,14 @@ class JsonPatch(object):
689
732
  class DiffBuilder(object):
690
733
 
691
734
  def __init__(self, src_doc, dst_doc, dumps=json.dumps, pointer_cls=JsonPointer,
692
- optimization=True):
735
+ optimization=True, generate_test_ops=False):
693
736
  self.dumps = dumps
694
737
  self.pointer_cls = pointer_cls
695
738
  self.optimization = optimization
739
+ self.generate_test_ops = generate_test_ops
740
+ # the index of the test operation preceding a remove operation, by
741
+ # the id of the remove operation
742
+ self.remove_tests = {}
696
743
  self.index_storage = [{}, {}]
697
744
  self.__root = root = []
698
745
  self.src_doc = src_doc
@@ -839,6 +886,10 @@ class DiffBuilder(object):
839
886
  source = self._parts(removed)
840
887
  # RFC 6902 does not allow moving a value into its own children
841
888
  if not _is_inside(target, source):
889
+ # the value is moved rather than removed, so it is not tested
890
+ test_index = self.remove_tests.pop(id(index[2]), None)
891
+ if test_index is not None:
892
+ self.remove(test_index)
842
893
  self.remove(index)
843
894
  if source != target:
844
895
  self.insert({'op': 'move', 'from': removed,
@@ -873,14 +924,27 @@ class DiffBuilder(object):
873
924
  self._set_present(added_location, False)
874
925
  return
875
926
 
927
+ test_index = self._insert_test(location, item)
876
928
  self._set_present(location, False)
877
929
  new_index = self.insert({'op': 'remove', 'path': location})
930
+ if test_index is not None:
931
+ self.remove_tests[id(new_index[2])] = test_index
878
932
  self.store_index(item, new_index, _ST_REMOVE)
879
933
 
880
- def _item_replaced(self, path, key, item):
934
+ def _insert_test(self, location, value):
935
+ """ Inserts a test operation that checks the value at location, if
936
+ test operations are generated """
937
+ if self.generate_test_ops:
938
+ # a copy, so that changing src afterwards does not change the test
939
+ return self.insert({'op': 'test', 'path': location,
940
+ 'value': copy.deepcopy(value)})
941
+
942
+ def _item_replaced(self, path, key, item, old_item):
943
+ location = self._location(_path_join(path, key))
944
+ self._insert_test(location, old_item)
881
945
  self.insert({
882
946
  'op': 'replace',
883
- 'path': self._location(_path_join(path, key)),
947
+ 'path': location,
884
948
  'value': item,
885
949
  })
886
950
 
@@ -1015,7 +1079,7 @@ class DiffBuilder(object):
1015
1079
  return
1016
1080
 
1017
1081
  else:
1018
- self._item_replaced(path, key, dst)
1082
+ self._item_replaced(path, key, dst, src)
1019
1083
 
1020
1084
 
1021
1085
  def _positional_cost(old, new):
jsonpatch_cli.py CHANGED
@@ -18,6 +18,9 @@ jsondiff_parser.add_argument('--indent', type=int, default=None,
18
18
  help='Indent output by n spaces')
19
19
  jsondiff_parser.add_argument('-u', '--preserve-unicode', action='store_true',
20
20
  help='Output Unicode character as-is without using Code Point')
21
+ jsondiff_parser.add_argument('-t', '--test-ops', action='store_true',
22
+ help='Precede each remove and replace operation '
23
+ 'by a test of the value it changes')
21
24
  jsondiff_parser.add_argument('-v', '--version', action='version',
22
25
  version='%(prog)s ' + jsonpatch.__version__)
23
26
 
@@ -34,7 +37,7 @@ def diff_files():
34
37
  args = jsondiff_parser.parse_args()
35
38
  doc1 = json.load(args.FILE1)
36
39
  doc2 = json.load(args.FILE2)
37
- patch = jsonpatch.make_patch(doc1, doc2)
40
+ patch = jsonpatch.make_patch(doc1, doc2, generate_test_ops=args.test_ops)
38
41
  if patch.patch:
39
42
  print(json.dumps(patch.patch, indent=args.indent, ensure_ascii=not(args.preserve_unicode)))
40
43
  sys.exit(1)
@@ -70,8 +73,7 @@ def patch_files():
70
73
  """ Applies a JSON patch on a JSON file """
71
74
  args = jsonpatch_parser.parse_args()
72
75
  doc = json.load(args.ORIGINAL)
73
- patch = json.load(args.PATCH)
74
- result = jsonpatch.apply_patch(doc, patch)
76
+ result = jsonpatch.apply_patch(doc, args.PATCH.read())
75
77
 
76
78
  if args.in_place:
77
79
  # 2026-10-11: Release the input handle before replacing it on Windows.
@@ -1,9 +0,0 @@
1
- jsonpatch.py,sha256=CUWLdFCK8nBgO4KWsRNy40sjHouzmGx_C30WE0xT2VU,44186
2
- jsonpatch_cli.py,sha256=IRfXFLpY4qF6QRGSZA227tIZo7ly_RXjImOrMvz8Lag,6043
3
- jsonpatch-1.38.dist-info/licenses/AUTHORS,sha256=hOtEnBGbfDegKjzMDEl5vuVJyczbI2PlYE2ho4LjGNQ,140
4
- jsonpatch-1.38.dist-info/licenses/LICENSE,sha256=Q5PrZzP6HjZ_QXabOC9PG-e_Da6x4kPtkrP12Lr9I28,1481
5
- jsonpatch-1.38.dist-info/METADATA,sha256=-P36hnnP8bn-Bhjj2jRAVl5xmz7XHEaA_kkz-DeAk60,3672
6
- jsonpatch-1.38.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
- jsonpatch-1.38.dist-info/entry_points.txt,sha256=aY9ormBVRZHHDaAeMcdqTBwZ-ax7GvBTSQ33I75xtZM,98
8
- jsonpatch-1.38.dist-info/top_level.txt,sha256=efUF341HUk8WcQKnFt8ZLKEKNrm1kFT76Flr38Fjno0,24
9
- jsonpatch-1.38.dist-info/RECORD,,