Skip to content

Commit c431f37

Browse files
committed
gh-143201: warnings writes the full source line instead of the truncated one
The truncated object is meant to be written instead.
1 parent 7a91841 commit c431f37

3 files changed

Lines changed: 27 additions & 1 deletion

File tree

Lib/test/test_warnings/__init__.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1094,6 +1094,31 @@ def test_showwarnmsg_missing(self):
10941094
self.module._showwarnmsg = show
10951095
self.assertIn(text, result)
10961096

1097+
def test_showwarning_fallback_truncates_source_line(self):
1098+
# gh-143201: C implementation's show_warning fallback should truncate leading whitespace
1099+
text = 'test fallback truncates source line'
1100+
with self.module.catch_warnings():
1101+
self.module.filterwarnings("always", category=UserWarning)
1102+
1103+
show = self.module._showwarnmsg
1104+
show_orig = getattr(self.module, 'showwarning', None)
1105+
try:
1106+
del self.module._showwarnmsg
1107+
if hasattr(self.module, 'showwarning'):
1108+
del self.module.showwarning
1109+
with support.captured_output('stderr') as stream:
1110+
def my_warn():
1111+
self.module.warn(text)
1112+
my_warn()
1113+
result = stream.getvalue()
1114+
finally:
1115+
self.module._showwarnmsg = show
1116+
if show_orig is not None:
1117+
self.module.showwarning = show_orig
1118+
1119+
self.assertIn('self.module.warn(text)', result)
1120+
self.assertNotIn(' self.module.warn(text)', result)
1121+
10971122
def test_showwarning_not_callable(self):
10981123
orig = self.module.showwarning
10991124
try:
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix an issue where the :mod:`warnings` module printed the full source line instead of the truncated one.

Python/_warnings.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -698,7 +698,7 @@ show_warning(PyThreadState *tstate, PyObject *filename, int lineno,
698698
if (truncated == NULL)
699699
goto error;
700700

701-
PyFile_WriteObject(sourceline, f_stderr, Py_PRINT_RAW);
701+
PyFile_WriteObject(truncated, f_stderr, Py_PRINT_RAW);
702702
Py_DECREF(truncated);
703703
PyFile_WriteString("\n", f_stderr);
704704
}

0 commit comments

Comments
 (0)