From 09643d9eba6fb1580b28172a832f0dbea099cbdf Mon Sep 17 00:00:00 2001 From: Bruno Oliveira Date: Sun, 31 Mar 2024 09:47:21 -0300 Subject: [PATCH] Drop explicit checks from is_namespace_package and add tests --- src/_pytest/pathlib.py | 10 ++++------ testing/test_pathlib.py | 13 +++++++++++++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/_pytest/pathlib.py b/src/_pytest/pathlib.py index 27504230e..054c21445 100644 --- a/src/_pytest/pathlib.py +++ b/src/_pytest/pathlib.py @@ -795,16 +795,14 @@ def resolve_pkg_root_and_module_name( def _is_namespace_package(module_path: Path) -> bool: module_name = module_path.name - # Empty module names break find_spec. + # Empty module names (such as Path.cwd()) might break meta_path hooks (like our own assertion rewriter). if not module_name: return False - # Modules starting with "." indicate relative imports and break find_spec, and we are only attempting - # to find top-level namespace packages anyway. - if module_name.startswith("."): + try: + spec = importlib.util.find_spec(module_name) + except ImportError: return False - - spec = importlib.util.find_spec(module_name) if spec is not None and spec.submodule_search_locations: # Found a spec, however make sure the module_path is in one of the search locations -- # this ensures common module name like "src" (which might be in sys.path under different locations) diff --git a/testing/test_pathlib.py b/testing/test_pathlib.py index 8a162d9ad..a4cb77932 100644 --- a/testing/test_pathlib.py +++ b/testing/test_pathlib.py @@ -17,6 +17,7 @@ from typing import Tuple import unittest.mock from _pytest.monkeypatch import MonkeyPatch +from _pytest.pathlib import _is_namespace_package from _pytest.pathlib import bestrelpath from _pytest.pathlib import commonpath from _pytest.pathlib import CouldNotResolvePathError @@ -1311,3 +1312,15 @@ class TestNamespacePackages: tmp_path / "src/dist1", "com.company.app.core.models", ) + + def test_is_namespace_package_bad_arguments(self, pytester: Pytester) -> None: + pytester.syspathinsert() + path = pytester.path / "bar.x" + path.mkdir() + assert _is_namespace_package(path) is False + + path = pytester.path / ".bar.x" + path.mkdir() + assert _is_namespace_package(path) is False + + assert _is_namespace_package(Path()) is False