Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/13420.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added ``lru_cache`` to ``nodes._check_initialpaths_for_relpath``.
10 changes: 7 additions & 3 deletions src/_pytest/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import abc
from functools import cached_property
from functools import lru_cache
from inspect import signature
import os
import pathlib
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
18 changes: 4 additions & 14 deletions testing/test_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

from pathlib import Path
import re
from typing import cast
import warnings

from _pytest import nodes
Expand Down Expand Up @@ -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:
Expand Down
Loading