diff --git a/jsonpatch.py b/jsonpatch.py index 9ff14d5..61ac8f9 100644 --- a/jsonpatch.py +++ b/jsonpatch.py @@ -1055,7 +1055,7 @@ def from_diff( optimization=optimization, generate_test_ops=generate_test_ops) builder._compare_values((), None, src, dst) - ops = copy.deepcopy(list(builder.execute())) + ops = _json_copy(list(builder.execute())) return cls(ops, pointer_cls=pointer_cls) def to_string(self, dumps=None): @@ -1175,7 +1175,7 @@ def from_diff(cls, src, dst, optimization=True, dumps=None, optimization=optimization, generate_test_ops=generate_test_ops) builder._compare_values((), None, src, dst) - ops = copy.deepcopy(list(builder.execute())) + ops = _json_copy(list(builder.execute())) return cls(ops, pointer_cls=pointer_cls) @@ -1184,6 +1184,10 @@ class DiffBuilder: def __init__(self, src_doc, dst_doc, dumps=json.dumps, pointer_cls=JsonPointer, optimization=True, generate_test_ops=False): self.dumps = dumps + # json.dumps builds a JSONEncoder for every call; the default dumps + # is called once per added and removed value, so cache its encoder + self._canonical_dumps = (json.JSONEncoder(sort_keys=True).encode + if dumps is json.dumps else None) self.pointer_cls = pointer_cls self.optimization = optimization self.generate_test_ops = generate_test_ops @@ -1201,6 +1205,17 @@ def __init__(self, src_doc, dst_doc, dumps=json.dumps, pointer_cls=JsonPointer, def _move_key(self, value): """ A key of value, which is equal for values that are equal in JSON, so that e.g. [1] is not moved where [true] is added """ + if self._canonical_dumps is not None: + try: + # sort_keys gives the same string as _sorted_members for JSON + # documents, without building a sorted copy of every added or + # removed subtree + return self._canonical_dumps(value) + except (TypeError, ValueError, RecursionError): + # Values like UserDict and UserList are normalized by + # _sorted_members, but the encoder cannot serialize them as + # they are, so fall through to the generic path below + pass try: # Serialized like in _differing_runs return self.dumps(_sorted_members(value)) @@ -1581,6 +1596,37 @@ def _json_equal(first, second): return first == second +def _json_copy(value, memo=None): + """ Copies a JSON value like copy.deepcopy, but without the generic + dispatch for dicts, lists and scalars, which dominate patch creation. + + Values that are not plain JSON containers keep the copy.deepcopy + behaviour, and shared references are preserved through memo. """ + if value is None or type(value) in (str, int, float, bool): + return value + if memo is None: + memo = {} + value_id = id(value) + copied = memo.get(value_id) + if copied is not None: + return copied + value_type = type(value) + if value_type is dict: + # memo must hold the new dict before the children are copied, so + # that self-referential documents terminate like copy.deepcopy + copied = memo[value_id] = {} + for key, item in value.items(): + # copy.deepcopy copies the keys too, through the same memo, so + # that a key and a value that are the same object stay shared + copied[_json_copy(key, memo)] = _json_copy(item, memo) + return copied + if value_type is list: + copied = memo[value_id] = [] + copied.extend(_json_copy(item, memo) for item in value) + return copied + return copy.deepcopy(value, memo) + + def _sorted_members(value): """ Copies the arrays and objects in value, with the members of objects sorted by key """ diff --git a/tests.py b/tests.py index f0d7581..193636c 100644 --- a/tests.py +++ b/tests.py @@ -1379,6 +1379,38 @@ def test_moves_of_unhashable_values(self): self.assertEqual({op['op'] for op in patch}, {'move'}) self.assertEqual(patch.apply(src), dst) + def test_move_of_non_json_containers(self): + """ UserDict and UserList get the same move key as the plain dict + and list with the same members """ + src = [collections.UserDict({'x': 1}), 'B', + collections.UserList([1, 2])] + dst = ['B', collections.UserList([1, 2]), + collections.UserDict({'x': 1})] + patch = jsonpatch.make_patch(src, dst) + self.assertEqual(patch.patch, + [{'op': 'move', 'from': '/0', 'path': '/2'}]) + self.assertEqual(patch.to_string(), + '[{"op": "move", "from": "/0", "path": "/2"}]') + self.assertEqual(patch.apply(src), dst) + + def test_dict_keys_are_copied_with_the_values(self): + """ The patch keeps its own copy of the keys, and a key that is also + a value stays the same object in it """ + class Key(str): + pass + key = Key('k') + key.tag = ['original'] + src = {'a': 1} + dst = {'a': 1, 'x': {key: key}} + patch = jsonpatch.make_patch(src, dst) + added = [op for op in patch.patch if op['op'] == 'add'][-1]['value'] + copied_key, = added + self.assertIsNot(copied_key, key) + self.assertIs(added[copied_key], copied_key) + self.assertEqual(copied_key.tag, ['original']) + copied_key.tag.append('changed') + self.assertEqual(key.tag, ['original']) + def test_success_if_replace_inside_dict(self): src = [{'a': 1, 'foo': {'b': 2, 'd': 5}}] dst = [{'a': 1, 'foo': {'b': 3, 'd': 6}}]