From aae608237495fb63d9428da84f36db96d4e4c9dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20K=C3=B6gl?= Date: Sun, 3 Dec 2017 23:02:18 +0100 Subject: Expect path/from attributes also as JsonPoiner instances (#60) --- jsonpatch.py | 15 ++++++++++++--- tests.py | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/jsonpatch.py b/jsonpatch.py index cd08a82..e8608ec 100644 --- a/jsonpatch.py +++ b/jsonpatch.py @@ -335,8 +335,14 @@ class PatchOperation(object): """A single operation inside a JSON Patch.""" def __init__(self, operation): - self.location = operation['path'] - self.pointer = JsonPointer(self.location) + + if isinstance(operation['path'], JsonPointer): + self.location = operation['path'].path + self.pointer = operation['path'] + else: + self.location = operation['path'] + self.pointer = JsonPointer(self.location) + self.operation = operation def apply(self, obj): @@ -493,7 +499,10 @@ class MoveOperation(PatchOperation): def apply(self, obj): try: - from_ptr = JsonPointer(self.operation['from']) + if isinstance(self.operation['from'], JsonPointer): + from_ptr = self.operation['from'] + else: + from_ptr = JsonPointer(self.operation['from']) except KeyError as ex: raise InvalidJsonPatch( "The operation does not contain a 'from' member") diff --git a/tests.py b/tests.py index 29a8ae9..e6c4597 100755 --- a/tests.py +++ b/tests.py @@ -594,6 +594,27 @@ class ConflictTests(unittest.TestCase): self.assertRaises(jsonpatch.JsonPatchConflict, jsonpatch.apply_patch, src, patch_obj) +class JsonPointerTests(unittest.TestCase): + + def test_create_with_pointer(self): + + patch = jsonpatch.JsonPatch([ + {'op': 'add', 'path': jsonpointer.JsonPointer('/foo'), 'value': 'bar'}, + {'op': 'add', 'path': jsonpointer.JsonPointer('/baz'), 'value': [1, 2, 3]}, + {'op': 'remove', 'path': jsonpointer.JsonPointer('/baz/1')}, + {'op': 'test', 'path': jsonpointer.JsonPointer('/baz'), 'value': [1, 3]}, + {'op': 'replace', 'path': jsonpointer.JsonPointer('/baz/0'), 'value': 42}, + {'op': 'remove', 'path': jsonpointer.JsonPointer('/baz/1')}, + {'op': 'move', 'from': jsonpointer.JsonPointer('/foo'), 'path': jsonpointer.JsonPointer('/bar')}, + + ]) + doc = {} + result = patch.apply(doc) + expected = {'bar': 'bar', 'baz': [42]} + self.assertEqual(result, expected) + + + if __name__ == '__main__': modules = ['jsonpatch'] @@ -608,6 +629,7 @@ if __name__ == '__main__': suite.addTest(unittest.makeSuite(InvalidInputTests)) suite.addTest(unittest.makeSuite(ConflictTests)) suite.addTest(unittest.makeSuite(OptimizationTests)) + suite.addTest(unittest.makeSuite(JsonPointerTests)) return suite -- cgit v1.2.1