jsonpatch 1.39__py3-none-any.whl → 1.41__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.39
3
+ Version: 1.41
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
@@ -28,11 +28,12 @@ Classifier: Programming Language :: Python :: Implementation :: CPython
28
28
  Classifier: Programming Language :: Python :: Implementation :: PyPy
29
29
  Classifier: Topic :: Software Development :: Libraries
30
30
  Classifier: Topic :: Utilities
31
+ Classifier: Typing :: Typed
31
32
  Requires-Python: >=3.10
32
33
  Description-Content-Type: text/markdown
33
34
  License-File: LICENSE
34
35
  License-File: AUTHORS
35
- Requires-Dist: jsonpointer>=3.2
36
+ Requires-Dist: jsonpointer>=3.8
36
37
  Dynamic: author
37
38
  Dynamic: author-email
38
39
  Dynamic: classifier
@@ -69,6 +70,20 @@ See source code for examples
69
70
  * CI: https://github.com/stefankoegl/python-json-patch/actions
70
71
  * Coveralls: https://coveralls.io/github/stefankoegl/python-json-patch
71
72
 
73
+ Type hints
74
+ ----------
75
+ jsonpatch ships type stubs (in the `jsonpatch-stubs` directory, as
76
+ jsonpatch.py is a single-file module), so type checkers such as mypy and
77
+ pyright work with it without further setup. JSON documents are typed as `Any`.
78
+
79
+ When changing the public API of jsonpatch.py, update
80
+ `jsonpatch-stubs/__init__.pyi` as well. These check that both agree, and that
81
+ typical usage in `typetests/usage.py` type-checks:
82
+
83
+ pip install mypy .
84
+ python -m mypy.stubtest --mypy-config-file pyproject.toml jsonpatch
85
+ cd typetests && mypy --config-file ../pyproject.toml usage.py
86
+
72
87
  Running external tests
73
88
  ----------------------
