Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add test for syntax error (and fix colorization)
  • Loading branch information
pablogsal committed Dec 5, 2023
commit 1838f1c8f5a18792a7b5a0f6c3e44a84348072c3
21 changes: 21 additions & 0 deletions Lib/test/test_traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -4284,6 +4284,27 @@ def bar():
self.assertIn(boldr + ",4)" + reset, lines)
self.assertIn(red + "bar" + reset + boldr + "()" + reset, lines)

def test_colorized_syntax_error(self):
try:
compile("a $ b", "<string>", "exec")
except SyntaxError as e:
exc = traceback.TracebackException.from_exception(
e, capture_locals=True
)
actual = "".join(exc.format(colorize=True))
red = traceback._ANSIColors.RED
magenta = traceback._ANSIColors.MAGENTA
boldm = traceback._ANSIColors.BOLD_MAGENTA
boldr = traceback._ANSIColors.BOLD_RED
reset = traceback._ANSIColors.RESET
expected = "".join([
f' File {magenta}"<string>"{reset}, line {magenta}1{reset}\n',
f' a {boldr}${reset} b\n',
f' {boldr}^{reset}\n',
f'{boldm}SyntaxError{reset}: {magenta}invalid syntax{reset}\n']
)
self.assertIn(expected, actual)

def test_colorized_traceback_is_the_default(self):
def foo():
1/0
Expand Down
20 changes: 15 additions & 5 deletions Lib/traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -1310,22 +1310,32 @@ def _format_syntax_error(self, stype, **kwargs):
# colorize from colno to end_colno
ltext = (
ltext[:colno] +
_ANSIColors.RED + ltext[colno:end_colno] + _ANSIColors.RESET +
_ANSIColors.BOLD_RED + ltext[colno:end_colno] + _ANSIColors.RESET +
ltext[end_colno:]
)
start_color = _ANSIColors.RED
start_color = _ANSIColors.BOLD_RED
end_color = _ANSIColors.RESET
yield ' {}\n'.format(ltext)
yield ' {}{}{}{}'.format(
yield ' {}{}{}{}\n'.format(
"".join(caretspace),
start_color,
('^' * (end_colno - colno) + "\n"),
('^' * (end_colno - colno)),
end_color,
)
else:
yield ' {}\n'.format(ltext)
msg = self.msg or "<no detail available>"
yield "{}: {}{}\n".format(stype, msg, filename_suffix)
if colorize:
yield "{}{}{}: {}{}{}{}\n".format(
_ANSIColors.BOLD_MAGENTA,
stype,
_ANSIColors.RESET,
_ANSIColors.MAGENTA,
msg,
_ANSIColors.RESET,
filename_suffix)
else:
yield "{}: {}{}\n".format(stype, msg, filename_suffix)

def format(self, *, chain=True, _ctx=None, **kwargs):
"""Format the exception.
Expand Down