This commit is contained in:
Philipp A. 2024-02-06 09:12:08 +01:00
parent e0402fa0d9
commit 90d1550063
2 changed files with 16 additions and 17 deletions

View File

@ -613,31 +613,30 @@ def module_name_from_path(path: Path, root: Path) -> str:
For example: path="projects/src/tests/test_foo.py" and root="/projects", the For example: path="projects/src/tests/test_foo.py" and root="/projects", the
resulting module name will be "src.tests.test_foo". resulting module name will be "src.tests.test_foo".
""" """
path = path.with_suffix("")
candidates = ( candidates = (
_module_name_from_path(path, dir) _maybe_relative_parts(path, dir)
for dir in itertools.chain([root], map(Path, sys.path)) for dir in itertools.chain([root], map(Path, sys.path))
) )
return ".".join(min(candidates, key=len)) # type: ignore[arg-type] path_parts = min(candidates, key=len) # type: ignore[arg-type]
def _module_name_from_path(path: Path, root: Path) -> "tuple[str, ...]":
path = path.with_suffix("")
try:
relative_path = path.relative_to(root)
except ValueError:
# If we can't get a relative path to root, use the full path, except
# for the first part ("d:\\" or "/" depending on the platform, for example).
path_parts = path.parts[1:]
else:
# Use the parts for the relative path to the root path.
path_parts = relative_path.parts
# Module name for packages do not contain the __init__ file, unless # Module name for packages do not contain the __init__ file, unless
# the `__init__.py` file is at the root. # the `__init__.py` file is at the root.
if len(path_parts) >= 2 and path_parts[-1] == "__init__": if len(path_parts) >= 2 and path_parts[-1] == "__init__":
path_parts = path_parts[:-1] path_parts = path_parts[:-1]
return path_parts return ".".join(path_parts)
def _maybe_relative_parts(path: Path, root: Path) -> "tuple[str, ...]":
try:
relative_path = path.relative_to(root)
except ValueError:
# If we can't get a relative path to root, use the full path, except
# for the first part ("d:\\" or "/" depending on the platform, for example).
return path.parts[1:]
# Use the parts for the relative path to the root path.
return relative_path.parts
def insert_missing_modules(modules: Dict[str, ModuleType], module_name: str) -> None: def insert_missing_modules(modules: Dict[str, ModuleType], module_name: str) -> None:

View File

@ -669,7 +669,7 @@ class TestImportLibMode:
mod = import_path(init, root=tmp_path, mode=ImportMode.importlib) mod = import_path(init, root=tmp_path, mode=ImportMode.importlib)
assert len(mod.instance.INSTANCES) == 1 assert len(mod.instance.INSTANCES) == 1
def test_importlib_doctest(self, monkeypatch: MonkeyPatch, tmp_path: Path): def test_importlib_doctest(self, monkeypatch: MonkeyPatch, tmp_path: Path) -> None:
""" """
Importing a package using --importmode=importlib should Importing a package using --importmode=importlib should
import the package using the canonical name import the package using the canonical name