diff --git a/changelog/13420.bugfix.rst b/changelog/13420.bugfix.rst new file mode 100644 index 00000000000..02f7372a759 --- /dev/null +++ b/changelog/13420.bugfix.rst @@ -0,0 +1 @@ +Added ``lru_cache`` to ``nodes._check_initialpaths_for_relpath``. diff --git a/src/_pytest/nodes.py b/src/_pytest/nodes.py index 51bc5174628..2b818ade252 100644 --- a/src/_pytest/nodes.py +++ b/src/_pytest/nodes.py @@ -3,6 +3,7 @@ import abc from functools import cached_property +from functools import lru_cache from inspect import signature import os import pathlib @@ -543,8 +544,11 @@ def _traceback_filter(self, excinfo: ExceptionInfo[BaseException]) -> Traceback: return excinfo.traceback -def _check_initialpaths_for_relpath(session: Session, path: Path) -> str | None: - for initial_path in session._initialpaths: +@lru_cache(maxsize=1000) +def _check_initialpaths_for_relpath( + initial_paths: frozenset[Path], path: Path +) -> str | None: + for initial_path in initial_paths: if commonpath(path, initial_path) == initial_path: rel = str(path.relative_to(initial_path)) return "" if rel == "." else rel @@ -594,7 +598,7 @@ def __init__( try: nodeid = str(self.path.relative_to(session.config.rootpath)) except ValueError: - nodeid = _check_initialpaths_for_relpath(session, path) + nodeid = _check_initialpaths_for_relpath(session._initialpaths, path) if nodeid and os.sep != SEP: nodeid = nodeid.replace(os.sep, SEP) diff --git a/testing/test_nodes.py b/testing/test_nodes.py index f039acf243b..f5f21e9775c 100644 --- a/testing/test_nodes.py +++ b/testing/test_nodes.py @@ -3,7 +3,6 @@ from pathlib import Path import re -from typing import cast import warnings from _pytest import nodes @@ -103,24 +102,15 @@ def test__check_initialpaths_for_relpath() -> None: """Ensure that it handles dirs, and does not always use dirname.""" cwd = Path.cwd() - class FakeSession1: - _initialpaths = frozenset({cwd}) + initial_paths = frozenset({cwd}) - session = cast(pytest.Session, FakeSession1) - - assert nodes._check_initialpaths_for_relpath(session, cwd) == "" + assert nodes._check_initialpaths_for_relpath(initial_paths, cwd) == "" sub = cwd / "file" - - class FakeSession2: - _initialpaths = frozenset({cwd}) - - session = cast(pytest.Session, FakeSession2) - - assert nodes._check_initialpaths_for_relpath(session, sub) == "file" + assert nodes._check_initialpaths_for_relpath(initial_paths, sub) == "file" outside = Path("/outside-this-does-not-exist") - assert nodes._check_initialpaths_for_relpath(session, outside) is None + assert nodes._check_initialpaths_for_relpath(initial_paths, outside) is None def test_failure_with_changed_cwd(pytester: Pytester) -> None: