mirror of
https://github.com/python/cpython.git
synced 2026-05-06 12:49:07 -04:00
gh-145058: Add input validation to _PyImport_LazyImportModuleLevelObject (#145068)
This commit is contained in:
@@ -393,6 +393,15 @@ class DunderLazyImportTests(unittest.TestCase):
|
||||
import test.test_import.data.lazy_imports.dunder_lazy_import_used
|
||||
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
|
||||
|
||||
def test_dunder_lazy_import_invalid_arguments(self):
|
||||
"""__lazy_import__ should reject invalid arguments."""
|
||||
for invalid_name in (b"", 123, None):
|
||||
with self.assertRaises(TypeError):
|
||||
__lazy_import__(invalid_name)
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
__lazy_import__("sys", level=-1)
|
||||
|
||||
def test_dunder_lazy_import_builtins(self):
|
||||
"""__lazy_import__ should use module's __builtins__ for __import__."""
|
||||
from test.test_import.data.lazy_imports import dunder_lazy_import_builtins
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
Fix a crash when :func:`!__lazy_import__` is passed a non-string argument,
|
||||
by raising an :exc:`TypeError` instead.
|
||||
@@ -4468,6 +4468,17 @@ _PyImport_LazyImportModuleLevelObject(PyThreadState *tstate,
|
||||
PyObject *globals, PyObject *locals,
|
||||
PyObject *fromlist, int level)
|
||||
{
|
||||
assert(name != NULL);
|
||||
if (!PyUnicode_Check(name)) {
|
||||
_PyErr_Format(tstate, PyExc_TypeError,
|
||||
"module name must be a string, got %T", name);
|
||||
return NULL;
|
||||
}
|
||||
if (level < 0) {
|
||||
_PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
PyObject *abs_name = get_abs_name(tstate, name, globals, level);
|
||||
if (abs_name == NULL) {
|
||||
return NULL;
|
||||
|
||||
Reference in New Issue
Block a user