Skip to content

Commit

Permalink
Apply some small formatting fixes in ultratb
Browse files Browse the repository at this point in the history
  • Loading branch information
EtiennePelletier committed May 1, 2023
1 parent ef994b4 commit f7014a8
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 30 deletions.
26 changes: 13 additions & 13 deletions IPython/core/tests/test_ultratb.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,24 +51,24 @@ def wrapper(*args, **kwargs):
class ChangedPyFileTest(unittest.TestCase):
def test_changing_py_file(self):
"""Traceback produced if the line where the error occurred is missing?
https://github.com/ipython/ipython/issues/1456
"""
with TemporaryDirectory() as td:
fname = os.path.join(td, "foo.py")
with open(fname, "w", encoding="utf-8") as f:
f.write(file_1)

with prepended_to_syspath(td):
ip.run_cell("import foo")

with tt.AssertPrints("ZeroDivisionError"):
ip.run_cell("foo.f()")

# Make the file shorter, so the line of the error is missing.
with open(fname, "w", encoding="utf-8") as f:
f.write(file_2)

# For some reason, this was failing on the *second* call after
# changing the file, so we call f() twice.
with tt.AssertNotPrints("Internal Python error", channel='stderr'):
Expand All @@ -92,27 +92,27 @@ def test_nonascii_path(self):
fname = os.path.join(td, u"fooé.py")
with open(fname, "w", encoding="utf-8") as f:
f.write(file_1)

with prepended_to_syspath(td):
ip.run_cell("import foo")

with tt.AssertPrints("ZeroDivisionError"):
ip.run_cell("foo.f()")

def test_iso8859_5(self):
with TemporaryDirectory() as td:
fname = os.path.join(td, 'dfghjkl.py')

with io.open(fname, 'w', encoding='iso-8859-5') as f:
f.write(iso_8859_5_file)

with prepended_to_syspath(td):
ip.run_cell("from dfghjkl import fail")

with tt.AssertPrints("ZeroDivisionError"):
with tt.AssertPrints(u'дбИЖ', suppress=False):
ip.run_cell('fail()')

def test_nonascii_msg(self):
cell = u"raise Exception('é')"
expected = u"Exception('é')"
Expand Down Expand Up @@ -167,12 +167,12 @@ def test_indentationerror_shows_line(self):
with tt.AssertPrints("IndentationError"):
with tt.AssertPrints("zoon()", suppress=False):
ip.run_cell(indentationerror_file)

with TemporaryDirectory() as td:
fname = os.path.join(td, "foo.py")
with open(fname, "w", encoding="utf-8") as f:
f.write(indentationerror_file)

with tt.AssertPrints("IndentationError"):
with tt.AssertPrints("zoon()", suppress=False):
ip.magic('run %s' % fname)
Expand Down
37 changes: 20 additions & 17 deletions IPython/core/ultratb.py
Original file line number Diff line number Diff line change
Expand Up @@ -591,7 +591,7 @@ def _format_list(self, extracted_list):
"""

Colors = self.Colors
list = []
output_list = []
for ind, (filename, lineno, name, line) in enumerate(extracted_list):
normalCol, nameCol, fileCol, lineCol = (
# Emphasize the last entry
Expand All @@ -609,9 +609,9 @@ def _format_list(self, extracted_list):
item += "\n"
if line:
item += f"{lineCol} {line.strip()}{normalCol}\n"
list.append(item)
output_list.append(item)

return list
return output_list

def _format_exception_only(self, etype, value):
"""Format the exception part of a traceback.
Expand All @@ -628,11 +628,11 @@ def _format_exception_only(self, etype, value):
"""
have_filedata = False
Colors = self.Colors
list = []
output_list = []
stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
if value is None:
# Not sure if this can still happen in Python 2.6 and above
list.append(stype + '\n')
output_list.append(stype + "\n")
else:
if issubclass(etype, SyntaxError):
have_filedata = True
Expand All @@ -643,7 +643,7 @@ def _format_exception_only(self, etype, value):
else:
lineno = "unknown"
textline = ""
list.append(
output_list.append(
"%s %s%s\n"
% (
Colors.normalEm,
Expand All @@ -663,39 +663,41 @@ def _format_exception_only(self, etype, value):
i = 0
while i < len(textline) and textline[i].isspace():
i += 1
list.append('%s %s%s\n' % (Colors.line,
textline.strip(),
Colors.Normal))
output_list.append(
"%s %s%s\n" % (Colors.line, textline.strip(), Colors.Normal)
)
if value.offset is not None:
s = ' '
for c in textline[i:value.offset - 1]:
if c.isspace():
s += c
else:
s += ' '
list.append('%s%s^%s\n' % (Colors.caret, s,
Colors.Normal))
s += " "
output_list.append(
"%s%s^%s\n" % (Colors.caret, s, Colors.Normal)
)

try:
s = value.msg
except Exception:
s = self._some_str(value)
if s:
list.append('%s%s:%s %s\n' % (stype, Colors.excName,
Colors.Normal, s))
output_list.append(
"%s%s:%s %s\n" % (stype, Colors.excName, Colors.Normal, s)
)
else:
list.append('%s\n' % stype)
output_list.append("%s\n" % stype)

# PEP-678 notes
list.extend(f"{x}\n" for x in getattr(value, "__notes__", []))
output_list.extend(f"{x}\n" for x in getattr(value, "__notes__", []))

# sync with user hooks
if have_filedata:
ipinst = get_ipython()
if ipinst is not None:
ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)

return list
return output_list

def get_exception_only(self, etype, value):
"""Only print the exception type and message, without a traceback.
Expand Down Expand Up @@ -1012,6 +1014,7 @@ def format_exception(self, etype, evalue):
etype, evalue = str, sys.exc_info()[:2]
etype_str, evalue_str = map(str, (etype, evalue))

# PEP-678 notes
notes = getattr(evalue, "__notes__", [])
if not isinstance(notes, Sequence) or isinstance(notes, (str, bytes)):
notes = [_safe_string(notes, "__notes__", func=repr)]
Expand Down

0 comments on commit f7014a8

Please sign in to comment.