74
89
  To run external tests (such as those from https://github.com/json-patch/json-patch-tests) use ext_tests.py
@@ -0,0 +1,10 @@
1
+ jsonpatch.py,sha256=i0UN_UBxpx9ClyplHpbEEhVpHC-ckzcwqlAsPutxD28,47675
2
+ jsonpatch_cli.py,sha256=ooxDB62_Vcx6ryCbyMHItkNgmZjp73ZOyxgV1IAcdVI,6274
3
+ jsonpatch-1.41.dist-info/licenses/AUTHORS,sha256=hOtEnBGbfDegKjzMDEl5vuVJyczbI2PlYE2ho4LjGNQ,140
4
+ jsonpatch-1.41.dist-info/licenses/LICENSE,sha256=Q5PrZzP6HjZ_QXabOC9PG-e_Da6x4kPtkrP12Lr9I28,1481
5
+ jsonpatch-stubs/__init__.pyi,sha256=puuW3LKHkYNSMyGQ_0XqfDwqLjdHbSUTJU79gpPZy54,5215
6
+ jsonpatch-1.41.dist-info/METADATA,sha256=je3-rYA4OmtMG6NM7sDfYCSU3MSttqM9CmKJ4ugSFEo,4287
7
+ jsonpatch-1.41.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ jsonpatch-1.41.dist-info/entry_points.txt,sha256=aY9ormBVRZHHDaAeMcdqTBwZ-ax7GvBTSQ33I75xtZM,98
9
+ jsonpatch-1.41.dist-info/top_level.txt,sha256=AGmziZtf5TSFAtbhYlhDGjQg1POmwzF9HwLdbzPkoio,40
10
+ jsonpatch-1.41.dist-info/RECORD,,
@@ -1,2 +1,3 @@
1
1
  jsonpatch
2
+ jsonpatch-stubs
2
3
  jsonpatch_cli
@@ -0,0 +1,146 @@
1
+ # Type stubs for jsonpatch.
2
+ #
3
+ # jsonpatch is a single-file module, and PEP 561 has no py.typed marker for
4
+ # those, so its types are shipped as this stub-only package in the same
5
+ # distribution. Keep it in sync with jsonpatch.py; CI runs mypy's stubtest to
6
+ # check that both agree.
7
+ #
8
+ # JSON documents are typed as Any: they can be any JSON value, and the module
9
+ # also accepts arbitrary Mapping / Sequence types, which a recursive JSON type
10
+ # would reject.
11
+
12
+ from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
13
+ from typing import Any, ClassVar
14
+
15
+ # Re-exported, as jsonpatch.py imports them and users rely on that, e.g. to
16
+ # catch jsonpatch.JsonPointerException. stubtest does not check these, as
17
+ # they are defined in another module.
18
+ from jsonpointer import JsonPointer as JsonPointer
19
+ from jsonpointer import JsonPointerException as JsonPointerException
20
+ from typing_extensions import Self
21
+
22
+ __author__: str
23
+ __version__: str
24
+ __website__: str
25
+ __license__: str
26
+
27
+ # A single patch operation, e.g. {'op': 'add', 'path': '/a', 'value': 1}
28
+ _Operation = Mapping[str, Any]
29
+
30
+ class JsonPatchException(Exception):
31
+ # The failing operation: a PatchOperation, or the raw operation object if
32
+ # none could be constructed from it, or None.
33
+ op: Any
34
+ def __init__(self, *args: object, op: Any = None) -> None: ...
35
+
36
+ class InvalidJsonPatch(JsonPatchException): ...
37
+ class JsonPatchConflict(JsonPatchException): ...
38
+ class JsonPatchTestFailed(JsonPatchException, AssertionError): ...
39
+
40
+ def multidict(ordered_pairs: Iterable[tuple[str, Any]]) -> dict[str, Any]: ...
41
+ def apply_patch(
42
+ doc: Any,
43
+ patch: str | bytes | Iterable[_Operation],
44
+ in_place: bool = False,
45
+ pointer_cls: type[JsonPointer] = ...,
46
+ ) -> Any: ...
47
+ def make_patch(
48
+ src: Any,
49
+ dst: Any,
50
+ pointer_cls: type[JsonPointer] = ...,
51
+ generate_test_ops: bool = False,
52
+ ) -> JsonPatch: ...
53
+
54
+ class PatchOperation:
55
+ pointer_cls: type[JsonPointer]
56
+ location: str
57
+ pointer: JsonPointer
58
+ operation: _Operation
59
+ def __init__(self, operation: _Operation, pointer_cls: type[JsonPointer] = ...) -> None: ...
60
+ def apply(self, obj: Any) -> Any: ...
61
+ def __hash__(self) -> int: ...
62
+ def __eq__(self, other: object) -> bool: ...
63
+ def __ne__(self, other: object) -> bool: ...
64
+ @property
65
+ def path(self) -> str: ...
66
+ @property
67
+ def key(self) -> int | str: ...
68
+ @key.setter
69
+ def key(self, value: int | str) -> None: ...
70
+ def get_part(self, index: int) -> int | str: ...
71
+ def set_part(self, index: int, value: int | str) -> None: ...
72
+
73
+ class RemoveOperation(PatchOperation): ...
74
+ class AddOperation(PatchOperation): ...
75
+ class ReplaceOperation(PatchOperation): ...
76
+
77
+ class MoveOperation(PatchOperation):
78
+ @property
79
+ def from_path(self) -> str: ...
80
+ @property
81
+ def from_key(self) -> int | str: ...
82
+ @from_key.setter
83
+ def from_key(self, value: int | str) -> None: ...
84
+ def get_from_part(self, index: int) -> int | str: ...
85
+ def set_from_part(self, index: int, value: int | str) -> None: ...
86
+
87
+ class TestOperation(PatchOperation): ...
88
+ class CopyOperation(PatchOperation): ...
89
+
90
+ class JsonPatch:
91
+ json_dumper: ClassVar[Callable[..., str]]
92
+ json_loader: ClassVar[Callable[..., Any]]
93
+ operations: ClassVar[Mapping[str, type[PatchOperation]]]
94
+ pointer_cls: type[JsonPointer]
95
+ patch: Sequence[_Operation]
96
+ def __init__(self, patch: Iterable[_Operation], pointer_cls: type[JsonPointer] = ...) -> None: ...
97
+ def __bool__(self) -> bool: ...
98
+ def __iter__(self) -> Iterator[_Operation]: ...
99
+ def __hash__(self) -> int: ...
100
+ def __eq__(self, other: object) -> bool: ...
101
+ def __ne__(self, other: object) -> bool: ...
102
+ __nonzero__ = __bool__
103
+ @classmethod
104
+ def from_string(
105
+ cls,
106
+ patch_str: str | bytes | bytearray,
107
+ loads: Callable[[Any], Any] | None = None,
108
+ pointer_cls: type[JsonPointer] = ...,
109
+ ) -> Self: ...
110
+ @classmethod
111
+ def from_diff(
112
+ cls,
113
+ src: Any,
114
+ dst: Any,
115
+ optimization: bool = True,
116
+ dumps: Callable[[Any], str] | None = None,
117
+ pointer_cls: type[JsonPointer] = ...,
118
+ generate_test_ops: bool = False,
119
+ ) -> Self: ...
120
+ def to_string(self, dumps: Callable[[Any], str] | None = None) -> str: ...
121
+ def apply(self, obj: Any, in_place: bool = False) -> Any: ...
122
+
123
+ # Computes the operations for JsonPatch.from_diff; mostly an implementation
124
+ # detail, so its internal methods are typed loosely.
125
+ class DiffBuilder:
126
+ dumps: Callable[[Any], str]
127
+ pointer_cls: type[JsonPointer]
128
+ optimization: bool
129
+ generate_test_ops: bool
130
+ src_doc: Any
131
+ dst_doc: Any
132
+ def __init__(
133
+ self,
134
+ src_doc: Any,
135
+ dst_doc: Any,
136
+ dumps: Callable[[Any], str] = ...,
137
+ pointer_cls: type[JsonPointer] = ...,
138
+ optimization: bool = True,
139
+ generate_test_ops: bool = False,
140
+ ) -> None: ...
141
+ def store_index(self, value: Any, index: Any, st: int) -> None: ...
142
+ def take_index(self, value: Any, st: int) -> Any: ...
143
+ def insert(self, op: Any) -> Any: ...
144
+ def remove(self, index: Any) -> None: ...
145
+ def __iter__(self) -> Iterator[Any]: ...
146
+ def execute(self) -> Iterator[dict[str, Any]]: ...
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.39'
58
+ __version__ = '1.41'
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,9 +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)
266
286
  except TypeError as ex:
