Skip to content

Commit

Permalink
Add initial implementation for namespace packages
Browse files Browse the repository at this point in the history
Also needs more tests and docs
  • Loading branch information
nicoddemus committed Feb 24, 2024
1 parent f953bf4 commit 1232d19
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/_pytest/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -761,12 +761,13 @@ def resolve_pkg_root_and_module_name(
"""
pkg_path = resolve_package_path(path)
if pkg_path is not None:
pkg_root = pkg_path.parent
# pkg_root.parent does not contain a __init__.py file, as per resolve_package_path,
# but if it is reachable from sys.argv, it should be considered a namespace package.
# https://packaging.python.org/en/latest/guides/packaging-namespace-packages/
if consider_ns_packages and str(pkg_root.parent) in sys.path:
pkg_root = pkg_root.parent
pkg_root = pkg_path.parent
if consider_ns_packages:
for parent in pkg_path.parents:
if str(parent) in sys.path:
pkg_root = parent
break

Check warning on line 770 in src/_pytest/pathlib.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/pathlib.py#L769-L770

Added lines #L769 - L770 were not covered by tests
names = list(path.with_suffix("").relative_to(pkg_root).parts)
if names[-1] == "__init__":
names.pop()
Expand Down
23 changes: 23 additions & 0 deletions testing/test_pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,29 @@ def test_resolve_pkg_root_and_module_name(
"src.app.core.models",
)

def test_resolve_pkg_root_and_module_name_ns_multiple_levels(
self, tmp_path: Path, monkeypatch: MonkeyPatch
) -> None:
(tmp_path / "src/com/company/app/core").mkdir(parents=True)
(tmp_path / "src/com/company/app/__init__.py").touch()
(tmp_path / "src/com/company/app/core/__init__.py").touch()
models_py = tmp_path / "src/com/company/app/core/models.py"
models_py.touch()

monkeypatch.syspath_prepend(tmp_path / "src")

pkg_root, module_name = resolve_pkg_root_and_module_name(
models_py, consider_ns_packages=True
)
assert (pkg_root, module_name) == (
tmp_path / "src",
"com.company.app.core.models",
)

mod = import_path(models_py, mode="importlib", root=tmp_path)
assert mod.__name__ == "com.company.app.core.models"
assert mod.__file__ == str(models_py)

def test_insert_missing_modules(
self, monkeypatch: MonkeyPatch, tmp_path: Path
) -> None:
Expand Down

0 comments on commit 1232d19

Please sign in to comment.