]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-45249: Fix caret location when end_offset is set to 0 (GH-28855)
authorPablo Galindo Salgado <Pablogsal@gmail.com>
Sat, 16 Oct 2021 17:27:43 +0000 (18:27 +0100)
committerGitHub <noreply@github.com>
Sat, 16 Oct 2021 17:27:43 +0000 (10:27 -0700)
Lib/test/test_traceback.py
Lib/traceback.py
Misc/NEWS.d/next/Library/2021-10-10-16-14-33.bpo-45249.xqLliz.rst [new file with mode: 0644]

index 83d36e12c02d146574149b39091734acde29f059..1c7db9d3d47376252da989e1df8f32f12b6424ac 100644 (file)
@@ -55,6 +55,9 @@ class TracebackCases(unittest.TestCase):
     def syntax_error_bad_indentation2(self):
         compile(" print(2)", "?", "exec")
 
+    def tokenizer_error_with_caret_range(self):
+        compile("blech  (  ", "?", "exec")
+
     def test_caret(self):
         err = self.get_exception_format(self.syntax_error_with_caret,
                                         SyntaxError)
@@ -85,6 +88,13 @@ class TracebackCases(unittest.TestCase):
         self.assertEqual(err[1].find("y"), err[2].find("^"))  # in the right place
         self.assertEqual(err[2].count("^"), len("y for y in range(30)"))
 
+        err = self.get_exception_format(self.tokenizer_error_with_caret_range,
+                                        SyntaxError)
+        self.assertIn("^", err[2]) # third line has caret
+        self.assertEqual(err[2].count('\n'), 1)   # and no additional newline
+        self.assertEqual(err[1].find("("), err[2].find("^"))  # in the right place
+        self.assertEqual(err[2].count("^"), 1)
+
     def test_nocaret(self):
         exc = SyntaxError("error", ("x.py", 23, None, "bad syntax"))
         err = traceback.format_exception_only(SyntaxError, exc)
index 3cb8e5700de44866d45bbb615454462f8a7efde7..568f3ff28c29b2d9c92247eb4dbc91a587d1eab0 100644 (file)
@@ -781,7 +781,7 @@ class TracebackException:
 
             if self.offset is not None:
                 offset = self.offset
-                end_offset = self.end_offset if self.end_offset is not None else offset
+                end_offset = self.end_offset if self.end_offset not in {None, 0} else offset
                 if offset == end_offset or end_offset == -1:
                     end_offset = offset + 1
 
diff --git a/Misc/NEWS.d/next/Library/2021-10-10-16-14-33.bpo-45249.xqLliz.rst b/Misc/NEWS.d/next/Library/2021-10-10-16-14-33.bpo-45249.xqLliz.rst
new file mode 100644 (file)
index 0000000..1d5a857
--- /dev/null
@@ -0,0 +1,2 @@
+Fix the behaviour of :func:`traceback.print_exc` when displaying the caret
+when the ``end_offset`` in the exception is set to 0. Patch by Pablo Galindo