Skip to content

Commit

Permalink
Add join method and / operator
Browse files Browse the repository at this point in the history
  • Loading branch information
benkehoe committed Feb 20, 2022
1 parent 04e4ac2 commit d811454
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
19 changes: 18 additions & 1 deletion jsonpointer.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
except ImportError: # Python 3
from collections import Mapping, Sequence

from itertools import tee
from itertools import tee, chain
import re
import copy

Expand Down Expand Up @@ -299,6 +299,23 @@ def __contains__(self, item):
""" Returns True if self contains the given ptr """
return self.contains(item)

def join(self, suffix):
""" Returns a new JsonPointer with the given suffix append to this ptr """
if isinstance(suffix, JsonPointer):
suffix_parts = suffix.parts
elif isinstance(suffix, str):
suffix_parts = JsonPointer(suffix).parts
else:
suffix_parts = suffix
try:
return JsonPointer.from_parts(chain(self.parts, suffix_parts))
except:
raise JsonPointerException("Invalid suffix")

def __truediv__(self, suffix): # Python 3
return self.join(suffix)
__div__ = __truediv__ # Python 2

@property
def path(self):
"""Returns the string representation of the pointer
Expand Down
36 changes: 36 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,42 @@ def test_contains_magic(self):
self.assertTrue(self.ptr1 in self.ptr1)
self.assertFalse(self.ptr3 in self.ptr1)

def test_join(self):

ptr12a = self.ptr1.join(self.ptr2)
self.assertEqual(ptr12a.path, "/a/b/c/a/b")

ptr12b = self.ptr1.join(self.ptr2.parts)
self.assertEqual(ptr12b.path, "/a/b/c/a/b")

ptr12c = self.ptr1.join(self.ptr2.parts[0:1])
self.assertEqual(ptr12c.path, "/a/b/c/a")

ptr12d = self.ptr1.join("/a/b")
self.assertEqual(ptr12d.path, "/a/b/c/a/b")

ptr12e = self.ptr1.join(["a", "b"])
self.assertEqual(ptr12e.path, "/a/b/c/a/b")

self.assertRaises(JsonPointerException, self.ptr1.join, 0)

def test_join_magic(self):

ptr12a = self.ptr1 / self.ptr2
self.assertEqual(ptr12a.path, "/a/b/c/a/b")

ptr12b = self.ptr1 / self.ptr2.parts
self.assertEqual(ptr12b.path, "/a/b/c/a/b")

ptr12c = self.ptr1 / self.ptr2.parts[0:1]
self.assertEqual(ptr12c.path, "/a/b/c/a")

ptr12d = self.ptr1 / "/a/b"
self.assertEqual(ptr12d.path, "/a/b/c/a/b")

ptr12e = self.ptr1 / ["a", "b"]
self.assertEqual(ptr12e.path, "/a/b/c/a/b")

class WrongInputTests(unittest.TestCase):

def test_no_start_slash(self):
Expand Down

0 comments on commit d811454

Please sign in to comment.