From 90d15500630eb6ec4bce70e0ba193ed2c61e8a4f Mon Sep 17 00:00:00 2001 From: "Philipp A." Date: Tue, 6 Feb 2024 09:12:08 +0100 Subject: [PATCH] faster --- src/_pytest/pathlib.py | 31 +++++++++++++++---------------- testing/test_pathlib.py | 2 +- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/src/_pytest/pathlib.py b/src/_pytest/pathlib.py index c5f70a034..69fc41fec 100644 --- a/src/_pytest/pathlib.py +++ b/src/_pytest/pathlib.py @@ -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 resulting module name will be "src.tests.test_foo". """ + path = path.with_suffix("") candidates = ( - _module_name_from_path(path, dir) + _maybe_relative_parts(path, dir) for dir in itertools.chain([root], map(Path, sys.path)) ) - return ".".join(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 + path_parts = min(candidates, key=len) # type: ignore[arg-type] # Module name for packages do not contain the __init__ file, unless # the `__init__.py` file is at the root. if len(path_parts) >= 2 and path_parts[-1] == "__init__": 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: diff --git a/testing/test_pathlib.py b/testing/test_pathlib.py index 4f8b5b07b..1ff5e7f2f 100644 --- a/testing/test_pathlib.py +++ b/testing/test_pathlib.py @@ -669,7 +669,7 @@ class TestImportLibMode: mod = import_path(init, root=tmp_path, mode=ImportMode.importlib) 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 import the package using the canonical name