Skip to content

Commit d811454

Browse files
committed
Add join method and / operator
1 parent 04e4ac2 commit d811454

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

jsonpointer.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@
5454
except ImportError: # Python 3
5555
from collections import Mapping, Sequence
5656

57-
from itertools import tee
57+
from itertools import tee, chain
5858
import re
5959
import copy
6060

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

302+
def join(self, suffix):
303+
""" Returns a new JsonPointer with the given suffix append to this ptr """
304+
if isinstance(suffix, JsonPointer):
305+
suffix_parts = suffix.parts
306+
elif isinstance(suffix, str):
307+
suffix_parts = JsonPointer(suffix).parts
308+
else:
309+
suffix_parts = suffix
310+
try:
311+
return JsonPointer.from_parts(chain(self.parts, suffix_parts))
312+
except:
313+
raise JsonPointerException("Invalid suffix")
314+
315+
def __truediv__(self, suffix): # Python 3
316+
return self.join(suffix)
317+
__div__ = __truediv__ # Python 2
318+
302319
@property
303320
def path(self):
304321
"""Returns the string representation of the pointer

tests.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,42 @@ def test_contains_magic(self):
175175
self.assertTrue(self.ptr1 in self.ptr1)
176176
self.assertFalse(self.ptr3 in self.ptr1)
177177

178+
def test_join(self):
179+
180+
ptr12a = self.ptr1.join(self.ptr2)
181+
self.assertEqual(ptr12a.path, "/a/b/c/a/b")
182+
183+
ptr12b = self.ptr1.join(self.ptr2.parts)
184+
self.assertEqual(ptr12b.path, "/a/b/c/a/b")
185+
186+
ptr12c = self.ptr1.join(self.ptr2.parts[0:1])
187+
self.assertEqual(ptr12c.path, "/a/b/c/a")
188+
189+
ptr12d = self.ptr1.join("/a/b")
190+
self.assertEqual(ptr12d.path, "/a/b/c/a/b")
191+
192+
ptr12e = self.ptr1.join(["a", "b"])
193+
self.assertEqual(ptr12e.path, "/a/b/c/a/b")
194+
195+
self.assertRaises(JsonPointerException, self.ptr1.join, 0)
196+
197+
def test_join_magic(self):
198+
199+
ptr12a = self.ptr1 / self.ptr2
200+
self.assertEqual(ptr12a.path, "/a/b/c/a/b")
201+
202+
ptr12b = self.ptr1 / self.ptr2.parts
203+
self.assertEqual(ptr12b.path, "/a/b/c/a/b")
204+
205+
ptr12c = self.ptr1 / self.ptr2.parts[0:1]
206+
self.assertEqual(ptr12c.path, "/a/b/c/a")
207+
208+
ptr12d = self.ptr1 / "/a/b"
209+
self.assertEqual(ptr12d.path, "/a/b/c/a/b")
210+
211+
ptr12e = self.ptr1 / ["a", "b"]
212+
self.assertEqual(ptr12e.path, "/a/b/c/a/b")
213+
178214
class WrongInputTests(unittest.TestCase):
179215

180216
def test_no_start_slash(self):

0 commit comments

Comments
 (0)