Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
25 changes: 25 additions & 0 deletions Lib/test/test_warnings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1094,6 +1094,31 @@ def test_showwarnmsg_missing(self):
self.module._showwarnmsg = show
self.assertIn(text, result)

def test_showwarning_fallback_truncates_source_line(self):
# gh-143201: C implementation's show_warning fallback should truncate leading whitespace
text = 'test fallback truncates source line'
with self.module.catch_warnings():
self.module.filterwarnings("always", category=UserWarning)

show = self.module._showwarnmsg
show_orig = getattr(self.module, 'showwarning', None)
try:
del self.module._showwarnmsg
if hasattr(self.module, 'showwarning'):
del self.module.showwarning
with support.captured_output('stderr') as stream:
def my_warn():
self.module.warn(text)
my_warn()
result = stream.getvalue()
finally:
self.module._showwarnmsg = show
if show_orig is not None:
self.module.showwarning = show_orig

self.assertIn('self.module.warn(text)', result)
self.assertNotIn(' self.module.warn(text)', result)

def test_showwarning_not_callable(self):
orig = self.module.showwarning
try:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix an issue where the :mod:`warnings` module printed the full source line instead of the truncated one.
2 changes: 1 addition & 1 deletion Python/_warnings.c
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,7 @@ show_warning(PyThreadState *tstate, PyObject *filename, int lineno,
if (truncated == NULL)
goto error;

PyFile_WriteObject(sourceline, f_stderr, Py_PRINT_RAW);
PyFile_WriteObject(truncated, f_stderr, Py_PRINT_RAW);
Py_DECREF(truncated);
PyFile_WriteString("\n", f_stderr);
}
Expand Down
Loading