Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 46 additions & 10 deletions jsonpatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import copy
import functools
import json
import re
from collections.abc import (Mapping, MutableMapping, MutableSequence,
Sequence)
from difflib import SequenceMatcher
Expand All @@ -52,6 +53,10 @@
# of two lists
_EXACT_MATCH_LIMIT = 500 ** 2

# The default JSON encoder can stringify number, bool and None keys. If
# none of those spellings occurs as a member name, no walk is needed.
_POSSIBLY_NON_STRING_MEMBER = re.compile(r'"(?:[-0-9][^"]*|true|false|null|NaN|Infinity)":')


# The from_parts of pointer classes that don't override it, see path_join
_JSONPOINTER_FROM_PARTS = JsonPointer.from_parts.__func__
Expand Down Expand Up @@ -1232,23 +1237,28 @@ def __init__(self, src_doc, dst_doc, dumps=json.dumps, pointer_cls=JsonPointer,
self.arrays = {}
root[:] = [root, root, None]

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 """
def _matching_key(self, value):
""" Compare values independently of the order of object members. """
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)
encoded = 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
else:
if _POSSIBLY_NON_STRING_MEMBER.search(encoded):
return _preserve_member_names(value, encoded)
return encoded
return _preserve_member_names(value, self.dumps(_sorted_members(value)))

def _move_key(self, value):
try:
# Serialized like in _differing_runs
return self.dumps(_sorted_members(value))
return self._matching_key(value)
except (TypeError, ValueError, RecursionError):
# Values that cannot be serialized, e.g. as they contain
# themselves, are only moved where they are added unchanged
Expand Down Expand Up @@ -1476,8 +1486,8 @@ def _differing_runs(self, src, dst):
try:
# Serialized like in _compare_values, so e.g. 1 and True differ,
# but independent of the order of object members
src_keys = [self.dumps(_sorted_members(item)) for item in src]
dst_keys = [self.dumps(_sorted_members(item)) for item in dst]
src_keys = [self._matching_key(item) for item in src]
dst_keys = [self._matching_key(item) for item in dst]
except (TypeError, ValueError, RecursionError):
# Items that cannot be serialized are compared by position
return [(0, len(src), 0, len(dst))]
Expand Down Expand Up @@ -1551,7 +1561,8 @@ def _compare_lists(self, path, src, dst):
# To ensure we catch changes to JSON, we can't rely on a
# simple old == new, because it would not recognize the
# difference between 1 and True, among other things.
elif self.dumps(old) == self.dumps(new):
elif _preserve_member_names(old, self.dumps(old)) == \
_preserve_member_names(new, self.dumps(new)):
continue

else:
Expand Down Expand Up @@ -1580,7 +1591,8 @@ def _compare_values(self, path, key, src, dst):
# and ignore those that don't. The performance of this could be
# improved by doing more direct type checks, but we'd need to be
# careful to accept type changes that don't matter when JSONified.
elif self.dumps(src) == self.dumps(dst):
elif _preserve_member_names(src, self.dumps(src)) == \
_preserve_member_names(dst, self.dumps(dst)):
return

else:
Expand Down Expand Up @@ -1709,6 +1721,30 @@ def _sorted_members(value):
return value


def _preserve_member_names(value, encoded):
""" Keep object names that JSON serialization coerces to strings. """
if value is None or type(value) in (str, int, float, bool):
return encoded
names = frozenset(_non_string_key_paths(value))
return (encoded, names) if names else encoded


def _non_string_key_paths(value, path=()):
if value is None or isinstance(value, (str, int, float, bytes)):
return
if isinstance(value, Mapping):
for key, item in value.items():
if isinstance(key, str):
member_path = path + (key,)
else:
member_path = path + ((type(key), key),)
yield member_path
yield from _non_string_key_paths(item, member_path)
elif isinstance(value, Sequence):
for index, item in enumerate(value):
yield from _non_string_key_paths(item, path + (index,))


# The DiffBuilder works with parts, which are tuples of object keys (str) and
# array indices (int), and with locations, in which _ArrayItem objects take
# the place of array indices. Operations keep locations: when a move replaces
Expand Down
17 changes: 17 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1077,6 +1077,9 @@ def test_changed_member_with_non_string_name_is_rejected(self):
({1: {'a': 1}}, {1: {'a': 2}}),
({1: [1, 2]}, {1: [1, 2, 3]}),
({'a': [{1: 'a'}]}, {'a': [{1: 'b'}]}),
([{1: 'a'}], [{'1': 'a'}]),
([{'1': 'a'}], [{1: 'a'}]),
([{-1.5: 'a'}], [{'-1.5': 'a'}]),
# moved from or to such a member
({'a': {1: [1, 2]}}, {'a': {}, 'b': [1, 2]}),
({'a': {}, 'b': [1, 2]}, {'a': {1: [1, 2]}}),
Expand All @@ -1094,6 +1097,20 @@ def test_changed_member_with_non_string_name_is_rejected(self):
with self.assertRaises(TypeError):
jsonpatch.JsonPatchWithAppend.from_diff({1: 'a'}, {1: 'ab'})

def test_values_with_different_member_names_are_not_moved(self):
cases = [
({1: 'a'}, {'1': 'a'}),
([{None: 'a'}], [{'null': 'a'}]),
({True: 'a'}, {'true': 'a'}),
([{1: 'a'}, {'1': 'a'}], [{'1': 'a'}, {1: 'a'}]),
]
for before, after in cases:
with self.subTest(before=before, after=after):
src, dst = {'old': before}, {'new': after}
patch = jsonpatch.make_patch(src, dst)
self.assertEqual(patch.apply(src), dst)
self.assertEqual([op['op'] for op in patch], ['remove', 'add'])

def test_non_string_member_names_differ_from_strings(self):
name = jsonpatch._member_name(1)
self.assertTrue(name != '1')
Expand Down
Loading