267
- raise JsonPatchConflict(str(ex))
287
+ raise JsonPatchConflict(str(ex), op=self)
268
288
 
269
289
  return obj
270
290
 
@@ -277,7 +297,7 @@ class AddOperation(PatchOperation):
277
297
  value = self.operation["value"]
278
298
  except KeyError:
279
299
  raise InvalidJsonPatch(
280
- "The operation does not contain a 'value' member")
300
+ "The operation does not contain a 'value' member", op=self)
281
301
 
282
302
  # Insert a copy so the document does not share mutable values with
283
303
  # the patch; otherwise later operations would modify the patch itself.
@@ -294,7 +314,7 @@ class AddOperation(PatchOperation):
294
314
  subobj.append(value) # pylint: disable=E1103
295
315
 
296
316
  elif part > len(subobj) or part < 0:
297
- raise JsonPatchConflict("can't insert outside of list")
317
+ raise JsonPatchConflict("can't insert outside of list", op=self)
298
318
 
299
319
  else:
300
320
  subobj.insert(part, value) # pylint: disable=E1103
@@ -303,7 +323,7 @@ class AddOperation(PatchOperation):
303
323
  subobj[part] = value
304
324
 
305
325
  else:
306
- 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)
307
327
  return obj
308
328
 
309
329
 
@@ -315,7 +335,7 @@ class ReplaceOperation(PatchOperation):
315
335
  value = self.operation["value"]
316
336
  except KeyError:
317
337
  raise InvalidJsonPatch(
318
- "The operation does not contain a 'value' member")
338
+ "The operation does not contain a 'value' member", op=self)
319
339
 
320
340
  # copied for the same reason as in AddOperation.apply
321
341
  value = copy.deepcopy(value)
@@ -329,17 +349,17 @@ class ReplaceOperation(PatchOperation):
329
349
  # '-' only refers to the (nonexistent) element after the end of
330
350
  # an array; for an object it is an ordinary member name
331
351
  if part == "-":
332
- 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)
333
353
 
334
354
  if part >= len(subobj) or part < 0:
335
- raise JsonPatchConflict("can't replace outside of list")
355
+ raise JsonPatchConflict("can't replace outside of list", op=self)
336
356
 
337
357
  elif isinstance(subobj, MutableMapping):
338
358
  if part not in subobj:
339
359
  msg = "can't replace a non-existent object '{0}'".format(part)
