Skip to content

Commit 437a510

Browse files
committed
Improve patch coverage: test Path 1 shadow branch, pragma on OSError
1 parent d3ca26b commit 437a510

2 files changed

Lines changed: 32 additions & 1 deletion

File tree

src/_pytest/pathlib.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -793,7 +793,7 @@ def _top_level_shadows_external(module_name: str, local_root: Path) -> bool:
793793
and child not in local_candidates
794794
):
795795
local_candidates.append(child)
796-
except OSError:
796+
except OSError: # pragma: no cover
797797
pass
798798
resolved_candidates = [c.resolve() for c in local_candidates if c.exists()]
799799

testing/test_pathlib.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1070,6 +1070,37 @@ def test_canonical():
10701070
# Must use the real dotted name, not a shadow-prefixed name.
10711071
assert mod.__name__ == "myapp.test_core"
10721072

1073+
def test_importlib_shadow_skips_standard_import_path(
1074+
self, pytester, ns_param: bool
1075+
):
1076+
"""When test/__init__.py exists AND the name shadows stdlib,
1077+
the standard-import path (Path 1) must be skipped so that
1078+
the fallback prefixes the name instead. This exercises the
1079+
shadow check inside the ``else`` block of
1080+
``resolve_pkg_root_and_module_name`` (#12303)."""
1081+
test_dir = pytester.path / "test"
1082+
test_dir.mkdir()
1083+
(test_dir / "__init__.py").touch()
1084+
file_path = test_dir / "test_demo.py"
1085+
file_path.write_text(
1086+
dedent(
1087+
"""
1088+
def test_passes():
1089+
pass
1090+
"""
1091+
),
1092+
encoding="utf-8",
1093+
)
1094+
1095+
mod = import_path(
1096+
file_path,
1097+
mode=ImportMode.importlib,
1098+
root=pytester.path,
1099+
consider_namespace_packages=ns_param,
1100+
)
1101+
# Must NOT be imported as "test.test_demo" (would shadow stdlib).
1102+
assert not mod.__name__.startswith("test.")
1103+
10731104
def create_installed_doctests_and_tests_dir(
10741105
self, path: Path, monkeypatch: MonkeyPatch
10751106
) -> tuple[Path, Path, Path]:

0 commit comments

Comments
 (0)