From c9bfb91727690d6c7249b9250aba8942613f3f1c Mon Sep 17 00:00:00 2001 From: Julien Palard Date: Tue, 16 Mar 2021 15:33:47 +0100 Subject: FIX: TypeError when one forgot to put its operation in a list. --- jsonpatch.py | 15 ++++++++++++++- tests.py | 6 ++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/jsonpatch.py b/jsonpatch.py index 5213b32..1bced46 100644 --- a/jsonpatch.py +++ b/jsonpatch.py @@ -558,6 +558,19 @@ class JsonPatch(object): # Much of the validation is done in the initializer # though some is delayed until the patch is applied. for op in self.patch: + # We're only checking for basestring in the following check + # for two reasons: + # + # - It should come from JSON, which only allows strings as + # dictionary keys, so having a string here unambiguously means + # someone used: {"op": ..., ...} instead of [{"op": ..., ...}]. + # + # - There's no possible false positive: if someone give a sequence + # of mappings, this won't raise. + if isinstance(op, basestring): + raise InvalidJsonPatch("Document is expected to be sequence of " + "operations, got a sequence of strings.") + self._get_operation(op) def __str__(self): @@ -677,7 +690,7 @@ class JsonPatch(object): op = operation['op'] if not isinstance(op, basestring): - raise InvalidJsonPatch("Operation must be a string") + raise InvalidJsonPatch("Operation's op must be a string") if op not in self.operations: raise InvalidJsonPatch("Unknown operation {0!r}".format(op)) diff --git a/tests.py b/tests.py index 8a638cf..797c220 100755 --- a/tests.py +++ b/tests.py @@ -190,6 +190,12 @@ class ApplyPatchTestCase(unittest.TestCase): obj, [{'op': 'test', 'path': '/baz', 'value': 'bar'}]) + def test_forgetting_surrounding_list(self): + obj = {'bar': 'qux'} + self.assertRaises(jsonpatch.InvalidJsonPatch, + jsonpatch.apply_patch, + obj, {'op': 'test', 'path': '/bar'}) + def test_test_noval_existing(self): obj = {'bar': 'qux'} self.assertRaises(jsonpatch.InvalidJsonPatch, -- cgit v1.2.1