340
- raise JsonPatchConflict(msg)
360
+ raise JsonPatchConflict(msg, op=self)
341
361
  else:
342
- 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)
343
363
 
344
364
  subobj[part] = value
345
365
  return obj
@@ -355,7 +375,7 @@ class MoveOperation(PatchOperation):
355
375
  # shifts its siblings, so the target would resolve to a different
356
376
  # location. This also covers moving the whole document ('from' is "").
357
377
  if self.pointer != from_ptr and self.pointer.contains(from_ptr):
358
- raise JsonPatchConflict('Cannot move values into their own children')
378
+ raise JsonPatchConflict('Cannot move values into their own children', op=self)
359
379
 
360
380
  subobj, part = _to_existing_last(from_ptr, obj)
361
381
 
@@ -366,22 +386,29 @@ class MoveOperation(PatchOperation):
366
386
  try:
367
387
  value = subobj[part]
368
388
  except (KeyError, IndexError) as ex:
369
- raise JsonPatchConflict(str(ex))
389
+ raise JsonPatchConflict(str(ex), op=self)
370
390
 
371
391
  # If source and target are equal, this is a no-op
372
392
  if self.pointer == from_ptr:
373
393
  return obj
374
394
 
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)
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
385
412
 
386
413
  return obj
387
414
 
@@ -422,18 +449,18 @@ class TestOperation(PatchOperation):
422
449
  else:
423
450
  val = self.pointer.walk(subobj, part)
424
451
  except JsonPointerException as ex:
425
- raise JsonPatchTestFailed(str(ex))
452
+ raise JsonPatchTestFailed(str(ex), op=self)
426
453
 
427
454
  try:
428
455
  value = self.operation['value']
429
456
  except KeyError:
430
457
  raise InvalidJsonPatch(
431
- "The operation does not contain a 'value' member")
458
+ "The operation does not contain a 'value' member", op=self)
432
459
 
433
460
  if not _json_equal(val, value):
434
461
  msg = '{0} ({1}) is not equal to tested value {2} ({3})'
435
462
  raise JsonPatchTestFailed(msg.format(val, type(val),
436
- value, type(value)))
463
+ value, type(value)), op=self)
437
464
 
438
465
  return obj
439
466
 
@@ -448,13 +475,19 @@ class CopyOperation(PatchOperation):
448
475
  try:
449
476
  value = copy.deepcopy(subobj if part is None else subobj[part])
450
477
  except (KeyError, IndexError) as ex:
451
- raise JsonPatchConflict(str(ex))
478
+ raise JsonPatchConflict(str(ex), op=self)
452
479
 
453
480
  # 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)
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
458
491
 
459
492
  return obj
460
493
 
@@ -547,7 +580,8 @@ class JsonPatch(object):
547
580
  # of mappings, this won't raise.
548
581
  if isinstance(op, (str, bytes)):
549
582
  raise InvalidJsonPatch("Document is expected to be sequence of "
550
- "operations, got a sequence of strings.")
583
+ "operations, got a sequence of strings.",
584
+ op=op)
551
585
 
552
586
  self._get_operation(op)
553
587
 
@@ -597,7 +631,7 @@ class JsonPatch(object):
597
631
  @classmethod
598
632
  def from_diff(
599
633
  cls, src, dst, optimization=True, dumps=None,
600
- pointer_cls=JsonPointer,
634
+ pointer_cls=JsonPointer, generate_test_ops=False,
601
635
  ):
602
636
  """Creates JsonPatch instance based on comparison of two document
603
637
  objects. Json patch would be created for `src` argument against `dst`
@@ -621,6 +655,12 @@ class JsonPatch(object):
621
655
  :param pointer_cls: JSON pointer class to use.
622
656
  :type pointer_cls: Type[JsonPointer]
623
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
+
624
664
  :return: :class:`JsonPatch` instance.
625
665
 
626
666
  >>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]}
@@ -632,7 +672,8 @@ class JsonPatch(object):
632
672
  """
633
673
  json_dumper = dumps or cls.json_dumper
634
674
  builder = DiffBuilder(src, dst, json_dumper, pointer_cls=pointer_cls,
635
- optimization=optimization)
675
+ optimization=optimization,
676
+ generate_test_ops=generate_test_ops)
636
677
  builder._compare_values((), None, src, dst)
