Skip to content

Commit 80a0900

Browse files
committed
Refactor insert_missing_modules function
Makes the logic more straightforward IMO.
1 parent 089116b commit 80a0900

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
@@ -709,34 +709,31 @@ def insert_missing_modules(modules: Dict[str, ModuleType], module_name: str) ->
709709
otherwise "src.tests.test_foo" is not importable by ``__import__``.
710710
"""
711711
module_parts = module_name.split(".")
712-
child_module: Union[ModuleType, None] = None
713-
module: Union[ModuleType, None] = None
714-
child_name: str = ""
715712
while module_name:
716-
if module_name not in modules:
717-
try:
718-
# If sys.meta_path is empty, calling import_module will issue
719-
# a warning and raise ModuleNotFoundError. To avoid the
720-
# warning, we check sys.meta_path explicitly and raise the error
721-
# ourselves to fall back to creating a dummy module.
722-
if not sys.meta_path:
723-
raise ModuleNotFoundError
724-
module = importlib.import_module(module_name)
725-
except ModuleNotFoundError:
726-
module = ModuleType(
727-
module_name,
728-
doc="Empty module created by pytest's importmode=importlib.",
729-
)
730-
else:
731-
module = modules[module_name]
732-
if child_module:
713+
parent_module_name, _, child_name = module_name.rpartition(".")
714+
if parent_module_name:
715+
parent_module = modules.get(parent_module_name)
716+
if parent_module is None:
717+
try:
718+
# If sys.meta_path is empty, calling import_module will issue
719+
# a warning and raise ModuleNotFoundError. To avoid the
720+
# warning, we check sys.meta_path explicitly and raise the error
721+
# ourselves to fall back to creating a dummy module.
722+
if not sys.meta_path:
723+
raise ModuleNotFoundError
724+
parent_module = importlib.import_module(parent_module_name)
725+
except ModuleNotFoundError:
726+
parent_module = ModuleType(
727+
module_name,
728+
doc="Empty module created by pytest's importmode=importlib.",
729+
)
730+
modules[parent_module_name] = parent_module
731+
733732
# Add child attribute to the parent that can reference the child
734733
# modules.
735-
if not hasattr(module, child_name):
736-
setattr(module, child_name, child_module)
737-
modules[module_name] = module
738-
# Keep track of the child module while moving up the tree.
739-
child_module, child_name = module, module_name.rpartition(".")[-1]
734+
if not hasattr(parent_module, child_name):
735+
setattr(parent_module, child_name, modules[module_name])
736+
740737
module_parts.pop(-1)
741738
module_name = ".".join(module_parts)
742739

0 commit comments

Comments
 (0)