summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBen Kehoe <ben@kehoe.io>2022-02-20 14:09:08 -0700
committerBen Kehoe <ben@kehoe.io>2022-02-20 14:09:08 -0700
commit04e4ac28b935f7538fa54d8ffd385549015040b5 (patch)
treebca054ff89807085fedf18f87e12b8b49dec5d6c
parent66ec8f71ac52384cc61d1db88672a86903671de4 (diff)
downloadpython-json-pointer-04e4ac28b935f7538fa54d8ffd385549015040b5.tar.gz
Add __str__ and __repr__ methods
-rw-r--r--jsonpointer.py8
-rwxr-xr-xtests.py44
2 files changed, 52 insertions, 0 deletions
diff --git a/jsonpointer.py b/jsonpointer.py
index d353632..3eaea19 100644
--- a/jsonpointer.py
+++ b/jsonpointer.py
@@ -44,8 +44,10 @@ __license__ = 'Modified BSD License'
try:
from itertools import izip
str = unicode
+ encode_str = lambda u: u.encode("raw_unicode_escape")
except ImportError: # Python 3
izip = zip
+ encode_str = lambda u: u
try:
from collections.abc import Mapping, Sequence
@@ -322,6 +324,12 @@ class JsonPointer(object):
def __hash__(self):
return hash(tuple(self.parts))
+ def __str__(self):
+ return encode_str(self.path)
+
+ def __repr__(self):
+ return "JsonPointer(" + repr(self.path) + ")"
+
@classmethod
def from_parts(cls, parts):
"""Constructs a JsonPointer from a list of (unescaped) paths
diff --git a/tests.py b/tests.py
index 4fefd9f..7a2520b 100755
--- a/tests.py
+++ b/tests.py
@@ -75,6 +75,50 @@ class SpecificationTests(unittest.TestCase):
new_ptr = JsonPointer.from_parts(parts)
self.assertEqual(ptr, new_ptr)
+ def test_str_and_repr(self):
+ paths = [
+ ("", "", "JsonPointer({u}'')"),
+ ("/foo", "/foo", "JsonPointer({u}'/foo')"),
+ ("/foo/0", "/foo/0", "JsonPointer({u}'/foo/0')"),
+ ("/", "/", "JsonPointer({u}'/')"),
+ ("/a~1b", "/a~1b", "JsonPointer({u}'/a~1b')"),
+ ("/c%d", "/c%d", "JsonPointer({u}'/c%d')"),
+ ("/e^f", "/e^f", "JsonPointer({u}'/e^f')"),
+ ("/g|h", "/g|h", "JsonPointer({u}'/g|h')"),
+ ("/i\\j", "/i\\j", "JsonPointer({u}'/i\\\\j')"),
+ ("/k\"l", "/k\"l", "JsonPointer({u}'/k\"l')"),
+ ("/ ", "/ ", "JsonPointer({u}'/ ')"),
+ ("/m~0n", "/m~0n", "JsonPointer({u}'/m~0n')"),
+ ]
+ for path, ptr_str, ptr_repr in paths:
+ ptr = JsonPointer(path)
+ self.assertEqual(path, ptr.path)
+
+ if sys.version_info[0] == 2:
+ u_str = "u"
+ else:
+ u_str = ""
+ self.assertEqual(ptr_str, str(ptr))
+ self.assertEqual(ptr_repr.format(u=u_str), repr(ptr))
+
+ if sys.version_info[0] == 2:
+ path = "/\xee"
+ ptr_str = b"/\xee"
+ ptr_repr = "JsonPointer(u'/\\xee')"
+ else:
+ path = "/\xee"
+ ptr_str = "/\xee"
+ ptr_repr = "JsonPointer('/\xee')"
+ ptr = JsonPointer(path)
+ self.assertEqual(path, ptr.path)
+
+ self.assertEqual(ptr_str, str(ptr))
+ self.assertEqual(ptr_repr, repr(ptr))
+
+ # should not be unicode in Python 2
+ self.assertIsInstance(str(ptr), str)
+ self.assertIsInstance(repr(ptr), str)
+
def test_parts(self):
paths = [
("", []),