637
678
  ops = list(builder.execute())
638
679
  return cls(ops, pointer_cls=pointer_cls)
@@ -671,18 +712,18 @@ class JsonPatch(object):
671
712
 
672
713
  def _get_operation(self, operation):
673
714
  if not isinstance(operation, Mapping):
674
- raise InvalidJsonPatch("Operation must be an object")
715
+ raise InvalidJsonPatch("Operation must be an object", op=operation)
675
716
 
676
717
  if 'op' not in operation:
677
- raise InvalidJsonPatch("Operation does not contain 'op' member")
718
+ raise InvalidJsonPatch("Operation does not contain 'op' member", op=operation)
678
719
 
679
720
  op = operation['op']
680
721
 
681
722
  if not isinstance(op, (str, bytes)):
682
- raise InvalidJsonPatch("Operation's op must be a string")
723
+ raise InvalidJsonPatch("Operation's op must be a string", op=operation)
683
724
 
684
725
  if op not in self.operations:
685
- raise InvalidJsonPatch("Unknown operation {0!r}".format(op))
726
+ raise InvalidJsonPatch("Unknown operation {0!r}".format(op), op=operation)
686
727
 
687
728
  cls = self.operations[op]
688
729
  return cls(operation, pointer_cls=self.pointer_cls)
@@ -691,10 +732,14 @@ class JsonPatch(object):
691
732
  class DiffBuilder(object):
692
733
 
693
734
  def __init__(self, src_doc, dst_doc, dumps=json.dumps, pointer_cls=JsonPointer,
694
- optimization=True):
735
+ optimization=True, generate_test_ops=False):
695
736
  self.dumps = dumps
696
737
  self.pointer_cls = pointer_cls
697
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 = {}
698
743
  self.index_storage = [{}, {}]
699
744
  self.__root = root = []
700
745
  self.src_doc = src_doc
@@ -841,6 +886,10 @@ class DiffBuilder(object):
841
886
  source = self._parts(removed)
842
887
  # RFC 6902 does not allow moving a value into its own children
843
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)
844
893
  self.remove(index)
845
894
  if source != target:
846
895
  self.insert({'op': 'move', 'from': removed,
@@ -875,14 +924,27 @@ class DiffBuilder(object):
875
924
  self._set_present(added_location, False)
876
925
  return
877
926
 
927
+ test_index = self._insert_test(location, item)
878
928
  self._set_present(location, False)
879
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
880
932
  self.store_index(item, new_index, _ST_REMOVE)
881
933
 
882
- 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)
883
945
  self.insert({
884
946
  'op': 'replace',
885
- 'path': self._location(_path_join(path, key)),
947
+ 'path': location,
886
948
  'value': item,
887
949
  })
888
950
 
@@ -1017,7 +1079,7 @@ class DiffBuilder(object):
1017
1079
  return
1018
1080
 
1019
1081
  else:
1020
- self._item_replaced(path, key, dst)
1082
+ self._item_replaced(path, key, dst, src)
1021
1083
 
1022
1084
 
1023
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=JHVEKitWJsb_89w6zcg8B2Q4whNvJOLU2uKQEzW4ROQ,44263
2
- jsonpatch_cli.py,sha256=IRfXFLpY4qF6QRGSZA227tIZo7ly_RXjImOrMvz8Lag,6043
3
- jsonpatch-1.39.dist-info/licenses/AUTHORS,sha256=hOtEnBGbfDegKjzMDEl5vuVJyczbI2PlYE2ho4LjGNQ,140
4
- jsonpatch-1.39.dist-info/licenses/LICENSE,sha256=Q5PrZzP6HjZ_QXabOC9PG-e_Da6x4kPtkrP12Lr9I28,1481
5
- jsonpatch-1.39.dist-info/METADATA,sha256=UTTMETeu0ZinFeuu2bwHdtutUbDVW8MoEEGRRfFt62o,3672
6
- jsonpatch-1.39.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
- jsonpatch-1.39.dist-info/entry_points.txt,sha256=aY9ormBVRZHHDaAeMcdqTBwZ-ax7GvBTSQ33I75xtZM,98
8
- jsonpatch-1.39.dist-info/top_level.txt,sha256=efUF341HUk8WcQKnFt8ZLKEKNrm1kFT76Flr38Fjno0,24
9
- jsonpatch-1.39.dist-info/RECORD,,