Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

B/fix invalid remove index #134

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions jsonpatch.py
Original file line number Diff line number Diff line change
@@ -39,6 +39,12 @@
import functools
import json
import sys

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

try:
from types import MappingProxyType
except ImportError:
@@ -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:
6 changes: 6 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
@@ -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'}])