@@ -699,6 +699,35 @@ def f_with_multiline():
699
699
result_lines = self .get_exception (f_with_multiline )
700
700
self .assertEqual (result_lines , expected_f .splitlines ())
701
701
702
+ # Check custom error messages covering multiple lines
703
+ code = textwrap .dedent ("""
704
+ dummy_call(
705
+ "dummy value"
706
+ foo="bar",
707
+ )
708
+ """ )
709
+
710
+ def f_with_multiline ():
711
+ # Need to defer the compilation until in self.get_exception(..)
712
+ return compile (code , "?" , "exec" )
713
+
714
+ lineno_f = f_with_multiline .__code__ .co_firstlineno
715
+
716
+ expected_f = (
717
+ 'Traceback (most recent call last):\n '
718
+ f' File "{ __file__ } ", line { self .callable_line } , in get_exception\n '
719
+ ' callable()\n '
720
+ ' ~~~~~~~~^^\n '
721
+ f' File "{ __file__ } ", line { lineno_f + 2 } , in f_with_multiline\n '
722
+ ' return compile(code, "?", "exec")\n '
723
+ ' File "?", line 3\n '
724
+ ' "dummy value"\n '
725
+ ' ^^^^^^^^^^^^^'
726
+ )
727
+
728
+ result_lines = self .get_exception (f_with_multiline )
729
+ self .assertEqual (result_lines , expected_f .splitlines ())
730
+
702
731
def test_caret_multiline_expression_bin_op (self ):
703
732
# Make sure no carets are printed for expressions spanning multiple
704
733
# lines.
@@ -2312,19 +2341,22 @@ def test_message_none(self):
2312
2341
def test_syntax_error_various_offsets (self ):
2313
2342
for offset in range (- 5 , 10 ):
2314
2343
for add in [0 , 2 ]:
2315
- text = " " * add + "text%d" % offset
2344
+ text = " " * add + "text%d" % offset
2316
2345
expected = [' File "file.py", line 1' ]
2317
2346
if offset < 1 :
2318
2347
expected .append (" %s" % text .lstrip ())
2319
2348
elif offset <= 6 :
2320
2349
expected .append (" %s" % text .lstrip ())
2321
- expected .append (" %s^" % (" " * (offset - 1 )))
2350
+ # Set the caret length to match the length of the text minus the offset.
2351
+ caret_length = max (1 , len (text .lstrip ()) - offset + 1 )
2352
+ expected .append (" %s%s" % (" " * (offset - 1 ), "^" * caret_length ))
2322
2353
else :
2354
+ caret_length = max (1 , len (text .lstrip ()) - 4 )
2323
2355
expected .append (" %s" % text .lstrip ())
2324
- expected .append (" %s^ " % (" " * 5 ))
2356
+ expected .append (" %s%s " % (" " * 5 , "^" * caret_length ))
2325
2357
expected .append ("SyntaxError: msg" )
2326
2358
expected .append ("" )
2327
- err = self .get_report (SyntaxError ("msg" , ("file.py" , 1 , offset + add , text )))
2359
+ err = self .get_report (SyntaxError ("msg" , ("file.py" , 1 , offset + add , text )))
2328
2360
exp = "\n " .join (expected )
2329
2361
self .assertEqual (exp , err )
2330
2362
0 commit comments