Skip to content

Commit c5a7ed8

Browse files
committedDec 12, 2024
fix: Resolved an ImportError crash when using --import-mode=importlib and encountering a directory containing a Python file with the same name as the directory.
1 parent 949c771 commit c5a7ed8

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed
 

Diff for: ‎src/_pytest/pathlib.py

+12-3
Original file line numberDiff line numberDiff line change
@@ -694,9 +694,18 @@ def _import_module_using_spec(
694694
# Checking with sys.meta_path first in case one of its hooks can import this module,
695695
# such as our own assertion-rewrite hook.
696696
for meta_importer in sys.meta_path:
697-
spec = meta_importer.find_spec(
698-
module_name, [str(module_location), str(module_path)]
699-
)
697+
module_name_of_meta = getattr(meta_importer.__class__, "__module__", "")
698+
if module_name_of_meta == "_pytest.assertion.rewrite" and module_path.is_file():
699+
# import modules in subdirectories by module_path
700+
# to ensure assertion rewrites are not missed (#12659)
701+
find_spec_path = [str(module_location), str(module_path)]
702+
else:
703+
find_spec_path = [
704+
str(module_location),
705+
]
706+
707+
spec = meta_importer.find_spec(module_name, find_spec_path)
708+
700709
if spec_matches_module_path(spec, module_path):
701710
break
702711
else:

Diff for: ‎testing/test_pathlib.py

+27
Original file line numberDiff line numberDiff line change
@@ -1498,6 +1498,33 @@ def test():
14981498
]
14991499
)
15001500

1501+
def test_ns_multiple_levels_import_error(
1502+
self,
1503+
tmp_path: Path,
1504+
pytester: Pytester,
1505+
) -> None:
1506+
# Trigger condition 1: ns and file with the same name
1507+
file = pytester.path / "cow/moo/moo.py"
1508+
file.parent.mkdir(parents=True)
1509+
file.write_text("data=123", encoding="utf-8")
1510+
1511+
# Trigger condition 2: tests are located in ns
1512+
tests = pytester.path / "cow/moo/test_moo.py"
1513+
1514+
tests.write_text(
1515+
dedent(
1516+
"""
1517+
from cow.moo.moo import data
1518+
1519+
def test_moo():
1520+
print(data)
1521+
"""
1522+
)
1523+
)
1524+
1525+
result = pytester.runpytest("--import-mode=importlib")
1526+
assert result.ret == ExitCode.OK
1527+
15011528
@pytest.mark.parametrize("import_mode", ["prepend", "append", "importlib"])
15021529
def test_incorrect_namespace_package(
15031530
self,

0 commit comments

Comments
 (0)