Skip to content

Commit 1944dc0

Browse files
[7.4.x] Fix --import-mode=importlib when root contains __init__.py file (#11426)
Co-authored-by: Bruno Oliveira <[email protected]>
1 parent 946634c commit 1944dc0

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

src/_pytest/pathlib.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -623,8 +623,9 @@ def module_name_from_path(path: Path, root: Path) -> str:
623623
# Use the parts for the relative path to the root path.
624624
path_parts = relative_path.parts
625625

626-
# Module name for packages do not contain the __init__ file.
627-
if path_parts[-1] == "__init__":
626+
# Module name for packages do not contain the __init__ file, unless
627+
# the `__init__.py` file is at the root.
628+
if len(path_parts) >= 2 and path_parts[-1] == "__init__":
628629
path_parts = path_parts[:-1]
629630

630631
return ".".join(path_parts)

testing/test_pathlib.py

+21
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
from _pytest.pathlib import safe_exists
2929
from _pytest.pathlib import symlink_or_skip
3030
from _pytest.pathlib import visit
31+
from _pytest.pytester import Pytester
3132
from _pytest.tmpdir import TempPathFactory
3233

3334

@@ -592,6 +593,10 @@ def test_module_name_from_path(self, tmp_path: Path) -> None:
592593
result = module_name_from_path(tmp_path / "src/app/__init__.py", tmp_path)
593594
assert result == "src.app"
594595

596+
# Unless __init__.py file is at the root, in which case we cannot have an empty module name.
597+
result = module_name_from_path(tmp_path / "__init__.py", tmp_path)
598+
assert result == "__init__"
599+
595600
def test_insert_missing_modules(
596601
self, monkeypatch: MonkeyPatch, tmp_path: Path
597602
) -> None:
@@ -663,6 +668,22 @@ def __init__(self) -> None:
663668
mod = import_path(init, root=tmp_path, mode=ImportMode.importlib)
664669
assert len(mod.instance.INSTANCES) == 1
665670

671+
def test_importlib_root_is_package(self, pytester: Pytester) -> None:
672+
"""
673+
Regression for importing a `__init__`.py file that is at the root
674+
(#11417).
675+
"""
676+
pytester.makepyfile(__init__="")
677+
pytester.makepyfile(
678+
"""
679+
def test_my_test():
680+
assert True
681+
"""
682+
)
683+
684+
result = pytester.runpytest("--import-mode=importlib")
685+
result.stdout.fnmatch_lines("* 1 passed *")
686+
666687

667688
def test_safe_exists(tmp_path: Path) -> None:
668689
d = tmp_path.joinpath("some_dir")

0 commit comments

Comments
 (0)