Skip to content

bpo-31285: fix an assertion failure and a SystemError in warnings.warn_explicit #3219

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
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
36 changes: 36 additions & 0 deletions Lib/test/test_warnings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -794,6 +794,42 @@ def test_stderr_none(self):
self.assertNotIn(b'Warning!', stderr)
self.assertNotIn(b'Error', stderr)

def test_issue31285(self):
# warn_explicit() should neither raise a SystemError nor cause an
# assertion failure, in case the return value of get_source() has a
# bad splitlines() method.
def get_bad_loader(splitlines_ret_val):
class BadLoader:
def get_source(self, fullname):
class BadSource(str):
def splitlines(self):
return splitlines_ret_val
return BadSource('spam')
return BadLoader()

wmod = self.module
with original_warnings.catch_warnings(module=wmod):
wmod.filterwarnings('default', category=UserWarning)

with support.captured_stderr() as stderr:
wmod.warn_explicit(
'foo', UserWarning, 'bar', 1,
module_globals={'__loader__': get_bad_loader(42),
'__name__': 'foobar'})
self.assertIn('UserWarning: foo', stderr.getvalue())

show = wmod._showwarnmsg
try:
del wmod._showwarnmsg
with support.captured_stderr() as stderr:
wmod.warn_explicit(
'eggs', UserWarning, 'bar', 1,
module_globals={'__loader__': get_bad_loader([42]),
'__name__': 'foobar'})
self.assertIn('UserWarning: eggs', stderr.getvalue())
finally:
wmod._showwarnmsg = show

@support.cpython_only
def test_issue31411(self):
# warn_explicit() shouldn't raise a SystemError in case
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix an assertion failure in `warnings.warn_explicit`, when the return value
of the received loader's get_source() has a bad splitlines() method. Patch
by Oren Milman.
4 changes: 1 addition & 3 deletions Python/_warnings.c
Original file line number Diff line number Diff line change
Expand Up @@ -893,9 +893,7 @@ warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds)
}

/* Split the source into lines. */
source_list = PyObject_CallMethodObjArgs(source,
PyId_splitlines.object,
NULL);
source_list = PyUnicode_Splitlines(source, 0);
Py_DECREF(source);
if (!source_list)
return NULL;
Expand Down