From 07b0af061f286b2f93a7e4848c19cdf91a8387b8 Mon Sep 17 00:00:00 2001 From: Alexander Shorin Date: Sun, 25 Dec 2011 16:28:19 +0400 Subject: [PATCH] Add support for test operation --- jsonpatch.py | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/jsonpatch.py b/jsonpatch.py index d77f4e4..db4dd75 100644 --- a/jsonpatch.py +++ b/jsonpatch.py @@ -73,7 +73,8 @@ class JsonPatch(object): 'remove': RemoveOperation, 'add': AddOperation, 'replace': ReplaceOperation, - 'move': MoveOperation + 'move': MoveOperation, + 'test': TestOperation } @@ -256,3 +257,31 @@ class MoveOperation(PatchOperation): value = subobj[part] RemoveOperation(self.location, self.operation).apply(obj) AddOperation(self.operation['to'], {'value': value}).apply(obj) + + +class TestOperation(PatchOperation): + """ Test value by specified location + + >>> obj = {'baz': 'qux', 'foo': ['a', 2, 'c']} + >>> patch = JsonPatch([ + ... {'test': '/baz', 'value': 'qux'}, + ... {'test': '/foo/1', 'value': 2} + ... ]) + >>> patch.apply(obj) + {'foo': ['a', 2, 'c'], 'baz': 'qux'} + + >>> patch = JsonPatch([ + ... {'test': '/foo/1', 'value': 'BOOM!'} + ... ]) + >>> try: + ... patch.apply(obj) + ... except AssertionError: + ... pass + ... else: + ... assert False, 'test should fall' + """ + + def apply(self, obj): + value = self.operation['value'] + subobj, part = self.locate(obj, self.location) + assert subobj[part] == value