Optimize "deep" `replace` operation, fixes #36

This commit is contained in:
Stefan Kögl
2016-02-13 15:40:03 +01:00
parent 32dcbb03d8
commit a33021bf5a
2 changed files with 28 additions and 3 deletions

View File

@@ -756,10 +756,17 @@ def _optimize(operations):
def _optimize_using_replace(prev, cur):
"""Optimises JSON patch by using ``replace`` operation instead of
``remove`` and ``add`` against the same path."""
"""Optimises by replacing ``add``/``remove`` with ``replace`` on same path
For nested strucures, tries to recurse replacement, see #36 """
prev['op'] = 'replace'
if cur['op'] == 'add':
# make recursive patch
patch = make_patch(prev['value'], cur['value'])
if len(patch.patch) == 1:
prev['path'] = prev['path'] + patch.patch[0]['path']
prev['value'] = patch.patch[0]['value']
else:
prev['value'] = cur['value']

View File

@@ -366,6 +366,24 @@ class MakePatchTestCase(unittest.TestCase):
dest = [7, 2, 1, 0, 9, 4, 3, 6, 5, 8]
patch = jsonpatch.make_patch(src, dest)
def test_minimal_patch(self):
""" Test whether a minimal patch is created, see #36 """
src = [{"foo": 1, "bar": 2}]
dst = [{"foo": 2, "bar": 2}]
import pudb
#pudb.set_trace()
patch = jsonpatch.make_patch(src, dst)
exp = [
{
"path": "/0/foo",
"value": 2,
"op": "replace"
}
]
self.assertEqual(patch.patch, exp)
class InvalidInputTests(unittest.TestCase):