Skip to content
Open
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
31 changes: 31 additions & 0 deletions Lib/test/test_warnings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1661,6 +1661,37 @@ def test_RuntimeError(self):
_version=version)


class WarnExplicitSourceTests(BaseTest):
# gh-155319: the source line is taken from the loader of the module
# whose globals are passed as module_globals, if the file which name
# is passed as filename cannot be read.

def warn_explicit(self, lineno):
with support.captured_stderr() as stderr:
with self.module.catch_warnings():
self.module.simplefilter("always")
self.module.warn_explicit(
'eggs', UserWarning, 'nonexistent', lineno,
module_globals=warning_tests.__dict__)
return stderr.getvalue()

def test_source_line(self):
source = warning_tests.__loader__.get_source(warning_tests.__name__)
expected = source.splitlines()[0].strip()
self.assertEqual(self.warn_explicit(1),
f'nonexistent:1: UserWarning: eggs\n {expected}\n')

def test_source_line_out_of_range(self):
self.assertEqual(self.warn_explicit(1000),
'nonexistent:1000: UserWarning: eggs\n')

class CWarnExplicitSourceTests(WarnExplicitSourceTests, unittest.TestCase):
module = c_warnings

class PyWarnExplicitSourceTests(WarnExplicitSourceTests, unittest.TestCase):
module = py_warnings


class BootstrapTest(unittest.TestCase):

def test_issue_8766(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
:func:`warnings.warn_explicit` now displays the source line taken from the
loader of the module whose globals are passed as *module_globals*. It also
no longer raises :exc:`IndexError` if *lineno* is out of the range of the
module source.
10 changes: 7 additions & 3 deletions Python/_warnings.c
Original file line number Diff line number Diff line change
Expand Up @@ -747,7 +747,8 @@ call_show_warning(PyThreadState *tstate, PyObject *category,
}

msg = PyObject_CallFunctionObjArgs(warnmsg_cls, message, category,
filename, lineno_obj, Py_None, Py_None,
filename, lineno_obj, Py_None,
sourceline ? sourceline : Py_None,
source ? source : Py_None, module,
NULL);
Py_DECREF(warnmsg_cls);
Expand Down Expand Up @@ -1234,8 +1235,11 @@ get_source_line(PyInterpreterState *interp, PyObject *module_globals, int lineno
}

/* Get the source line. */
source_line = PyList_GetItem(source_list, lineno-1);
Py_XINCREF(source_line);
if (lineno < 1 || lineno > PyList_GET_SIZE(source_list)) {
Py_DECREF(source_list);
return NULL;
}
source_line = Py_NewRef(PyList_GET_ITEM(source_list, lineno-1));
Py_DECREF(source_list);
return source_line;
}
Expand Down
Loading