Skip to content
Open
42 changes: 20 additions & 22 deletions Lib/test/test_traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -3802,6 +3802,26 @@ def test_traceback_header(self):
exc = traceback.TracebackException(Exception, Exception("haven"), None)
self.assertEqual(list(exc.format()), ["Exception: haven\n"])

def test_exception_punctuation_handling_with_suggestions(self):
def raise_mssage(message, name):
try:
raise NameError(message, name=name)
except Exception as e:
return traceback.TracebackException.from_exception(e)._str

test_cases = [
("Error.", "time", "Error. Did you forget to import 'time'?"),
("Error?", "time", "Error? Did you forget to import 'time'?"),
("Error!", "time", "Error! Did you forget to import 'time'?"),
("Error", "time", "Error. Did you forget to import 'time'?"),
("Error", "foo123", "Error"),
]
for puctuation, name, expected in test_cases:
with self.subTest(puctuation=puctuation):
messsage = raise_mssage(puctuation, name)
self.assertEqual(messsage, expected)


@requires_debug_ranges()
def test_print(self):
def f():
Expand Down Expand Up @@ -4878,28 +4898,6 @@ class PurePythonSuggestionFormattingTests(
traceback printing in traceback.py.
"""

def test_exception_punctuation_handling_with_suggestions(self):
def raise_with_period(): raise NameError("Error.", name='time')
def raise_with_exclamation(): raise NameError("Error!", name='time')
def raise_with_question(): raise NameError("Error?", name='time')
def raise_without_punctuation(): raise NameError("Error", name='time')

test_cases = [
(raise_with_period, "."),
(raise_with_exclamation, "!"),
(raise_with_question, "?"),
(raise_without_punctuation, "."),
]

for raise_function, punctuation in test_cases:
with self.subTest(raise_func=raise_function.__name__):
result_lines = self.get_exception(
raise_function, slice_start=-1, slice_end=None
)
expected = f"NameError: Error{punctuation} Did you forget to import 'time'?"
self.assertEqual(result_lines[0], expected)



@cpython_only
class CPythonSuggestionFormattingTests(
Expand Down
6 changes: 3 additions & 3 deletions Lib/traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -1732,16 +1732,16 @@ def _suggestion_message(exc_type, exc_value, exc_traceback):
other_name = _compute_suggestion_error(
exc_value, exc_traceback, wrong_name
)
maybe_builtin_import = (
maybe_stdlib_import = (
issubclass(exc_type, NameError)
and wrong_name in sys.stdlib_module_names
)
if not other_name:
if maybe_builtin_import:
if maybe_stdlib_import:
return f"Did you forget to import '{wrong_name}'?"
return None
text = f"Did you mean: '{other_name}'?"
if maybe_builtin_import:
if maybe_stdlib_import:
return f"{text} Or did you forget to import '{wrong_name}'?"
return text
return None
Expand Down
Loading