Skip to content

Commit aae6082

Browse files
committed
Expect path/from attributes also as JsonPoiner instances (#60)
1 parent df0c56d commit aae6082

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

jsonpatch.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -335,8 +335,14 @@ class PatchOperation(object):
335335
"""A single operation inside a JSON Patch."""
336336

337337
def __init__(self, operation):
338-
self.location = operation['path']
339-
self.pointer = JsonPointer(self.location)
338+
339+
if isinstance(operation['path'], JsonPointer):
340+
self.location = operation['path'].path
341+
self.pointer = operation['path']
342+
else:
343+
self.location = operation['path']
344+
self.pointer = JsonPointer(self.location)
345+
340346
self.operation = operation
341347

342348
def apply(self, obj):
@@ -493,7 +499,10 @@ class MoveOperation(PatchOperation):
493499

494500
def apply(self, obj):
495501
try:
496-
from_ptr = JsonPointer(self.operation['from'])
502+
if isinstance(self.operation['from'], JsonPointer):
503+
from_ptr = self.operation['from']
504+
else:
505+
from_ptr = JsonPointer(self.operation['from'])
497506
except KeyError as ex:
498507
raise InvalidJsonPatch(
499508
"The operation does not contain a 'from' member")

tests.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -594,6 +594,27 @@ def test_replace_missing(self):
594594
self.assertRaises(jsonpatch.JsonPatchConflict, jsonpatch.apply_patch, src, patch_obj)
595595

596596

597+
class JsonPointerTests(unittest.TestCase):
598+
599+
def test_create_with_pointer(self):
600+
601+
patch = jsonpatch.JsonPatch([
602+
{'op': 'add', 'path': jsonpointer.JsonPointer('/foo'), 'value': 'bar'},
603+
{'op': 'add', 'path': jsonpointer.JsonPointer('/baz'), 'value': [1, 2, 3]},
604+
{'op': 'remove', 'path': jsonpointer.JsonPointer('/baz/1')},
605+
{'op': 'test', 'path': jsonpointer.JsonPointer('/baz'), 'value': [1, 3]},
606+
{'op': 'replace', 'path': jsonpointer.JsonPointer('/baz/0'), 'value': 42},
607+
{'op': 'remove', 'path': jsonpointer.JsonPointer('/baz/1')},
608+
{'op': 'move', 'from': jsonpointer.JsonPointer('/foo'), 'path': jsonpointer.JsonPointer('/bar')},
609+
610+
])
611+
doc = {}
612+
result = patch.apply(doc)
613+
expected = {'bar': 'bar', 'baz': [42]}
614+
self.assertEqual(result, expected)
615+
616+
617+
597618
if __name__ == '__main__':
598619
modules = ['jsonpatch']
599620

@@ -608,6 +629,7 @@ def get_suite():
608629
suite.addTest(unittest.makeSuite(InvalidInputTests))
609630
suite.addTest(unittest.makeSuite(ConflictTests))
610631
suite.addTest(unittest.makeSuite(OptimizationTests))
632+
suite.addTest(unittest.makeSuite(JsonPointerTests))
611633
return suite
612634

613635

0 commit comments

Comments
 (0)