Refactor insert_missing_modules function (#12210)

Makes the logic more straightforward IMO.
This commit is contained in:
Bruno Oliveira 2024-04-20 08:58:14 -03:00 committed by GitHub
parent ff806b239e
commit 6fb474a3eb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 22 additions and 25 deletions

View File

@ -737,11 +737,11 @@ def insert_missing_modules(modules: Dict[str, ModuleType], module_name: str) ->
otherwise "src.tests.test_foo" is not importable by ``__import__``. otherwise "src.tests.test_foo" is not importable by ``__import__``.
""" """
module_parts = module_name.split(".") module_parts = module_name.split(".")
child_module: Union[ModuleType, None] = None
module: Union[ModuleType, None] = None
child_name: str = ""
while module_name: while module_name:
if module_name not in modules: parent_module_name, _, child_name = module_name.rpartition(".")
if parent_module_name:
parent_module = modules.get(parent_module_name)
if parent_module is None:
try: try:
# If sys.meta_path is empty, calling import_module will issue # If sys.meta_path is empty, calling import_module will issue
# a warning and raise ModuleNotFoundError. To avoid the # a warning and raise ModuleNotFoundError. To avoid the
@ -749,22 +749,19 @@ def insert_missing_modules(modules: Dict[str, ModuleType], module_name: str) ->
# ourselves to fall back to creating a dummy module. # ourselves to fall back to creating a dummy module.
if not sys.meta_path: if not sys.meta_path:
raise ModuleNotFoundError raise ModuleNotFoundError
module = importlib.import_module(module_name) parent_module = importlib.import_module(parent_module_name)
except ModuleNotFoundError: except ModuleNotFoundError:
module = ModuleType( parent_module = ModuleType(
module_name, module_name,
doc="Empty module created by pytest's importmode=importlib.", doc="Empty module created by pytest's importmode=importlib.",
) )
else: modules[parent_module_name] = parent_module
module = modules[module_name]
if child_module:
# Add child attribute to the parent that can reference the child # Add child attribute to the parent that can reference the child
# modules. # modules.
if not hasattr(module, child_name): if not hasattr(parent_module, child_name):
setattr(module, child_name, child_module) setattr(parent_module, child_name, modules[module_name])
modules[module_name] = module
# Keep track of the child module while moving up the tree.
child_module, child_name = module, module_name.rpartition(".")[-1]
module_parts.pop(-1) module_parts.pop(-1)
module_name = ".".join(module_parts) module_name = ".".join(module_parts)