Skip to content

Commit 6fb474a

Browse files
authored
Refactor insert_missing_modules function (#12210)
Makes the logic more straightforward IMO.
1 parent ff806b2 commit 6fb474a

File tree

1 file changed

+22
-25
lines changed

1 file changed

+22
-25
lines changed

src/_pytest/pathlib.py

Lines changed: 22 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -737,34 +737,31 @@ def insert_missing_modules(modules: Dict[str, ModuleType], module_name: str) ->
737737
otherwise "src.tests.test_foo" is not importable by ``__import__``.
738738
"""
739739
module_parts = module_name.split(".")
740-
child_module: Union[ModuleType, None] = None
741-
module: Union[ModuleType, None] = None
742-
child_name: str = ""
743740
while module_name:
744-
if module_name not in modules:
745-
try:
746-
# If sys.meta_path is empty, calling import_module will issue
747-
# a warning and raise ModuleNotFoundError. To avoid the
748-
# warning, we check sys.meta_path explicitly and raise the error
749-
# ourselves to fall back to creating a dummy module.
750-
if not sys.meta_path:
751-
raise ModuleNotFoundError
752-
module = importlib.import_module(module_name)
753-
except ModuleNotFoundError:
754-
module = ModuleType(
755-
module_name,
756-
doc="Empty module created by pytest's importmode=importlib.",
757-
)
758-
else:
759-
module = modules[module_name]
760-
if child_module:
741+
parent_module_name, _, child_name = module_name.rpartition(".")
742+
if parent_module_name:
743+
parent_module = modules.get(parent_module_name)
744+
if parent_module is None:
745+
try:
746+
# If sys.meta_path is empty, calling import_module will issue
747+
# a warning and raise ModuleNotFoundError. To avoid the
748+
# warning, we check sys.meta_path explicitly and raise the error
749+
# ourselves to fall back to creating a dummy module.
750+
if not sys.meta_path:
751+
raise ModuleNotFoundError
752+
parent_module = importlib.import_module(parent_module_name)
753+
except ModuleNotFoundError:
754+
parent_module = ModuleType(
755+
module_name,
756+
doc="Empty module created by pytest's importmode=importlib.",
757+
)
758+
modules[parent_module_name] = parent_module
759+
761760
# Add child attribute to the parent that can reference the child
762761
# modules.
763-
if not hasattr(module, child_name):
764-
setattr(module, child_name, child_module)
765-
modules[module_name] = module
766-
# Keep track of the child module while moving up the tree.
767-
child_module, child_name = module, module_name.rpartition(".")[-1]
762+
if not hasattr(parent_module, child_name):
763+
setattr(parent_module, child_name, modules[module_name])
764+
768765
module_parts.pop(-1)
769766
module_name = ".".join(module_parts)
770767

0 commit comments

Comments
 (0)