Skip to content

Commit 9cbc8e8

Browse files
Copilotstefankoegl
andcommitted
Add VERBOSE_EXCEPTIONS flag to control JsonPointerException verbosity
Co-authored-by: stefankoegl <184196+stefankoegl@users.noreply.github.com>
1 parent cb6ec22 commit 9cbc8e8

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

jsonpointer.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@
4545

4646
_nothing = object()
4747

48+
# If True, exceptions include the doc content in the error message.
49+
# Set to False to suppress potentially large document content from exceptions.
50+
VERBOSE_EXCEPTIONS = True
51+
4852

4953
def set_pointer(doc, pointer, value, inplace=True):
5054
"""Resolves a pointer against doc and sets the value of the target within doc.
@@ -271,7 +275,10 @@ def walk(self, doc, part):
271275
return doc[part]
272276

273277
except KeyError:
274-
raise JsonPointerException("member '%s' not found in %s" % (part, doc))
278+
if VERBOSE_EXCEPTIONS:
279+
raise JsonPointerException("member '%s' not found in %s" % (part, doc))
280+
else:
281+
raise JsonPointerException("member '%s' not found" % (part,))
275282

276283
def contains(self, ptr):
277284
""" Returns True if self contains the given ptr """

tests.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,35 @@ def test_mock_dict_raises_key_error(self):
391391
self.assertRaises(JsonPointerException, resolve_pointer, doc, '/root/1/2/3/4')
392392

393393

394+
class VerboseExceptionsTests(unittest.TestCase):
395+
396+
def setUp(self):
397+
# Save original value and ensure verbose mode is on for each test
398+
self._original = jsonpointer.VERBOSE_EXCEPTIONS
399+
jsonpointer.VERBOSE_EXCEPTIONS = True
400+
401+
def tearDown(self):
402+
jsonpointer.VERBOSE_EXCEPTIONS = self._original
403+
404+
def test_verbose_exception_includes_doc(self):
405+
doc = {'foo': 1}
406+
try:
407+
resolve_pointer(doc, '/bar')
408+
self.fail('Expected JsonPointerException')
409+
except JsonPointerException as e:
410+
self.assertIn(repr(doc), str(e))
411+
412+
def test_non_verbose_exception_excludes_doc(self):
413+
doc = {'foo': 1}
414+
jsonpointer.VERBOSE_EXCEPTIONS = False
415+
try:
416+
resolve_pointer(doc, '/bar')
417+
self.fail('Expected JsonPointerException')
418+
except JsonPointerException as e:
419+
self.assertNotIn(repr(doc), str(e))
420+
self.assertIn('bar', str(e))
421+
422+
394423
def load_tests(loader, tests, ignore):
395424
tests.addTests(doctest.DocTestSuite(jsonpointer))
396425
return tests

0 commit comments

Comments
 (0)