Skip to content

Commit 1e22e0f

Browse files
committed
Change compute_module_name to return Optional
This is better to enforce callers to check for it instead of ending up with '' and possibly breaking later.
1 parent 981e399 commit 1e22e0f

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

src/_pytest/pathlib.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -789,14 +789,15 @@ def resolve_pkg_root_and_module_name(
789789
start = pkg_root if pkg_root is not None else path.parent
790790
for candidate in (start, *start.parents):
791791
module_name = compute_module_name(candidate, path)
792-
if is_importable(module_name, path):
792+
if module_name and is_importable(module_name, path):
793793
# Point the pkg_root to the root of the namespace package.
794794
pkg_root = candidate
795795
break
796796

797797
if pkg_root is not None:
798798
module_name = compute_module_name(pkg_root, path)
799-
return pkg_root, module_name
799+
if module_name:
800+
return pkg_root, module_name
800801

801802
raise CouldNotResolvePathError(f"Could not resolve for {path}")
802803

@@ -827,16 +828,22 @@ def is_importable(module_name: str, module_path: Path) -> bool:
827828
return spec_matches_module_path(spec, module_path)
828829

829830

830-
def compute_module_name(root: Path, module_path: Path) -> str:
831+
def compute_module_name(root: Path, module_path: Path) -> Optional[str]:
831832
"""Compute a module name based on a path and a root anchor."""
832833
try:
833834
path_without_suffix = module_path.with_suffix("")
834835
except ValueError:
835836
# Empty paths (such as Path.cwd()) might break meta_path hooks (like our own assertion rewriter).
836-
return ""
837+
return None
837838

838-
names = list(path_without_suffix.relative_to(root).parts)
839-
if names and names[-1] == "__init__":
839+
try:
840+
relative = path_without_suffix.relative_to(root)
841+
except ValueError: # pragma: no cover
842+
return None
843+
names = list(relative.parts)
844+
if not names:
845+
return None
846+
if names[-1] == "__init__":
840847
names.pop()
841848
return ".".join(names)
842849

testing/test_pathlib.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1400,8 +1400,8 @@ def test_is_importable(pytester: Pytester) -> None:
14001400

14011401

14021402
def test_compute_module_name(tmp_path: Path) -> None:
1403-
assert compute_module_name(tmp_path, tmp_path) == ""
1404-
assert compute_module_name(Path(), Path()) == ""
1403+
assert compute_module_name(tmp_path, tmp_path) is None
1404+
assert compute_module_name(Path(), Path()) is None
14051405

14061406
assert compute_module_name(tmp_path, tmp_path / "mod.py") == "mod"
14071407
assert compute_module_name(tmp_path, tmp_path / "src/app/bar") == "src.app.bar"

0 commit comments

Comments
 (0)