jsonpatch 1.47__tar.gz → 1.48__tar.gz
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.
- {jsonpatch-1.47/jsonpatch.egg-info → jsonpatch-1.48}/PKG-INFO +1 -1
- {jsonpatch-1.47 → jsonpatch-1.48}/doc/commandline.rst +5 -0
- {jsonpatch-1.47 → jsonpatch-1.48/jsonpatch.egg-info}/PKG-INFO +1 -1
- {jsonpatch-1.47 → jsonpatch-1.48}/jsonpatch.py +129 -14
- {jsonpatch-1.47 → jsonpatch-1.48}/jsonpatch_cli.py +54 -13
- {jsonpatch-1.47 → jsonpatch-1.48}/tests.py +371 -6
- {jsonpatch-1.47 → jsonpatch-1.48}/LICENSE +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/MANIFEST.in +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/README.md +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/doc/Makefile +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/doc/conf.py +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/doc/index.rst +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/doc/mod-jsonpatch.rst +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/doc/requirements.txt +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/doc/tutorial.rst +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/ext_tests.py +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/jsonpatch-stubs/__init__.pyi +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/jsonpatch.egg-info/SOURCES.txt +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/jsonpatch.egg-info/dependency_links.txt +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/jsonpatch.egg-info/entry_points.txt +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/jsonpatch.egg-info/requires.txt +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/jsonpatch.egg-info/top_level.txt +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/makefile +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/property_tests.py +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/pyproject.toml +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/pytest.ini +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/requirements-dev.txt +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/requirements.txt +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/setup.cfg +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/setup.py +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/tests.js +0 -0
- {jsonpatch-1.47 → jsonpatch-1.48}/typetests/usage.py +0 -0
|
@@ -7,6 +7,11 @@ The JSON patch package contains the commandline utilities ``jsondiff`` and
|
|
|
7
7
|
Both utilities read JSON files as UTF-8. When ``jsonpatch`` modifies a file
|
|
8
8
|
in-place, it also writes UTF-8.
|
|
9
9
|
|
|
10
|
+
If a file cannot be read or written, is not valid JSON, or if the patch
|
|
11
|
+
cannot be applied, both print a one-line error message to standard error and
|
|
12
|
+
exit with status 2. ``jsondiff`` exits with status 1 if the files differ,
|
|
13
|
+
like ``diff``, and with 0 if they are equal.
|
|
14
|
+
|
|
10
15
|
``jsondiff``
|
|
11
16
|
------------
|
|
12
17
|
|
|
@@ -59,7 +59,7 @@ _JSONPOINTER_FROM_PARTS = JsonPointer.from_parts.__func__
|
|
|
59
59
|
|
|
60
60
|
# Will be parsed by setup.py to determine package metadata
|
|
61
61
|
__author__ = 'Stefan Kögl <stefan@skoegl.net>'
|
|
62
|
-
__version__ = '1.
|
|
62
|
+
__version__ = '1.48'
|
|
63
63
|
__website__ = 'https://github.com/stefankoegl/python-json-patch'
|
|
64
64
|
__license__ = 'BSD-3-Clause'
|
|
65
65
|
|
|
@@ -205,6 +205,9 @@ def make_patch(src, dst, pointer_cls=JsonPointer, generate_test_ops=False):
|
|
|
205
205
|
fails on documents that differ from `src` there.
|
|
206
206
|
:type generate_test_ops: bool
|
|
207
207
|
|
|
208
|
+
:raises TypeError: if the documents differ in an object member whose
|
|
209
|
+
name is not a string, see :meth:`JsonPatch.from_diff`.
|
|
210
|
+
|
|
208
211
|
>>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]}
|
|
209
212
|
>>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]}
|
|
210
213
|
>>> patch = make_patch(src, dst)
|
|
@@ -437,6 +440,23 @@ def _reorder(mapping, keys):
|
|
|
437
440
|
mapping[key] = mapping.pop(key)
|
|
438
441
|
|
|
439
442
|
|
|
443
|
+
def _plain_operation(operation, pointer_cls):
|
|
444
|
+
"""Returns operation as a dict whose 'path' and 'from' are strings.
|
|
445
|
+
|
|
446
|
+
Both can be given as pointer objects instead. These are replaced by
|
|
447
|
+
their paths, so that the operation is JSON-serializable, and can be
|
|
448
|
+
compared to one that was given the paths. This is done in a copy; an
|
|
449
|
+
operation that is a dict already and has no pointer objects is returned
|
|
450
|
+
as it is.
|
|
451
|
+
"""
|
|
452
|
+
paths = {member: operation[member].path for member in ('path', 'from')
|
|
453
|
+
if member in operation and
|
|
454
|
+
isinstance(operation[member], pointer_cls)}
|
|
455
|
+
if paths:
|
|
456
|
+
return dict(operation, **paths)
|
|
457
|
+
return operation if isinstance(operation, dict) else dict(operation)
|
|
458
|
+
|
|
459
|
+
|
|
440
460
|
class PatchOperation:
|
|
441
461
|
"""A single operation inside a JSON Patch."""
|
|
442
462
|
|
|
@@ -491,13 +511,17 @@ class PatchOperation:
|
|
|
491
511
|
def __hash__(self):
|
|
492
512
|
# Other members can hold arrays or objects, which are unhashable.
|
|
493
513
|
# Operations that compare equal still have equal 'op' and 'path'.
|
|
494
|
-
|
|
514
|
+
operation = _plain_operation(self.operation, self.pointer_cls)
|
|
515
|
+
return hash((operation.get('op'), operation['path']))
|
|
495
516
|
|
|
496
517
|
def __eq__(self, other):
|
|
497
518
|
if not isinstance(other, PatchOperation):
|
|
498
519
|
return False
|
|
499
520
|
# e.g. tests for 1 and for true behave differently
|
|
500
|
-
|
|
521
|
+
# and paths are equal to pointer objects for them
|
|
522
|
+
return _json_equal(
|
|
523
|
+
_plain_operation(self.operation, self.pointer_cls),
|
|
524
|
+
_plain_operation(other.operation, other.pointer_cls))
|
|
501
525
|
|
|
502
526
|
@property
|
|
503
527
|
def path(self):
|
|
@@ -962,8 +986,7 @@ class JsonPatch:
|
|
|
962
986
|
self._get_operation(op)
|
|
963
987
|
# Keep validation errors tied to the original input, but expose
|
|
964
988
|
# concrete, JSON-serializable operation dictionaries on success.
|
|
965
|
-
|
|
966
|
-
self.patch[index] = dict(op)
|
|
989
|
+
self.patch[index] = _plain_operation(op, self.pointer_cls)
|
|
967
990
|
|
|
968
991
|
def __str__(self):
|
|
969
992
|
"""str(self) -> self.to_string()"""
|
|
@@ -1043,6 +1066,13 @@ class JsonPatch:
|
|
|
1043
1066
|
|
|
1044
1067
|
:return: :class:`JsonPatch` instance.
|
|
1045
1068
|
|
|
1069
|
+
:raises TypeError: if the documents differ in, or inside of, an
|
|
1070
|
+
object member whose name is not a string, such
|
|
1071
|
+
as the ``1`` of ``{1: 'a'}``. The path of an
|
|
1072
|
+
operation can't refer to such a member, which
|
|
1073
|
+
does not exist in JSON. Other differences of
|
|
1074
|
+
documents with such members are no problem.
|
|
1075
|
+
|
|
1046
1076
|
>>> src = {'foo': 'bar', 'numbers': [1, 3, 4, 8]}
|
|
1047
1077
|
>>> dst = {'baz': 'qux', 'numbers': [1, 4, 7]}
|
|
1048
1078
|
>>> patch = JsonPatch.from_diff(src, dst)
|
|
@@ -1055,7 +1085,7 @@ class JsonPatch:
|
|
|
1055
1085
|
optimization=optimization,
|
|
1056
1086
|
generate_test_ops=generate_test_ops)
|
|
1057
1087
|
builder._compare_values((), None, src, dst)
|
|
1058
|
-
ops =
|
|
1088
|
+
ops = _json_copy(list(builder.execute()))
|
|
1059
1089
|
return cls(ops, pointer_cls=pointer_cls)
|
|
1060
1090
|
|
|
1061
1091
|
def to_string(self, dumps=None):
|
|
@@ -1175,7 +1205,7 @@ class JsonPatchWithAppend(JsonPatch):
|
|
|
1175
1205
|
optimization=optimization,
|
|
1176
1206
|
generate_test_ops=generate_test_ops)
|
|
1177
1207
|
builder._compare_values((), None, src, dst)
|
|
1178
|
-
ops =
|
|
1208
|
+
ops = _json_copy(list(builder.execute()))
|
|
1179
1209
|
return cls(ops, pointer_cls=pointer_cls)
|
|
1180
1210
|
|
|
1181
1211
|
|
|
@@ -1184,6 +1214,10 @@ class DiffBuilder:
|
|
|
1184
1214
|
def __init__(self, src_doc, dst_doc, dumps=json.dumps, pointer_cls=JsonPointer,
|
|
1185
1215
|
optimization=True, generate_test_ops=False):
|
|
1186
1216
|
self.dumps = dumps
|
|
1217
|
+
# json.dumps builds a JSONEncoder for every call; the default dumps
|
|
1218
|
+
# is called once per added and removed value, so cache its encoder
|
|
1219
|
+
self._canonical_dumps = (json.JSONEncoder(sort_keys=True).encode
|
|
1220
|
+
if dumps is json.dumps else None)
|
|
1187
1221
|
self.pointer_cls = pointer_cls
|
|
1188
1222
|
self.optimization = optimization
|
|
1189
1223
|
self.generate_test_ops = generate_test_ops
|
|
@@ -1201,6 +1235,17 @@ class DiffBuilder:
|
|
|
1201
1235
|
def _move_key(self, value):
|
|
1202
1236
|
""" A key of value, which is equal for values that are equal in JSON,
|
|
1203
1237
|
so that e.g. [1] is not moved where [true] is added """
|
|
1238
|
+
if self._canonical_dumps is not None:
|
|
1239
|
+
try:
|
|
1240
|
+
# sort_keys gives the same string as _sorted_members for JSON
|
|
1241
|
+
# documents, without building a sorted copy of every added or
|
|
1242
|
+
# removed subtree
|
|
1243
|
+
return self._canonical_dumps(value)
|
|
1244
|
+
except (TypeError, ValueError, RecursionError):
|
|
1245
|
+
# Values like UserDict and UserList are normalized by
|
|
1246
|
+
# _sorted_members, but the encoder cannot serialize them as
|
|
1247
|
+
# they are, so fall through to the generic path below
|
|
1248
|
+
pass
|
|
1204
1249
|
try:
|
|
1205
1250
|
# Serialized like in _differing_runs
|
|
1206
1251
|
return self.dumps(_sorted_members(value))
|
|
@@ -1252,8 +1297,7 @@ class DiffBuilder:
|
|
|
1252
1297
|
op_second['op'] == 'add':
|
|
1253
1298
|
yield {
|
|
1254
1299
|
'op': 'replace',
|
|
1255
|
-
'path':
|
|
1256
|
-
self.pointer_cls),
|
|
1300
|
+
'path': self._path(op_second['path']),
|
|
1257
1301
|
'value': op_second['value'],
|
|
1258
1302
|
}
|
|
1259
1303
|
i += 2
|
|
@@ -1262,11 +1306,20 @@ class DiffBuilder:
|
|
|
1262
1306
|
operation = operations[i]
|
|
1263
1307
|
for member in ('from', 'path'):
|
|
1264
1308
|
if member in operation:
|
|
1265
|
-
operation[member] =
|
|
1266
|
-
self.pointer_cls)
|
|
1309
|
+
operation[member] = self._path(operation[member])
|
|
1267
1310
|
yield operation
|
|
1268
1311
|
i += 1
|
|
1269
1312
|
|
|
1313
|
+
def _path(self, parts):
|
|
1314
|
+
""" The path of an operation, in the syntax of pointer_cls """
|
|
1315
|
+
for part in parts:
|
|
1316
|
+
if isinstance(part, _NonStringKey):
|
|
1317
|
+
raise TypeError(
|
|
1318
|
+
"can't create an operation for the object member "
|
|
1319
|
+
"{0!r}: its name is not a string, which the path of an "
|
|
1320
|
+
"operation can't refer to".format(part.key))
|
|
1321
|
+
return path_join(parts, self.pointer_cls)
|
|
1322
|
+
|
|
1270
1323
|
def _replay(self):
|
|
1271
1324
|
""" Applies the operations to the arrays of the source document, and
|
|
1272
1325
|
returns them with the array indices at which they apply """
|
|
@@ -1406,13 +1459,13 @@ class DiffBuilder:
|
|
|
1406
1459
|
intersection = [key for key in src if key in dst]
|
|
1407
1460
|
|
|
1408
1461
|
for key in removed_keys:
|
|
1409
|
-
self._item_removed(path,
|
|
1462
|
+
self._item_removed(path, _member_name(key), src[key])
|
|
1410
1463
|
|
|
1411
1464
|
for key in added_keys:
|
|
1412
|
-
self._item_added(path,
|
|
1465
|
+
self._item_added(path, _member_name(key), dst[key])
|
|
1413
1466
|
|
|
1414
1467
|
for key in intersection:
|
|
1415
|
-
self._compare_values(path,
|
|
1468
|
+
self._compare_values(path, _member_name(key), src[key], dst[key])
|
|
1416
1469
|
|
|
1417
1470
|
def _differing_runs(self, src, dst):
|
|
1418
1471
|
""" Returns (i1, i2, j1, j2) for each run of items src[i1:i2] that is
|
|
@@ -1548,6 +1601,37 @@ class _AppendDiffBuilder(DiffBuilder):
|
|
|
1548
1601
|
super()._item_replaced(path, key, item, old_item)
|
|
1549
1602
|
|
|
1550
1603
|
|
|
1604
|
+
class _NonStringKey(str):
|
|
1605
|
+
""" Takes the place of an object key that is not a string in the parts
|
|
1606
|
+
of an operation.
|
|
1607
|
+
|
|
1608
|
+
A path can only refer to members whose names are strings: '/1' is the
|
|
1609
|
+
member '1', not the member 1. Members with other names are compared like
|
|
1610
|
+
all others, as nothing is wrong unless they differ; an operation for
|
|
1611
|
+
such a member, or for something in it, can't be written, though (see
|
|
1612
|
+
DiffBuilder._path). """
|
|
1613
|
+
|
|
1614
|
+
def __new__(cls, key):
|
|
1615
|
+
self = super().__new__(cls, key)
|
|
1616
|
+
self.key = key
|
|
1617
|
+
return self
|
|
1618
|
+
|
|
1619
|
+
# The member 1 is not the member '1', which this is equal to as a str
|
|
1620
|
+
def __eq__(self, other):
|
|
1621
|
+
return isinstance(other, _NonStringKey) and self.key == other.key
|
|
1622
|
+
|
|
1623
|
+
def __ne__(self, other):
|
|
1624
|
+
return not self == other
|
|
1625
|
+
|
|
1626
|
+
def __hash__(self):
|
|
1627
|
+
return hash(self.key)
|
|
1628
|
+
|
|
1629
|
+
|
|
1630
|
+
def _member_name(key):
|
|
1631
|
+
""" The part of an operation for the object key """
|
|
1632
|
+
return key if isinstance(key, str) else _NonStringKey(key)
|
|
1633
|
+
|
|
1634
|
+
|
|
1551
1635
|
def _positional_cost(old, new):
|
|
1552
1636
|
""" Estimates how many operations change old into new, if the items of
|
|
1553
1637
|
arrays are compared by position """
|
|
@@ -1581,6 +1665,37 @@ def _json_equal(first, second):
|
|
|
1581
1665
|
return first == second
|
|
1582
1666
|
|
|
1583
1667
|
|
|
1668
|
+
def _json_copy(value, memo=None):
|
|
1669
|
+
""" Copies a JSON value like copy.deepcopy, but without the generic
|
|
1670
|
+
dispatch for dicts, lists and scalars, which dominate patch creation.
|
|
1671
|
+
|
|
1672
|
+
Values that are not plain JSON containers keep the copy.deepcopy
|
|
1673
|
+
behaviour, and shared references are preserved through memo. """
|
|
1674
|
+
if value is None or type(value) in (str, int, float, bool):
|
|
1675
|
+
return value
|
|
1676
|
+
if memo is None:
|
|
1677
|
+
memo = {}
|
|
1678
|
+
value_id = id(value)
|
|
1679
|
+
copied = memo.get(value_id)
|
|
1680
|
+
if copied is not None:
|
|
1681
|
+
return copied
|
|
1682
|
+
value_type = type(value)
|
|
1683
|
+
if value_type is dict:
|
|
1684
|
+
# memo must hold the new dict before the children are copied, so
|
|
1685
|
+
# that self-referential documents terminate like copy.deepcopy
|
|
1686
|
+
copied = memo[value_id] = {}
|
|
1687
|
+
for key, item in value.items():
|
|
1688
|
+
# copy.deepcopy copies the keys too, through the same memo, so
|
|
1689
|
+
# that a key and a value that are the same object stay shared
|
|
1690
|
+
copied[_json_copy(key, memo)] = _json_copy(item, memo)
|
|
1691
|
+
return copied
|
|
1692
|
+
if value_type is list:
|
|
1693
|
+
copied = memo[value_id] = []
|
|
1694
|
+
copied.extend(_json_copy(item, memo) for item in value)
|
|
1695
|
+
return copied
|
|
1696
|
+
return copy.deepcopy(value, memo)
|
|
1697
|
+
|
|
1698
|
+
|
|
1584
1699
|
def _sorted_members(value):
|
|
1585
1700
|
""" Copies the arrays and objects in value, with the members of objects
|
|
1586
1701
|
sorted by key """
|
|
@@ -34,19 +34,38 @@ def _input_files(*streams):
|
|
|
34
34
|
return inputs
|
|
35
35
|
|
|
36
36
|
|
|
37
|
-
def
|
|
37
|
+
def _load(stream, loads=json.loads):
|
|
38
|
+
""" Parses the JSON document in stream; errors name the file """
|
|
38
39
|
try:
|
|
39
|
-
|
|
40
|
+
return loads(stream.read())
|
|
41
|
+
except ValueError as ex:
|
|
42
|
+
# invalid JSON or, as a UnicodeDecodeError, invalid UTF-8
|
|
43
|
+
name = getattr(stream, 'name', '<input>')
|
|
44
|
+
raise ValueError('{0}: {1}'.format(name, ex)) from ex
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _run(parser, program):
|
|
48
|
+
""" Runs a command line program. Errors in its input, and in reading
|
|
49
|
+
and writing files, are reported in one line, with exit status 2 """
|
|
50
|
+
try:
|
|
51
|
+
program()
|
|
40
52
|
except KeyboardInterrupt:
|
|
41
53
|
sys.exit(1)
|
|
54
|
+
except (jsonpatch.JsonPatchException, jsonpatch.JsonPointerException,
|
|
55
|
+
ValueError, OSError) as ex:
|
|
56
|
+
parser.exit(2, '{0}: error: {1}\n'.format(parser.prog, ex))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def jsondiff_main():
|
|
60
|
+
_run(jsondiff_parser, diff_files)
|
|
42
61
|
|
|
43
62
|
|
|
44
63
|
def diff_files():
|
|
45
64
|
""" Diffs two JSON files and prints a patch """
|
|
46
65
|
args = jsondiff_parser.parse_args()
|
|
47
66
|
with _input_files(args.FILE1, args.FILE2):
|
|
48
|
-
doc1 =
|
|
49
|
-
doc2 =
|
|
67
|
+
doc1 = _load(args.FILE1)
|
|
68
|
+
doc2 = _load(args.FILE2)
|
|
50
69
|
patch = jsonpatch.make_patch(doc1, doc2, generate_test_ops=args.test_ops)
|
|
51
70
|
if patch.patch:
|
|
52
71
|
print(json.dumps(patch.patch, indent=args.indent, ensure_ascii=not args.preserve_unicode))
|
|
@@ -73,11 +92,25 @@ jsonpatch_parser.add_argument('-u', '--preserve-unicode', action='store_true',
|
|
|
73
92
|
help='Output Unicode character as-is without using Code Point')
|
|
74
93
|
|
|
75
94
|
|
|
76
|
-
def
|
|
95
|
+
def _link_backup(original, temporary):
|
|
96
|
+
""" Links original to its backup name, replacing an older backup """
|
|
97
|
+
# link() does not overwrite an existing file, so the link is created
|
|
98
|
+
# under a temporary name, and then moved over an older backup
|
|
99
|
+
link = temporary + '.orig'
|
|
100
|
+
os.link(original, link)
|
|
77
101
|
try:
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
102
|
+
os.replace(link, original + '.orig')
|
|
103
|
+
finally:
|
|
104
|
+
# It is still there if replacing failed, and if the older backup is
|
|
105
|
+
# a link to original already, as replace() does nothing then
|
|
106
|
+
try:
|
|
107
|
+
os.unlink(link)
|
|
108
|
+
except OSError:
|
|
109
|
+
pass
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def jsonpatch_main():
|
|
113
|
+
_run(jsonpatch_parser, patch_files)
|
|
81
114
|
|
|
82
115
|
|
|
83
116
|
def patch_files():
|
|
@@ -86,8 +119,9 @@ def patch_files():
|
|
|
86
119
|
# The inputs are closed before anything is written, as Windows cannot
|
|
87
120
|
# replace ORIGINAL while it is open.
|
|
88
121
|
with _input_files(args.ORIGINAL, args.PATCH):
|
|
89
|
-
doc =
|
|
90
|
-
|
|
122
|
+
doc = _load(args.ORIGINAL)
|
|
123
|
+
patch = _load(args.PATCH, jsonpatch.JsonPatch.from_string)
|
|
124
|
+
result = patch.apply(doc)
|
|
91
125
|
|
|
92
126
|
if args.in_place:
|
|
93
127
|
dirname = os.path.abspath(os.path.dirname(args.ORIGINAL.name))
|
|
@@ -121,7 +155,13 @@ def patch_files():
|
|
|
121
155
|
# the original (if desired) and writing a new file.
|
|
122
156
|
|
|
123
157
|
if args.backup:
|
|
124
|
-
|
|
158
|
+
# like in atomic mode, an older backup is replaced
|
|
159
|
+
os.replace(args.ORIGINAL.name, args.ORIGINAL.name + '.orig')
|
|
160
|
+
# A same-inode replace may leave the original name in place.
|
|
161
|
+
try:
|
|
162
|
+
os.unlink(args.ORIGINAL.name)
|
|
163
|
+
except FileNotFoundError:
|
|
164
|
+
pass
|
|
125
165
|
fp = open(args.ORIGINAL.name, 'w', encoding='utf-8')
|
|
126
166
|
atomic = False
|
|
127
167
|
|
|
@@ -157,11 +197,12 @@ def patch_files():
|
|
|
157
197
|
if atomic:
|
|
158
198
|
try:
|
|
159
199
|
# Complete the atomic replace by linking the original
|
|
160
|
-
# to a backup (if desired),
|
|
200
|
+
# to a backup (if desired), which replaces an older
|
|
201
|
+
# backup, fixing up the permissions
|
|
161
202
|
# on the temporary file, and moving it into place.
|
|
162
203
|
|
|
163
204
|
if args.backup:
|
|
164
|
-
|
|
205
|
+
_link_backup(args.ORIGINAL.name, pathname)
|
|
165
206
|
os.chmod(pathname, os.stat(args.ORIGINAL.name).st_mode)
|
|
166
207
|
os.replace(pathname, args.ORIGINAL.name)
|
|
167
208
|
|
|
@@ -426,6 +426,26 @@ class ApplyPatchTestCase(unittest.TestCase):
|
|
|
426
426
|
jsonpatch.apply_patch,
|
|
427
427
|
obj, [{'op': 'test', 'path': '/bar', 'value': 'bar'}])
|
|
428
428
|
|
|
429
|
+
def test_test_compares_unicode_strings_exactly(self):
|
|
430
|
+
composed = '\u00e9'
|
|
431
|
+
decomposed = 'e\u0301'
|
|
432
|
+
for actual, expected in (
|
|
433
|
+
(composed, decomposed),
|
|
434
|
+
([composed], [decomposed]),
|
|
435
|
+
({'name': composed}, {'name': decomposed})):
|
|
436
|
+
with self.subTest(actual=actual):
|
|
437
|
+
doc = {'value': actual, 'updated': False}
|
|
438
|
+
matching = [{'op': 'test', 'path': '/value', 'value': actual}]
|
|
439
|
+
self.assertEqual(jsonpatch.apply_patch(doc, matching), doc)
|
|
440
|
+
|
|
441
|
+
patch = [
|
|
442
|
+
{'op': 'test', 'path': '/value', 'value': expected},
|
|
443
|
+
{'op': 'replace', 'path': '/updated', 'value': True},
|
|
444
|
+
]
|
|
445
|
+
with self.assertRaises(jsonpatch.JsonPatchTestFailed):
|
|
446
|
+
jsonpatch.apply_patch(doc, patch, in_place=True)
|
|
447
|
+
self.assertEqual(doc, {'value': actual, 'updated': False})
|
|
448
|
+
|
|
429
449
|
def test_test_numbers_by_value(self):
|
|
430
450
|
obj = {'a': 1, 'b': [0.0], 'c': {'d': 2}}
|
|
431
451
|
jsonpatch.apply_patch(obj, [{'op': 'test', 'path': '/a', 'value': 1.0},
|
|
@@ -1040,6 +1060,75 @@ class MakePatchTestCase(unittest.TestCase):
|
|
|
1040
1060
|
res = patch.apply(src)
|
|
1041
1061
|
self.assertEqual(json.dumps(res), json.dumps(dst))
|
|
1042
1062
|
|
|
1063
|
+
def test_changed_member_with_non_string_name_is_rejected(self):
|
|
1064
|
+
"""A path can't refer to such a member: '/1' is the member '1', so
|
|
1065
|
+
the patch did not apply to src, or added a member '1' to it"""
|
|
1066
|
+
cases = [
|
|
1067
|
+
({1: 'a'}, {1: 'b'}),
|
|
1068
|
+
({1: 'a'}, {}),
|
|
1069
|
+
({}, {1: 'a'}),
|
|
1070
|
+
({1: 'a'}, {1: 'a', 2: 'b'}),
|
|
1071
|
+
({1: 'a'}, {'1': 'a'}),
|
|
1072
|
+
({None: 1}, {None: 2}),
|
|
1073
|
+
({True: 1}, {True: 2}),
|
|
1074
|
+
({1.5: 1}, {1.5: 2}),
|
|
1075
|
+
({(1, 2): 1}, {(1, 2): 2}),
|
|
1076
|
+
# inside of such a member
|
|
1077
|
+
({1: {'a': 1}}, {1: {'a': 2}}),
|
|
1078
|
+
({1: [1, 2]}, {1: [1, 2, 3]}),
|
|
1079
|
+
({'a': [{1: 'a'}]}, {'a': [{1: 'b'}]}),
|
|
1080
|
+
# moved from or to such a member
|
|
1081
|
+
({'a': {1: [1, 2]}}, {'a': {}, 'b': [1, 2]}),
|
|
1082
|
+
({'a': {}, 'b': [1, 2]}, {'a': {1: [1, 2]}}),
|
|
1083
|
+
]
|
|
1084
|
+
for src, dst in cases:
|
|
1085
|
+
for kwargs in ({}, {'optimization': False},
|
|
1086
|
+
{'generate_test_ops': True}):
|
|
1087
|
+
with self.subTest(src=src, dst=dst, **kwargs):
|
|
1088
|
+
with self.assertRaises(TypeError) as caught:
|
|
1089
|
+
jsonpatch.JsonPatch.from_diff(src, dst, **kwargs)
|
|
1090
|
+
self.assertIn('not a string', str(caught.exception))
|
|
1091
|
+
with self.assertRaises(TypeError) as caught:
|
|
1092
|
+
jsonpatch.make_patch({1: 'a'}, {1: 'b'})
|
|
1093
|
+
self.assertIn('object member 1:', str(caught.exception))
|
|
1094
|
+
with self.assertRaises(TypeError):
|
|
1095
|
+
jsonpatch.JsonPatchWithAppend.from_diff({1: 'a'}, {1: 'ab'})
|
|
1096
|
+
|
|
1097
|
+
def test_non_string_member_names_differ_from_strings(self):
|
|
1098
|
+
name = jsonpatch._member_name(1)
|
|
1099
|
+
self.assertTrue(name != '1')
|
|
1100
|
+
self.assertFalse(name == '1')
|
|
1101
|
+
self.assertFalse(name != jsonpatch._member_name(1))
|
|
1102
|
+
self.assertEqual(hash(name), hash(jsonpatch._member_name(1)))
|
|
1103
|
+
self.assertEqual(jsonpatch._member_name('a'), 'a')
|
|
1104
|
+
|
|
1105
|
+
def test_unchanged_member_with_non_string_name_is_accepted(self):
|
|
1106
|
+
cases = [
|
|
1107
|
+
({1: 'a'}, {1: 'a'}),
|
|
1108
|
+
({1: 'a', 'b': 0}, {1: 'a', 'b': 1}),
|
|
1109
|
+
({1: {2: [3]}, 'b': 0}, {1: {2: [3]}, 'c': 0}),
|
|
1110
|
+
([{None: 1}, 2], [2, {None: 1}]),
|
|
1111
|
+
# members of values that are added, removed or moved as a whole
|
|
1112
|
+
({}, {'a': {1: 'a'}}),
|
|
1113
|
+
({'a': {1: 'a'}}, {}),
|
|
1114
|
+
({'a': {1: 'a'}}, {'b': {1: 'a'}}),
|
|
1115
|
+
([1, 2], [1, {3: 4}, 2]),
|
|
1116
|
+
({'a': 1}, {'a': {1: 'a'}}),
|
|
1117
|
+
# the member '1' is not the member 1
|
|
1118
|
+
({1: 'a', '1': 'b'}, {1: 'a', '1': 'c'}),
|
|
1119
|
+
({1: 'a', '1': 'b'}, {1: 'a'}),
|
|
1120
|
+
]
|
|
1121
|
+
for src, dst in cases:
|
|
1122
|
+
for optimization in (True, False):
|
|
1123
|
+
with self.subTest(src=src, dst=dst, optimization=optimization):
|
|
1124
|
+
original = copy.deepcopy(src)
|
|
1125
|
+
patch = jsonpatch.JsonPatch.from_diff(
|
|
1126
|
+
src, dst, optimization=optimization)
|
|
1127
|
+
self.assertEqual(patch.apply(src), dst)
|
|
1128
|
+
self.assertEqual(src, original)
|
|
1129
|
+
for operation in patch:
|
|
1130
|
+
self.assertIs(type(operation['path']), str)
|
|
1131
|
+
|
|
1043
1132
|
def test_move_only_values_equal_in_given_dumps(self):
|
|
1044
1133
|
"""The given dumps decides which values are the same"""
|
|
1045
1134
|
src = {'a': decimal.Decimal('1.0')}
|
|
@@ -1379,6 +1468,38 @@ class OptimizationTests(unittest.TestCase):
|
|
|
1379
1468
|
self.assertEqual({op['op'] for op in patch}, {'move'})
|
|
1380
1469
|
self.assertEqual(patch.apply(src), dst)
|
|
1381
1470
|
|
|
1471
|
+
def test_move_of_non_json_containers(self):
|
|
1472
|
+
""" UserDict and UserList get the same move key as the plain dict
|
|
1473
|
+
and list with the same members """
|
|
1474
|
+
src = [collections.UserDict({'x': 1}), 'B',
|
|
1475
|
+
collections.UserList([1, 2])]
|
|
1476
|
+
dst = ['B', collections.UserList([1, 2]),
|
|
1477
|
+
collections.UserDict({'x': 1})]
|
|
1478
|
+
patch = jsonpatch.make_patch(src, dst)
|
|
1479
|
+
self.assertEqual(patch.patch,
|
|
1480
|
+
[{'op': 'move', 'from': '/0', 'path': '/2'}])
|
|
1481
|
+
self.assertEqual(patch.to_string(),
|
|
1482
|
+
'[{"op": "move", "from": "/0", "path": "/2"}]')
|
|
1483
|
+
self.assertEqual(patch.apply(src), dst)
|
|
1484
|
+
|
|
1485
|
+
def test_dict_keys_are_copied_with_the_values(self):
|
|
1486
|
+
""" The patch keeps its own copy of the keys, and a key that is also
|
|
1487
|
+
a value stays the same object in it """
|
|
1488
|
+
class Key(str):
|
|
1489
|
+
pass
|
|
1490
|
+
key = Key('k')
|
|
1491
|
+
key.tag = ['original']
|
|
1492
|
+
src = {'a': 1}
|
|
1493
|
+
dst = {'a': 1, 'x': {key: key}}
|
|
1494
|
+
patch = jsonpatch.make_patch(src, dst)
|
|
1495
|
+
added = [op for op in patch.patch if op['op'] == 'add'][-1]['value']
|
|
1496
|
+
copied_key, = added
|
|
1497
|
+
self.assertIsNot(copied_key, key)
|
|
1498
|
+
self.assertIs(added[copied_key], copied_key)
|
|
1499
|
+
self.assertEqual(copied_key.tag, ['original'])
|
|
1500
|
+
copied_key.tag.append('changed')
|
|
1501
|
+
self.assertEqual(key.tag, ['original'])
|
|
1502
|
+
|
|
1382
1503
|
def test_success_if_replace_inside_dict(self):
|
|
1383
1504
|
src = [{'a': 1, 'foo': {'b': 2, 'd': 5}}]
|
|
1384
1505
|
dst = [{'a': 1, 'foo': {'b': 3, 'd': 6}}]
|
|
@@ -1967,6 +2088,95 @@ class JsonPointerTests(unittest.TestCase):
|
|
|
1967
2088
|
])
|
|
1968
2089
|
self.assertEqual(patch.apply({'foo': 1}), {'foo': 1, 'bar': 1})
|
|
1969
2090
|
|
|
2091
|
+
def pointer_and_string_operations(self, pointer_cls=jsonpointer.JsonPointer,
|
|
2092
|
+
paths=('/foo', '/bar/0', '')):
|
|
2093
|
+
foo, bar, root = paths
|
|
2094
|
+
with_strings = [
|
|
2095
|
+
{'op': 'add', 'path': foo, 'value': [1]},
|
|
2096
|
+
{'op': 'move', 'from': foo, 'path': bar},
|
|
2097
|
+
{'op': 'copy', 'from': root, 'path': foo},
|
|
2098
|
+
{'op': 'copy', 'from': foo, 'path': bar},
|
|
2099
|
+
]
|
|
2100
|
+
with_pointers = [
|
|
2101
|
+
{'op': 'add', 'path': pointer_cls(foo), 'value': [1]},
|
|
2102
|
+
{'op': 'move', 'from': pointer_cls(foo), 'path': pointer_cls(bar)},
|
|
2103
|
+
{'op': 'copy', 'from': pointer_cls(root), 'path': foo},
|
|
2104
|
+
{'op': 'copy', 'from': foo, 'path': pointer_cls(bar)},
|
|
2105
|
+
]
|
|
2106
|
+
return with_pointers, with_strings
|
|
2107
|
+
|
|
2108
|
+
def test_patch_with_pointers_is_serializable(self):
|
|
2109
|
+
with_pointers, with_strings = self.pointer_and_string_operations()
|
|
2110
|
+
patch = jsonpatch.JsonPatch(with_pointers)
|
|
2111
|
+
self.assertEqual(patch.patch, with_strings)
|
|
2112
|
+
self.assertEqual(list(patch), with_strings)
|
|
2113
|
+
self.assertEqual(json.loads(patch.to_string()), with_strings)
|
|
2114
|
+
self.assertEqual(json.loads(str(patch)), with_strings)
|
|
2115
|
+
self.assertEqual(jsonpatch.JsonPatch.from_string(patch.to_string()), patch)
|
|
2116
|
+
|
|
2117
|
+
def test_patch_with_pointers_equals_patch_with_strings(self):
|
|
2118
|
+
with_pointers, with_strings = self.pointer_and_string_operations()
|
|
2119
|
+
patch = jsonpatch.JsonPatch(with_pointers)
|
|
2120
|
+
other = jsonpatch.JsonPatch(with_strings)
|
|
2121
|
+
self.assertEqual(patch, other)
|
|
2122
|
+
self.assertEqual(hash(patch), hash(other))
|
|
2123
|
+
self.assertEqual(len({patch, other}), 1)
|
|
2124
|
+
doc = {'bar': []}
|
|
2125
|
+
self.assertEqual(patch.apply(doc), other.apply(doc))
|
|
2126
|
+
|
|
2127
|
+
def test_patch_with_pointers_does_not_change_the_operations(self):
|
|
2128
|
+
with_pointers, _ = self.pointer_and_string_operations()
|
|
2129
|
+
pointers = [(op, member, op[member]) for op in with_pointers
|
|
2130
|
+
for member in ('path', 'from')
|
|
2131
|
+
if isinstance(op.get(member), jsonpointer.JsonPointer)]
|
|
2132
|
+
jsonpatch.JsonPatch(with_pointers).apply({'bar': []})
|
|
2133
|
+
self.assertEqual(len(pointers), 5)
|
|
2134
|
+
for op, member, pointer in pointers:
|
|
2135
|
+
self.assertIs(op[member], pointer)
|
|
2136
|
+
|
|
2137
|
+
def test_patch_with_pointers_as_read_only_mappings(self):
|
|
2138
|
+
with_pointers, with_strings = self.pointer_and_string_operations()
|
|
2139
|
+
patch = jsonpatch.JsonPatch(map(MappingProxyType, with_pointers))
|
|
2140
|
+
self.assertEqual(patch.patch, with_strings)
|
|
2141
|
+
self.assertTrue(all(type(op) is dict for op in patch))
|
|
2142
|
+
|
|
2143
|
+
def test_patch_with_pointers_of_custom_class(self):
|
|
2144
|
+
with_pointers, with_strings = self.pointer_and_string_operations(
|
|
2145
|
+
DotJsonPointer, ('foo', 'bar.0', ''))
|
|
2146
|
+
patch = jsonpatch.JsonPatch(with_pointers, pointer_cls=DotJsonPointer)
|
|
2147
|
+
other = jsonpatch.JsonPatch(with_strings, pointer_cls=DotJsonPointer)
|
|
2148
|
+
self.assertEqual(patch.patch, with_strings)
|
|
2149
|
+
self.assertEqual(patch, other)
|
|
2150
|
+
self.assertEqual(patch.apply({'bar': []}), other.apply({'bar': []}))
|
|
2151
|
+
|
|
2152
|
+
def test_operation_with_pointers_equals_operation_with_strings(self):
|
|
2153
|
+
with_pointers, with_strings = self.pointer_and_string_operations()
|
|
2154
|
+
for pointers, strings in zip(with_pointers, with_strings):
|
|
2155
|
+
with self.subTest(operation=strings):
|
|
2156
|
+
cls = jsonpatch.JsonPatch.operations[strings['op']]
|
|
2157
|
+
operation, other = cls(pointers), cls(strings)
|
|
2158
|
+
self.assertEqual(operation, other)
|
|
2159
|
+
self.assertEqual(other, operation)
|
|
2160
|
+
self.assertEqual(hash(operation), hash(other))
|
|
2161
|
+
self.assertEqual(operation.location, other.location)
|
|
2162
|
+
# setters change the operation it was created from, so it
|
|
2163
|
+
# is not replaced by a copy without pointers
|
|
2164
|
+
self.assertIs(operation.operation, pointers)
|
|
2165
|
+
self.assertNotEqual(
|
|
2166
|
+
jsonpatch.RemoveOperation({'op': 'remove', 'path': jsonpointer.JsonPointer('/a')}),
|
|
2167
|
+
jsonpatch.RemoveOperation({'op': 'remove', 'path': '/b'}))
|
|
2168
|
+
|
|
2169
|
+
def test_operation_setters_with_pointers(self):
|
|
2170
|
+
pointers = {'op': 'move', 'from': jsonpointer.JsonPointer('/a/b'),
|
|
2171
|
+
'path': jsonpointer.JsonPointer('/c/d')}
|
|
2172
|
+
operation = jsonpatch.MoveOperation(pointers)
|
|
2173
|
+
operation.key = 'e'
|
|
2174
|
+
operation.from_key = 'f'
|
|
2175
|
+
self.assertEqual(pointers,
|
|
2176
|
+
{'op': 'move', 'from': '/a/f', 'path': '/c/e'})
|
|
2177
|
+
self.assertEqual(operation.apply({'a': {'f': 1}, 'c': {}}),
|
|
2178
|
+
{'a': {}, 'c': {'e': 1}})
|
|
2179
|
+
|
|
1970
2180
|
|
|
1971
2181
|
class JsonPatchCreationTest(unittest.TestCase):
|
|
1972
2182
|
|
|
@@ -3230,6 +3440,100 @@ class CommandLineTests(ScriptRunner, unittest.TestCase):
|
|
|
3230
3440
|
res = self.run_script('jsondiff', src, dst)
|
|
3231
3441
|
self.assertEqual((res.returncode, res.stdout), (0, ''), res.stderr)
|
|
3232
3442
|
|
|
3443
|
+
def assert_error(self, res, program, *parts):
|
|
3444
|
+
""" The program failed with a one-line message containing parts """
|
|
3445
|
+
self.assertEqual(res.returncode, 2, res.stderr)
|
|
3446
|
+
self.assertEqual(res.stdout, '')
|
|
3447
|
+
self.assertEqual(res.stderr.count('\n'), 1, res.stderr)
|
|
3448
|
+
self.assertTrue(res.stderr.startswith(program + ': error: '), res.stderr)
|
|
3449
|
+
for part in parts:
|
|
3450
|
+
self.assertIn(part, res.stderr)
|
|
3451
|
+
|
|
3452
|
+
def test_jsondiff_reports_invalid_json(self):
|
|
3453
|
+
src = self.write('a.json', {'a': 1})
|
|
3454
|
+
dst = os.path.join(self.dir, 'b.json')
|
|
3455
|
+
with open(dst, 'w', encoding='utf-8') as f:
|
|
3456
|
+
f.write('{"a": ')
|
|
3457
|
+
for files in ((src, dst), (dst, src)):
|
|
3458
|
+
with self.subTest(files=files):
|
|
3459
|
+
res = self.run_script('jsondiff', *files)
|
|
3460
|
+
self.assert_error(res, 'jsondiff', 'b.json', 'line 1 column 7')
|
|
3461
|
+
|
|
3462
|
+
def test_jsondiff_reports_invalid_utf8(self):
|
|
3463
|
+
src = self.write('a.json', {'a': 1})
|
|
3464
|
+
dst = os.path.join(self.dir, 'b.json')
|
|
3465
|
+
with open(dst, 'wb') as f:
|
|
3466
|
+
f.write(b'"\xff"')
|
|
3467
|
+
res = self.run_script('jsondiff', src, dst)
|
|
3468
|
+
self.assert_error(res, 'jsondiff', 'b.json', 'utf-8')
|
|
3469
|
+
|
|
3470
|
+
def test_jsonpatch_reports_failing_patch(self):
|
|
3471
|
+
doc = self.write('doc.json', {'a': 1})
|
|
3472
|
+
cases = [
|
|
3473
|
+
([{'op': 'remove', 'path': '/b'}], "can't remove a non-existent object 'b'"),
|
|
3474
|
+
([{'op': 'test', 'path': '/a', 'value': 2}], 'is not equal to tested value'),
|
|
3475
|
+
([{'op': 'remove', 'path': '/b/c'}], "member 'b' not found"),
|
|
3476
|
+
([{'op': 'frobnicate', 'path': '/a'}], "Unknown operation 'frobnicate'"),
|
|
3477
|
+
({'op': 'remove', 'path': '/a'}, 'sequence of operations'),
|
|
3478
|
+
]
|
|
3479
|
+
for patch, message in cases:
|
|
3480
|
+
with self.subTest(patch=patch):
|
|
3481
|
+
res = self.run_script('jsonpatch', doc, self.write('patch.json', patch))
|
|
3482
|
+
self.assert_error(res, 'jsonpatch', message)
|
|
3483
|
+
|
|
3484
|
+
def test_jsonpatch_reports_invalid_json(self):
|
|
3485
|
+
doc = self.write('doc.json', {'a': 1})
|
|
3486
|
+
patch = self.write('patch.json', [])
|
|
3487
|
+
broken = os.path.join(self.dir, 'broken.json')
|
|
3488
|
+
with open(broken, 'w', encoding='utf-8') as f:
|
|
3489
|
+
f.write('[')
|
|
3490
|
+
res = self.run_script('jsonpatch', broken, patch)
|
|
3491
|
+
self.assert_error(res, 'jsonpatch', 'broken.json', 'line 1 column 2')
|
|
3492
|
+
res = self.run_script('jsonpatch', doc, broken)
|
|
3493
|
+
self.assert_error(res, 'jsonpatch', 'broken.json', 'line 1 column 2')
|
|
3494
|
+
res = self.run_script('jsonpatch', doc, stdin='[')
|
|
3495
|
+
self.assert_error(res, 'jsonpatch', '<stdin>', 'line 1 column 2')
|
|
3496
|
+
|
|
3497
|
+
def test_jsonpatch_reports_invalid_json_of_unnamed_stream(self):
|
|
3498
|
+
doc = self.write('doc.json', {'a': 1})
|
|
3499
|
+
parser = jsonpatch_cli.jsonpatch_parser
|
|
3500
|
+
args = parser.parse_args([doc])
|
|
3501
|
+
self.addCleanup(args.ORIGINAL.close)
|
|
3502
|
+
# a stream without a name, as sys.stdin can be replaced by
|
|
3503
|
+
args.PATCH = io.StringIO('[')
|
|
3504
|
+
with mock.patch.object(parser, 'parse_args', return_value=args), \
|
|
3505
|
+
contextlib.redirect_stderr(io.StringIO()) as stderr:
|
|
3506
|
+
with self.assertRaises(SystemExit) as caught:
|
|
3507
|
+
jsonpatch_cli.jsonpatch_main()
|
|
3508
|
+
self.assertEqual(caught.exception.code, 2)
|
|
3509
|
+
self.assertTrue(stderr.getvalue().startswith('jsonpatch: error: <input>: '),
|
|
3510
|
+
stderr.getvalue())
|
|
3511
|
+
|
|
3512
|
+
def test_jsonpatch_reports_output_error(self):
|
|
3513
|
+
doc = self.write('doc.json', {'a': 1})
|
|
3514
|
+
patch = self.write('patch.json', [])
|
|
3515
|
+
failure = PermissionError(13, 'Permission denied', 'doc.json')
|
|
3516
|
+
with mock.patch('sys.argv', ['jsonpatch', '-i', doc, patch]), \
|
|
3517
|
+
mock.patch('os.replace', side_effect=failure), \
|
|
3518
|
+
contextlib.redirect_stderr(io.StringIO()) as stderr:
|
|
3519
|
+
with self.assertRaises(SystemExit) as caught:
|
|
3520
|
+
jsonpatch_cli.jsonpatch_main()
|
|
3521
|
+
self.assertEqual(caught.exception.code, 2)
|
|
3522
|
+
self.assertEqual(stderr.getvalue(),
|
|
3523
|
+
"jsonpatch: error: [Errno 13] Permission denied: 'doc.json'\n")
|
|
3524
|
+
self.assertEqual(self.read(doc), {'a': 1})
|
|
3525
|
+
|
|
3526
|
+
def test_interrupt_is_not_reported(self):
|
|
3527
|
+
for main, name in ((jsonpatch_cli.jsondiff_main, 'diff_files'),
|
|
3528
|
+
(jsonpatch_cli.jsonpatch_main, 'patch_files')):
|
|
3529
|
+
with self.subTest(program=name):
|
|
3530
|
+
with mock.patch.object(jsonpatch_cli, name, side_effect=KeyboardInterrupt), \
|
|
3531
|
+
contextlib.redirect_stderr(io.StringIO()) as stderr:
|
|
3532
|
+
with self.assertRaises(SystemExit) as caught:
|
|
3533
|
+
main()
|
|
3534
|
+
self.assertEqual(caught.exception.code, 1)
|
|
3535
|
+
self.assertEqual(stderr.getvalue(), '')
|
|
3536
|
+
|
|
3233
3537
|
def test_jsondiff_closes_inputs(self):
|
|
3234
3538
|
for target in (1, 2):
|
|
3235
3539
|
with self.subTest(target=target):
|
|
@@ -3265,8 +3569,10 @@ class CommandLineTests(ScriptRunner, unittest.TestCase):
|
|
|
3265
3569
|
self.addCleanup(args.FILE1.close)
|
|
3266
3570
|
self.addCleanup(args.FILE2.close)
|
|
3267
3571
|
with mock.patch.object(parser, 'parse_args', return_value=args):
|
|
3268
|
-
with self.assertRaises(
|
|
3572
|
+
with self.assertRaises(ValueError) as caught:
|
|
3269
3573
|
jsonpatch_cli.diff_files()
|
|
3574
|
+
self.assertIsInstance(caught.exception.__cause__, json.JSONDecodeError)
|
|
3575
|
+
self.assertIn(os.path.basename(paths[invalid]), str(caught.exception))
|
|
3270
3576
|
self.assertTrue(args.FILE1.closed)
|
|
3271
3577
|
self.assertTrue(args.FILE2.closed)
|
|
3272
3578
|
|
|
@@ -3381,8 +3687,7 @@ class CommandLineTests(ScriptRunner, unittest.TestCase):
|
|
|
3381
3687
|
with open(path, 'w', encoding='utf-8') as f:
|
|
3382
3688
|
f.write(patch)
|
|
3383
3689
|
res = self.run_script('jsonpatch', '-i', doc, path)
|
|
3384
|
-
self.
|
|
3385
|
-
self.assertIn('InvalidJsonPatch', res.stderr)
|
|
3690
|
+
self.assert_error(res, 'jsonpatch')
|
|
3386
3691
|
with open(doc, 'rb') as f:
|
|
3387
3692
|
self.assertEqual(f.read(), original)
|
|
3388
3693
|
|
|
@@ -3595,12 +3900,73 @@ class CommandLineTests(ScriptRunner, unittest.TestCase):
|
|
|
3595
3900
|
self.assertEqual(sorted(os.listdir(self.dir)), ['doc.json', 'patch.json'])
|
|
3596
3901
|
|
|
3597
3902
|
def test_jsonpatch_in_place_existing_backup(self):
|
|
3903
|
+
# an older backup is replaced, also when the backup is repeated
|
|
3598
3904
|
doc = self.write('doc.json', {'a': 1})
|
|
3599
3905
|
patch = self.write('patch.json', [{'op': 'replace', 'path': '/a', 'value': 2}])
|
|
3600
3906
|
backup = self.write('doc.json.orig', {'previous': True})
|
|
3601
3907
|
res = self.run_script('jsonpatch', '-i', '-b', doc, patch)
|
|
3602
3908
|
|
|
3603
|
-
self.
|
|
3909
|
+
self.assertEqual(res.returncode, 0, res.stderr)
|
|
3910
|
+
self.assertEqual(self.read(doc), {'a': 2})
|
|
3911
|
+
self.assertEqual(self.read(backup), {'a': 1})
|
|
3912
|
+
|
|
3913
|
+
patch = self.write('patch.json', [{'op': 'replace', 'path': '/a', 'value': 3}])
|
|
3914
|
+
res = self.run_script('jsonpatch', '-i', '-b', doc, patch)
|
|
3915
|
+
self.assertEqual(res.returncode, 0, res.stderr)
|
|
3916
|
+
self.assertEqual(self.read(doc), {'a': 3})
|
|
3917
|
+
self.assertEqual(self.read(backup), {'a': 2})
|
|
3918
|
+
self.assertEqual(sorted(os.listdir(self.dir)),
|
|
3919
|
+
['doc.json', 'doc.json.orig', 'patch.json'])
|
|
3920
|
+
|
|
3921
|
+
def test_jsonpatch_in_place_existing_backup_without_temporary_file(self):
|
|
3922
|
+
# the fallback that writes ORIGINAL directly replaces it as well
|
|
3923
|
+
doc = self.write('doc.json', {'a': 1})
|
|
3924
|
+
patch = self.write('patch.json', [{'op': 'replace', 'path': '/a', 'value': 2}])
|
|
3925
|
+
backup = self.write('doc.json.orig', {'previous': True})
|
|
3926
|
+
parser = jsonpatch_cli.jsonpatch_parser
|
|
3927
|
+
args = parser.parse_args(['-i', '-b', doc, patch])
|
|
3928
|
+
self.addCleanup(args.ORIGINAL.close)
|
|
3929
|
+
self.addCleanup(args.PATCH.close)
|
|
3930
|
+
|
|
3931
|
+
with mock.patch.object(parser, 'parse_args', return_value=args), \
|
|
3932
|
+
mock.patch('tempfile.mkstemp', side_effect=OSError('read-only')):
|
|
3933
|
+
jsonpatch_cli.patch_files()
|
|
3934
|
+
|
|
3935
|
+
self.assertEqual(self.read(doc), {'a': 2})
|
|
3936
|
+
self.assertEqual(self.read(backup), {'a': 1})
|
|
3937
|
+
self.assertEqual(sorted(os.listdir(self.dir)),
|
|
3938
|
+
['doc.json', 'doc.json.orig', 'patch.json'])
|
|
3939
|
+
|
|
3940
|
+
@unittest.skipUnless(hasattr(os, 'link'), 'needs hard links')
|
|
3941
|
+
def test_jsonpatch_in_place_backup_that_links_to_original(self):
|
|
3942
|
+
# left behind if an earlier run failed after linking the backup;
|
|
3943
|
+
# replacing a link to a file by another one does nothing
|
|
3944
|
+
doc = self.write('doc.json', {'a': 1})
|
|
3945
|
+
patch = self.write('patch.json', [{'op': 'replace', 'path': '/a', 'value': 2}])
|
|
3946
|
+
os.link(doc, doc + '.orig')
|
|
3947
|
+
res = self.run_script('jsonpatch', '-i', '-b', doc, patch)
|
|
3948
|
+
|
|
3949
|
+
self.assertEqual(res.returncode, 0, res.stderr)
|
|
3950
|
+
self.assertEqual(self.read(doc), {'a': 2})
|
|
3951
|
+
self.assertEqual(self.read(doc + '.orig'), {'a': 1})
|
|
3952
|
+
self.assertEqual(sorted(os.listdir(self.dir)),
|
|
3953
|
+
['doc.json', 'doc.json.orig', 'patch.json'])
|
|
3954
|
+
|
|
3955
|
+
def test_jsonpatch_in_place_keeps_backup_on_backup_error(self):
|
|
3956
|
+
# neither the original nor an older backup is lost
|
|
3957
|
+
doc = self.write('doc.json', {'a': 1})
|
|
3958
|
+
patch = self.write('patch.json', [{'op': 'replace', 'path': '/a', 'value': 2}])
|
|
3959
|
+
backup = self.write('doc.json.orig', {'previous': True})
|
|
3960
|
+
parser = jsonpatch_cli.jsonpatch_parser
|
|
3961
|
+
args = parser.parse_args(['-i', '-b', doc, patch])
|
|
3962
|
+
self.addCleanup(args.ORIGINAL.close)
|
|
3963
|
+
self.addCleanup(args.PATCH.close)
|
|
3964
|
+
|
|
3965
|
+
with mock.patch.object(parser, 'parse_args', return_value=args), \
|
|
3966
|
+
mock.patch('os.replace', side_effect=PermissionError('cannot replace')):
|
|
3967
|
+
with self.assertRaises(PermissionError):
|
|
3968
|
+
jsonpatch_cli.patch_files()
|
|
3969
|
+
|
|
3604
3970
|
self.assertEqual(self.read(doc), {'a': 1})
|
|
3605
3971
|
self.assertEqual(self.read(backup), {'previous': True})
|
|
3606
3972
|
self.assertEqual(sorted(os.listdir(self.dir)),
|
|
@@ -3611,8 +3977,7 @@ class CommandLineTests(ScriptRunner, unittest.TestCase):
|
|
|
3611
3977
|
doc = self.write('doc.json', {'a': 1})
|
|
3612
3978
|
patch = self.write('patch.json', [{'op': 'remove', 'path': '/b'}])
|
|
3613
3979
|
res = self.run_script('jsonpatch', '-i', '-b', doc, patch)
|
|
3614
|
-
self.
|
|
3615
|
-
self.assertIn('JsonPatchPathNotFound', res.stderr)
|
|
3980
|
+
self.assert_error(res, 'jsonpatch', "can't remove a non-existent object 'b'")
|
|
3616
3981
|
self.assertEqual(self.read(doc), {'a': 1})
|
|
3617
3982
|
self.assertEqual(sorted(os.listdir(self.dir)), ['doc.json', 'patch.json'])
|
|
3618
3983
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|