Skip to content

Commit c6b5735

Browse files
committed
Use _import_module_using_spec to import parent modules
Seems this is the right thing to do, as we will then also consider the parent modules for rewriting.
1 parent 815f4e1 commit c6b5735

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

src/_pytest/pathlib.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -641,8 +641,24 @@ def _import_module_using_spec(
641641
parent_module_name, _, name = module_name.rpartition(".")
642642
parent_module: Optional[ModuleType] = sys.modules.get(parent_module_name)
643643
if parent_module is None and parent_module_name:
644-
with contextlib.suppress(ModuleNotFoundError, ImportWarning):
645-
parent_module = importlib.import_module(parent_module_name)
644+
# Find the directory of this module's parent.
645+
parent_dir = (
646+
module_path.parent.parent
647+
if module_path.name == "__init__.py"
648+
else module_path.parent
649+
)
650+
# Consider the parent module path as its __init__.py file, if it has one.
651+
parent_module_path = (
652+
parent_dir / "__init__.py"
653+
if (parent_dir / "__init__.py").is_file()
654+
else parent_dir
655+
)
656+
parent_module = _import_module_using_spec(
657+
parent_module_name,
658+
parent_module_path,
659+
parent_dir,
660+
insert_modules=insert_modules,
661+
)
646662

647663
# Find spec and import this module.
648664
mod = importlib.util.module_from_spec(spec)

0 commit comments

Comments
 (0)