jsonpointer 3.4__tar.gz → 3.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jsonpointer
3
- Version: 3.4
3
+ Version: 3.6
4
4
  Summary: Identify specific nodes in a JSON document (RFC 6901)
5
5
  Home-page: https://github.com/stefankoegl/python-json-pointer
6
6
  Author: Stefan Kögl
@@ -13,7 +13,7 @@ parser = argparse.ArgumentParser(
13
13
  # Accept pointer as option, as file or as first positional argument
14
14
  ptr_group = parser.add_mutually_exclusive_group()
15
15
 
16
- ptr_group.add_argument('-f', '--pointer-file', type=argparse.FileType('r'),
16
+ ptr_group.add_argument('-f', '--pointer-file', type=argparse.FileType('r', encoding='utf-8'),
17
17
  help='File containing a JSON pointer expression')
18
18
 
19
19
  ptr_group.add_argument('-p', '--pointer', type=str,
@@ -58,7 +58,11 @@ def parse_pointer(args):
58
58
  ptr = args.pointer
59
59
  else:
60
60
  # 2026-10-11: Trim file line endings without changing member names.
61
- ptr = args.pointer_file.read().rstrip("\r\n")
61
+ try:
62
+ ptr = args.pointer_file.read().rstrip("\r\n")
63
+ finally:
64
+ if args.pointer_file is not sys.stdin:
65
+ args.pointer_file.close()
62
66
 
63
67
  elif args.POINTER is not None:
64
68
  ptr = args.POINTER
@@ -88,7 +92,7 @@ def resolve_files():
88
92
 
89
93
  for name in files:
90
94
  try:
91
- f = argparse.FileType('r')(name)
95
+ f = argparse.FileType('r', encoding='utf-8')(name)
92
96
  except argparse.ArgumentTypeError as e:
93
97
  parser.error(str(e))
94
98
 
@@ -101,9 +105,15 @@ def resolve_files():
101
105
  file=sys.stderr)
102
106
  ok = False
103
107
  continue
108
+ finally:
109
+ if f is not sys.stdin:
110
+ f.close()
104
111
 
105
112
  try:
106
113
  result = jsonpointer.resolve_pointer(doc, ptr)
114
+ if isinstance(result, jsonpointer.EndOfList):
115
+ raise jsonpointer.JsonPointerException(
116
+ "'-' does not reference an existing array element")
107
117
  print(json.dumps(result, indent=args.indent))
108
118
  except jsonpointer.JsonPointerException as e:
109
119
  print('Could not resolve pointer: %s' % str(e), file=sys.stderr)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jsonpointer
3
- Version: 3.4
3
+ Version: 3.6
4
4
  Summary: Identify specific nodes in a JSON document (RFC 6901)
5
5
  Home-page: https://github.com/stefankoegl/python-json-pointer
6
6
  Author: Stefan Kögl
@@ -32,7 +32,7 @@
32
32
 
33
33
  # Will be parsed by setup.py to determine package metadata
34
34
  __author__ = 'Stefan Kögl <stefan@skoegl.net>'
35
- __version__ = '3.4'
35
+ __version__ = '3.6'
36
36
  __website__ = 'https://github.com/stefankoegl/python-json-pointer'
37
37
  __license__ = 'Modified BSD License'
38
38
 
@@ -349,11 +349,34 @@ class JsonPointer:
349
349
  raise JsonPointerException("member '%s' not found" % (part,))
350
350
 
351
351
  def contains(self, ptr):
352
- """ Returns True if self contains the given ptr """
352
+ """Returns True if ptr's parts are a prefix of this pointer's parts.
353
+
354
+ Equal pointers and the root pointer are also prefixes. For example,
355
+ the longer pointer calls contains() with its parent:
356
+
357
+ >>> child = JsonPointer('/foo/bar')
358
+ >>> parent = JsonPointer('/foo')
359
+ >>> child.contains(parent)
360
+ True
361
+ >>> parent.contains(child)
362
+ False
363
+ >>> child.contains(child)
364
+ True
365
+ >>> child.contains(JsonPointer(''))
366
+ True
367
+ >>> child.contains(JsonPointer('/foo/b'))
368
+ False
369
+ """
353
370
  return self.parts[:len(ptr.parts)] == ptr.parts
354
371
 
355
372
  def __contains__(self, item):
356
- """ Returns True if self contains the given ptr """
373
+ """Equivalent to contains(): item must be a prefix of self.
374
+
375
+ >>> JsonPointer('/foo') in JsonPointer('/foo/bar')
376
+ True
377
+ >>> JsonPointer('/foo/bar') in JsonPointer('/foo')
378
+ False
379
+ """
357
380
  return self.contains(item)
358
381
 
359
382
  def join(self, suffix):
@@ -2,11 +2,16 @@
2
2
 
3
3
  import copy
4
4
  import doctest
5
+ import io
6
+ import json
5
7
  import os
8
+ import runpy
6
9
  import subprocess
7
10
  import sys
8
11
  import tempfile
9
12
  import unittest
13
+ from contextlib import redirect_stderr, redirect_stdout
14
+ from unittest import mock
10
15
 
11
16
  import jsonpointer
12
17
  from jsonpointer import resolve_pointer, EndOfList, JsonPointerException, \
@@ -566,14 +571,92 @@ class CommandLineTests(unittest.TestCase):
566
571
  self._write('ptr.txt', '/a\n')
567
572
 
568
573
  def _write(self, name, content):
569
- with open(os.path.join(self.dir, name), 'w') as f:
574
+ with open(os.path.join(self.dir, name), 'w', encoding='utf-8') as f:
570
575
  f.write(content)
571
576
 
572
- def _run(self, *args):
577
+ def _run(self, *args, utf8=True):
573
578
  env = dict(os.environ, PYTHONPATH=self.ROOT, PYTHONUTF8='1')
579
+ if not utf8:
580
+ # Keep pipes in UTF-8 while exercising locale-dependent file I/O.
581
+ env.update(PYTHONUTF8='0', PYTHONIOENCODING='utf-8',
582
+ LC_ALL='C', PYTHONCOERCECLOCALE='0')
574
583
  return subprocess.run([sys.executable, self.SCRIPT] + list(args),
575
584
  cwd=self.dir, env=env, capture_output=True,
576
- text=True)
585
+ encoding='utf-8')
586
+
587
+ def _run_with_retained_files(self, *args):
588
+ cli = runpy.run_path(self.SCRIPT)
589
+ opened = []
590
+ original_open = open
591
+
592
+ def retain_file(*args, **kwargs):
593
+ file_obj = original_open(*args, **kwargs)
594
+ opened.append(file_obj)
595
+ self.addCleanup(file_obj.close)
596
+ return file_obj
597
+
598
+ with mock.patch.object(sys, 'argv', [self.SCRIPT] + list(args)), \
599
+ mock.patch('builtins.open', side_effect=retain_file), \
600
+ redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
601
+ try:
602
+ return cli['resolve_files']()
603
+ finally:
604
+ self.assertTrue(opened)
605
+ self.assertTrue(all(file_obj.closed for file_obj in opened))
606
+
607
+ def test_closes_json_inputs(self):
608
+ self.assertTrue(self._run_with_retained_files(
609
+ '/a', os.path.join(self.dir, 'a.json'),
610
+ os.path.join(self.dir, 'b.json')))
611
+
612
+ def test_closes_pointer_file(self):
613
+ self.assertTrue(self._run_with_retained_files(
614
+ '-f', os.path.join(self.dir, 'ptr.txt'),
615
+ os.path.join(self.dir, 'a.json')))
616
+
617
+ def test_closes_invalid_pointer_file(self):
618
+ self._write('invalid-pointer.txt', 'missing-leading-slash')
619
+ with self.assertRaises(SystemExit) as caught:
620
+ self._run_with_retained_files(
621
+ '-f', os.path.join(self.dir, 'invalid-pointer.txt'),
622
+ os.path.join(self.dir, 'a.json'))
623
+ self.assertEqual(caught.exception.code, 2)
624
+
625
+ def test_closes_inputs_after_json_errors(self):
626
+ self._write('invalid.json', '{"a": }')
627
+ with self.assertRaises(json.JSONDecodeError):
628
+ self._run_with_retained_files('/a', os.path.join(self.dir, 'invalid.json'))
629
+ self.assertFalse(self._run_with_retained_files(
630
+ '--continue-on-error', '/a', os.path.join(self.dir, 'invalid.json'),
631
+ os.path.join(self.dir, 'a.json')))
632
+
633
+ def test_keeps_stdin_open(self):
634
+ cli = runpy.run_path(self.SCRIPT)
635
+ for args, content in ((['/a', '-'], '{"a": 1}'),
636
+ (['-f', '-', os.path.join(self.dir, 'a.json')], '/a\n')):
637
+ with self.subTest(args=args):
638
+ stdin = io.StringIO(content)
639
+ self.addCleanup(stdin.close)
640
+ with mock.patch.object(sys, 'argv', [self.SCRIPT] + args), \
641
+ mock.patch.object(sys, 'stdin', stdin), \
642
+ redirect_stdout(io.StringIO()):
643
+ self.assertTrue(cli['resolve_files']())
644
+ self.assertFalse(stdin.closed)
645
+
646
+ def test_utf8_json_file_without_utf8_mode(self):
647
+ self._write('unicode.json', '{"value": "🚀"}')
648
+ proc = self._run('/value', 'unicode.json', utf8=False)
649
+ self.assertEqual(proc.returncode, 0, proc.stderr)
650
+ self.assertEqual(json.loads(proc.stdout), '🚀')
651
+ self.assertEqual(proc.stderr, '')
652
+
653
+ def test_utf8_pointer_file_without_utf8_mode(self):
654
+ self._write('unicode.json', json.dumps({'ä': 'expected'}))
655
+ self._write('unicode.txt', '/ä\n')
656
+ proc = self._run('-f', 'unicode.txt', 'unicode.json', utf8=False)
657
+ self.assertEqual(proc.returncode, 0, proc.stderr)
658
+ self.assertEqual(json.loads(proc.stdout), 'expected')
659
+ self.assertEqual(proc.stderr, '')
577
660
 
578
661
  def test_positional_pointer(self):
579
662
  proc = self._run('/a', 'a.json', 'b.json')
@@ -639,6 +722,36 @@ class CommandLineTests(unittest.TestCase):
639
722
  self.assertIn('Could not resolve pointer', proc.stderr)
640
723
  self.assertEqual(proc.stdout, '')
641
724
 
725
+ def test_end_of_list_pointer(self):
726
+ for content, pointer in (('[]', '/-'), ('[1, 2]', '/-'),
727
+ ('{"a": []}', '/a/-')):
728
+ with self.subTest(content=content, pointer=pointer):
729
+ self._write('array.json', content)
730
+ proc = self._run(pointer, 'array.json')
731
+ self.assertEqual(proc.returncode, 1)
732
+ self.assertEqual(proc.stdout, '')
733
+ self.assertIn('Could not resolve pointer:', proc.stderr)
734
+ self.assertNotIn('Traceback', proc.stderr)
735
+
736
+ def test_end_of_list_pointer_in_one_file(self):
737
+ self._write('array.json', '{"a": []}')
738
+ self._write('member.json', '{"a": {"-": "value"}}')
739
+ for files in (('array.json', 'member.json'),
740
+ ('member.json', 'array.json')):
741
+ with self.subTest(files=files):
742
+ proc = self._run('/a/-', *files)
743
+ self.assertEqual(proc.returncode, 1)
744
+ self.assertEqual(proc.stdout, '"value"\n')
745
+ self.assertIn('Could not resolve pointer:', proc.stderr)
746
+ self.assertNotIn('Traceback', proc.stderr)
747
+
748
+ def test_hyphen_object_member(self):
749
+ self._write('member.json', '{"-": [1, 2]}')
750
+ proc = self._run('/-', 'member.json')
751
+ self.assertEqual(proc.returncode, 0, proc.stderr)
752
+ self.assertEqual(proc.stdout, '[1, 2]\n')
753
+ self.assertEqual(proc.stderr, '')
754
+
642
755
  def test_unresolvable_pointer_in_one_file(self):
643
756
  # /b resolves in b.json only; a.json is still reported but b.json
644
757
  # is processed
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes