Drop explicit checks from is_namespace_package and add tests

This commit is contained in:
Bruno Oliveira 2024-03-31 09:47:21 -03:00
parent 7a25556ae5
commit 09643d9eba
2 changed files with 17 additions and 6 deletions

View File

@ -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)

View File

@ -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