From d811454192adb18fc3a9aa333fc27e4e48ddd723 Mon Sep 17 00:00:00 2001 From: Ben Kehoe Date: Sun, 20 Feb 2022 14:10:10 -0700 Subject: Add join method and / operator --- jsonpointer.py | 19 ++++++++++++++++++- tests.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/jsonpointer.py b/jsonpointer.py index 3eaea19..d9fe0c0 100644 --- a/jsonpointer.py +++ b/jsonpointer.py @@ -54,7 +54,7 @@ try: except ImportError: # Python 3 from collections import Mapping, Sequence -from itertools import tee +from itertools import tee, chain import re import copy @@ -299,6 +299,23 @@ class JsonPointer(object): """ 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 diff --git a/tests.py b/tests.py index 7a2520b..dafbe89 100755 --- a/tests.py +++ b/tests.py @@ -175,6 +175,42 @@ class ComparisonTests(unittest.TestCase): 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): -- cgit v1.2.1