Skip to content

Commit 6ba3896

Browse files
committed
Add regression test
1 parent 6d8002f commit 6ba3896

2 files changed

Lines changed: 33 additions & 0 deletions

File tree

Lib/test/test_lazy_import/__init__.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1949,6 +1949,17 @@ def filter(*args):
19491949
def test_set_bad_filter(self):
19501950
self.assertRaises(ValueError, _testcapi.PyImport_SetLazyImportsFilter, 42)
19511951

1952+
def test_dunder_lazy_import_without_frame(self):
1953+
# gh-151510: __lazy_import__() called with no globals and no running
1954+
# Python frame must raise TypeError instead of crashing.
1955+
with self.assertRaisesRegex(
1956+
TypeError,
1957+
r"__lazy_import__\(\) missing globals when called without a frame",
1958+
):
1959+
_testcapi.lazy_import_without_frame(
1960+
"test.test_lazy_import.data.basic2"
1961+
)
1962+
19521963

19531964
if __name__ == '__main__':
19541965
unittest.main()

Modules/_testcapi/import.c

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,27 @@
11
#include "parts.h"
22
#include "util.h"
33

4+
static PyObject *
5+
pyimport_lazyimportwithoutframe(PyObject *self, PyObject *name)
6+
{
7+
PyObject *lazy_import = PyImport_ImportModuleAttrString("builtins",
8+
"__lazy_import__");
9+
if (lazy_import == NULL) {
10+
return NULL;
11+
}
12+
13+
// Simulate being called with no running Python frame (e.g. from a freshly
14+
// attached C thread), so that PyEval_GetGlobals() returns NULL.
15+
PyThreadState *tstate = PyThreadState_Get();
16+
struct _PyInterpreterFrame *saved = tstate->current_frame;
17+
tstate->current_frame = NULL;
18+
PyObject *res = PyObject_CallOneArg(lazy_import, name);
19+
tstate->current_frame = saved;
20+
21+
Py_DECREF(lazy_import);
22+
return res;
23+
}
24+
425
// Test PyImport_ImportModuleAttr()
526
static PyObject *
627
pyimport_importmoduleattr(PyObject *self, PyObject *args)
@@ -95,6 +116,7 @@ static PyMethodDef test_methods[] = {
95116
{"PyImport_GetLazyImportsMode", pyimport_getlazyimportsmode, METH_NOARGS},
96117
{"PyImport_SetLazyImportsFilter", pyimport_setlazyimportsfilter, METH_VARARGS},
97118
{"PyImport_GetLazyImportsFilter", pyimport_getlazyimportsfilter, METH_NOARGS},
119+
{"lazy_import_without_frame", pyimport_lazyimportwithoutframe, METH_O},
98120
{NULL},
99121
};
100122

0 commit comments

Comments
 (0)