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