Skip to content

Commit

Permalink
fix invalid remove index
Browse files Browse the repository at this point in the history
  • Loading branch information
Vu-Hoang Phan committed Apr 6, 2021
1 parent a652648 commit db194f8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
10 changes: 10 additions & 0 deletions jsonpatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@
import functools
import json
import sys

try:
from collections.abc import Mapping, Sequence
except ImportError: # Python 3
from collections import Mapping, Sequence

try:
from types import MappingProxyType
except ImportError:
Expand Down Expand Up @@ -234,6 +240,10 @@ class RemoveOperation(PatchOperation):

def apply(self, obj):
subobj, part = self.pointer.to_last(obj)

if isinstance(subobj, Sequence) and not isinstance(part, int):
raise JsonPointerException("invalid array index '{0}'".format(part))

try:
del subobj[part]
except (KeyError, IndexError) as ex:
Expand Down
6 changes: 6 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,12 @@ def test_remove_array_item(self):
res = jsonpatch.apply_patch(obj, [{'op': 'remove', 'path': '/foo/1'}])
self.assertEqual(res['foo'], ['bar', 'baz'])

def test_remove_invalid_item(self):
obj = {'foo': ['bar', 'qux', 'baz']}
with self.assertRaises(jsonpointer.JsonPointerException):
jsonpatch.apply_patch(obj, [{'op': 'remove', 'path': '/foo/-'}])


def test_replace_object_key(self):
obj = {'foo': 'bar', 'baz': 'qux'}
res = jsonpatch.apply_patch(obj, [{'op': 'replace', 'path': '/baz', 'value': 'boo'}])
Expand Down

0 comments on commit db194f8

Please sign in to comment.