Skip to content

Commit 46478fa

Browse files
RonnyPfannschmidtCursor AIclaude
committed
fix: assign conftest fixtures to Directory nodes during collection
Previously, conftest.py fixtures were registered with string-based nodeid scoping during plugin registration (before collection). This caused fixtures from nested conftest files to leak to sibling directories when testpaths pointed outside the rootdir. Now, conftest fixture registration is deferred until Directory collection. Each conftest's fixtures are parsed with the Directory node as their scope anchor, using node-based matching instead of string prefix matching. Above-rootdir conftests are handled by attaching to the Session node. Also introduces node-based autouse tracking (_node_autousenames) to replace the string-based _nodeid_autousenames dictionary. Fixes #14004. Co-authored-by: Cursor AI <[email protected]> Co-authored-by: Anthropic Claude Opus 4 <[email protected]>
1 parent 543b11f commit 46478fa

3 files changed

Lines changed: 288 additions & 41 deletions

File tree

‎changelog/14004.bugfix.rst‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Fixed conftest.py fixture scoping when :confval:`testpaths` points outside of the :ref:`rootdir <rootdir>`.
2+
3+
Previously, fixtures from nested conftest.py files would incorrectly leak to sibling directories
4+
when using a relative ``testpaths`` like ``../tests/sdk``.
5+
6+
Conftest fixtures are now parsed during :class:`Directory <pytest.Directory>` collection, using the ``Directory`` node for proper scoping.

‎src/_pytest/fixtures.py‎

Lines changed: 157 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
from _pytest.config import _PluggyPlugin
5454
from _pytest.config import Config
5555
from _pytest.config import ExitCode
56+
from _pytest.config import hookimpl
5657
from _pytest.config.argparsing import Parser
5758
from _pytest.deprecated import check_ispytest
5859
from _pytest.deprecated import CLASS_FIXTURE_INSTANCE_METHOD
@@ -69,6 +70,7 @@
6970
from _pytest.scope import HIGH_SCOPES
7071
from _pytest.scope import Scope
7172
from _pytest.scope import ScopeName
73+
from _pytest.warning_types import PytestRemovedIn10Warning
7274
from _pytest.warning_types import PytestWarning
7375

7476

@@ -80,6 +82,7 @@
8082
from _pytest.python import CallSpec2
8183
from _pytest.python import Function
8284
from _pytest.python import Metafunc
85+
from _pytest.reports import CollectReport
8386

8487

8588
# The value of the fixture -- return/yield of the fixture function (type variable).
@@ -1030,8 +1033,21 @@ def __init__(
10301033
_ispytest: bool = False,
10311034
# only used in a deprecationwarning msg, can be removed in pytest9
10321035
_autouse: bool = False,
1036+
node: nodes.Node | None = None,
10331037
) -> None:
10341038
check_ispytest(_ispytest)
1039+
# Emit deprecation warning if baseid string is used when node could be provided.
1040+
# baseid=None (global plugins) and baseid="" (synthetic fixtures) are fine.
1041+
if baseid and node is None:
1042+
warnings.warn(
1043+
"Passing baseid to FixtureDef is deprecated. "
1044+
"Pass node instead for fixture scoping.",
1045+
PytestRemovedIn10Warning,
1046+
stacklevel=2,
1047+
)
1048+
# The node where this fixture was defined, if available.
1049+
# Used for node-based matching which is more robust than string matching.
1050+
self.node: Final = node
10351051
# The "base" node ID for the fixture.
10361052
#
10371053
# This is a node ID prefix. A fixture is only available to a node (e.g.
@@ -1045,11 +1061,12 @@ def __init__(
10451061
# directory path relative to the rootdir.
10461062
#
10471063
# For other plugins, the baseid is the empty string (always matches).
1048-
self.baseid: Final = baseid or ""
1064+
# When node is available, baseid is derived from node.nodeid.
1065+
self.baseid: Final = node.nodeid if node is not None else (baseid or "")
10491066
# Whether the fixture was found from a node or a conftest in the
10501067
# collection tree. Will be false for fixtures defined in non-conftest
10511068
# plugins.
1052-
self.has_location: Final = baseid is not None
1069+
self.has_location: Final = node is not None or baseid is not None
10531070
# The fixture factory function.
10541071
self.func: Final = func
10551072
# The name by which the fixture may be requested.
@@ -1060,7 +1077,7 @@ def __init__(
10601077
scope = _eval_scope_callable(scope, argname, config)
10611078
if isinstance(scope, str):
10621079
scope = Scope.from_user(
1063-
scope, descr=f"Fixture '{func.__name__}'", where=baseid
1080+
scope, descr=f"Fixture '{func.__name__}'", where=self.baseid
10641081
)
10651082
self._scope: Final = scope
10661083
# If the fixture is directly parametrized, the parameter values.
@@ -1663,11 +1680,20 @@ def __init__(self, session: Session) -> None:
16631680
# explain.
16641681
self._arg2fixturedefs: Final[dict[str, list[FixtureDef[Any]]]] = {}
16651682
self._holderobjseen: Final[set[object]] = set()
1666-
# A mapping from a nodeid to a list of autouse fixtures it defines.
1667-
self._nodeid_autousenames: Final[dict[str, list[str]]] = {
1668-
"": self.config.getini("usefixtures"),
1683+
# A mapping from a node to a list of autouse fixture names it defines.
1684+
# The Session entry holds global usefixtures from config.
1685+
self._node_autousenames: Final[dict[nodes.Node, list[str]]] = {
1686+
session: list(self.config.getini("usefixtures")),
16691687
}
1688+
# Pending conftest modules waiting to be parsed when their Directory is collected.
1689+
# Maps directory path -> conftest plugin module.
1690+
self._pending_conftests: Final[dict[Path, object]] = {}
16701691
session.config.pluginmanager.register(self, "funcmanage")
1692+
# Flush initial conftests from directories above rootpath immediately.
1693+
# These will never get a Directory collector, so they need Session scope.
1694+
# This must happen here (not in pytest_make_collect_report) because
1695+
# collection may fail before Session collection starts (e.g. bad args).
1696+
self._flush_pending_conftests_to_session(session)
16711697

16721698
def getfixtureinfo(
16731699
self,
@@ -1708,31 +1734,62 @@ def getfixtureinfo(
17081734
def pytest_plugin_registered(self, plugin: _PluggyPlugin, plugin_name: str) -> None:
17091735
# Fixtures defined in conftest plugins are only visible to within the
17101736
# conftest's directory. This is unlike fixtures in non-conftest plugins
1711-
# which have global visibility. So for conftests, construct the base
1712-
# nodeid from the plugin name (which is the conftest path).
1737+
# which have global visibility. Conftest fixtures are deferred until
1738+
# their Directory is collected, so we can use the Directory's nodeid.
17131739
if plugin_name and plugin_name.endswith("conftest.py"):
17141740
# Note: we explicitly do *not* use `plugin.__file__` here -- The
17151741
# difference is that plugin_name has the correct capitalization on
17161742
# case-insensitive systems (Windows) and other normalization issues
17171743
# (issue #11816).
17181744
conftestpath = absolutepath(plugin_name)
1719-
try:
1720-
nodeid = str(conftestpath.parent.relative_to(self.config.rootpath))
1721-
except ValueError:
1722-
nodeid = ""
1723-
if nodeid == ".":
1724-
nodeid = ""
1725-
elif nodeid:
1726-
nodeid = nodes.norm_sep(nodeid)
1745+
conftest_dir = conftestpath.parent
1746+
# Store conftest for deferred parsing when its Directory is collected.
1747+
self._pending_conftests[conftest_dir] = plugin
17271748
else:
1728-
nodeid = None
1749+
# Non-conftest plugins have global visibility (nodeid=None).
1750+
self.parsefactories(plugin, None)
1751+
1752+
@hookimpl(wrapper=True)
1753+
def pytest_make_collect_report(
1754+
self, collector: nodes.Collector
1755+
) -> Generator[None, CollectReport, CollectReport]:
1756+
result = yield
1757+
if isinstance(collector, nodes.Directory):
1758+
plugin = self._pending_conftests.pop(collector.path, None)
1759+
if plugin is not None:
1760+
self.parsefactories(holder=plugin, node=collector)
1761+
return result
17291762

1730-
self.parsefactories(plugin, nodeid)
1763+
def _flush_pending_conftests_to_session(self, session: Session) -> None:
1764+
"""Assign Session scope to initial conftests whose directories won't
1765+
be collected as Directory nodes (e.g. ancestors above rootdir)."""
1766+
rootpath = session.config.rootpath
1767+
orphaned: list[tuple[Path, object]] = []
1768+
for conftest_dir, plugin in list(self._pending_conftests.items()):
1769+
# If the conftest dir is not under rootpath, it will never get
1770+
# a Directory collector — assign it to Session now.
1771+
try:
1772+
conftest_dir.relative_to(rootpath)
1773+
except ValueError:
1774+
orphaned.append((conftest_dir, plugin))
1775+
for conftest_dir, plugin in orphaned:
1776+
del self._pending_conftests[conftest_dir]
1777+
self.parsefactories(holder=plugin, node=session)
1778+
1779+
def pytest_collection_finish(self) -> None:
1780+
"""Clean up any conftests that were never collected by a Directory.
1781+
1782+
After __init__ flushes above-rootdir conftests and collection pops
1783+
under-rootdir ones, remaining entries mean collection was interrupted
1784+
(e.g. UsageError for a bad path). These conftests' fixtures aren't
1785+
needed since their directories' tests weren't collected either.
1786+
"""
1787+
self._pending_conftests.clear()
17311788

17321789
def _getautousenames(self, node: nodes.Node) -> Iterator[str]:
17331790
"""Return the names of autouse fixtures applicable to node."""
17341791
for parentnode in node.listchain():
1735-
basenames = self._nodeid_autousenames.get(parentnode.nodeid)
1792+
basenames = self._node_autousenames.get(parentnode)
17361793
if basenames:
17371794
yield from basenames
17381795

@@ -1835,11 +1892,12 @@ def _register_fixture(
18351892
*,
18361893
name: str,
18371894
func: _FixtureFunc[object],
1838-
nodeid: str | None,
1895+
nodeid: str | None = None,
18391896
scope: Scope | ScopeName | Callable[[str, Config], ScopeName] = "function",
18401897
params: Sequence[object] | None = None,
18411898
ids: tuple[object | None, ...] | Callable[[Any], object | None] | None = None,
18421899
autouse: bool = False,
1900+
node: nodes.Node | None = None,
18431901
) -> None:
18441902
"""Register a fixture
18451903
@@ -1848,10 +1906,12 @@ def _register_fixture(
18481906
:param func:
18491907
The fixture's implementation function.
18501908
:param nodeid:
1851-
The visibility of the fixture. The fixture will be available to the
1852-
node with this nodeid and its children in the collection tree.
1853-
None means that the fixture is visible to the entire collection tree,
1854-
e.g. a fixture defined for general use in a plugin.
1909+
The visibility of the fixture (deprecated, use node instead).
1910+
The fixture will be available to the node with this nodeid and
1911+
its children in the collection tree. None means global visibility.
1912+
:param node:
1913+
The node where the fixture is defined (preferred over nodeid).
1914+
When provided, enables node-based matching which is more robust.
18551915
:param scope:
18561916
The fixture's scope.
18571917
:param params:
@@ -1861,16 +1921,26 @@ def _register_fixture(
18611921
:param autouse:
18621922
Whether this is an autouse fixture.
18631923
"""
1924+
# Emit deprecation warning if nodeid string is used when node could be provided.
1925+
# nodeid=None (global plugins) is fine.
1926+
if nodeid and node is None:
1927+
warnings.warn(
1928+
"Passing nodeid to _register_fixture is deprecated. "
1929+
"Pass node instead for fixture scoping.",
1930+
PytestRemovedIn10Warning,
1931+
stacklevel=2,
1932+
)
18641933
fixture_def = FixtureDef(
18651934
config=self.config,
1866-
baseid=nodeid,
1935+
baseid=nodeid if node is None else None,
18671936
argname=name,
18681937
func=func,
18691938
scope=scope,
18701939
params=params,
18711940
ids=ids,
18721941
_ispytest=True,
18731942
_autouse=autouse,
1943+
node=node,
18741944
)
18751945

18761946
faclist = self._arg2fixturedefs.setdefault(name, [])
@@ -1884,7 +1954,11 @@ def _register_fixture(
18841954
i = len([f for f in faclist if not f.has_location])
18851955
faclist.insert(i, fixture_def)
18861956
if autouse:
1887-
self._nodeid_autousenames.setdefault(nodeid or "", []).append(name)
1957+
if node is not None:
1958+
self._node_autousenames.setdefault(node, []).append(name)
1959+
else:
1960+
# Global plugin autouse fixtures go under Session.
1961+
self._node_autousenames.setdefault(self.session, []).append(name)
18881962

18891963
@overload
18901964
def parsefactories(
@@ -1901,32 +1975,65 @@ def parsefactories(
19011975
) -> None:
19021976
raise NotImplementedError()
19031977

1978+
@overload
19041979
def parsefactories(
19051980
self,
1906-
node_or_obj: nodes.Node | object,
1981+
node_or_obj: None = ...,
1982+
nodeid: None = ...,
1983+
*,
1984+
holder: object,
1985+
node: nodes.Node,
1986+
) -> None:
1987+
raise NotImplementedError()
1988+
1989+
def parsefactories(
1990+
self,
1991+
node_or_obj: nodes.Node | object | None = None,
19071992
nodeid: str | NotSetType | None = NOTSET,
1993+
*,
1994+
holder: object | None = None,
1995+
node: nodes.Node | None = None,
19081996
) -> None:
19091997
"""Collect fixtures from a collection node or object.
19101998
19111999
Found fixtures are parsed into `FixtureDef`s and saved.
19122000
1913-
If `node_or_object` is a collection node (with an underlying Python
1914-
object), the node's object is traversed and the node's nodeid is used to
1915-
determine the fixtures' visibility. `nodeid` must not be specified in
1916-
this case.
2001+
The preferred API uses keyword-only arguments:
2002+
- ``holder``: The object to scan for fixtures.
2003+
- ``node``: The node determining fixture visibility scope.
19172004
1918-
If `node_or_object` is an object (e.g. a plugin), the object is
1919-
traversed and the given `nodeid` is used to determine the fixtures'
1920-
visibility. `nodeid` must be specified in this case; None and "" mean
1921-
total visibility.
2005+
Legacy positional API (translated internally):
2006+
- ``parsefactories(node)``: Uses node.obj as holder, node for scope.
2007+
- ``parsefactories(obj, nodeid)``: Uses obj as holder, nodeid string for scope.
19222008
"""
1923-
if nodeid is not NOTSET:
2009+
# Translate legacy API to holder/node sources of truth
2010+
# Either effective_node or effective_nodeid will be set, not both
2011+
effective_node: nodes.Node | None = None
2012+
effective_nodeid: str | None = None
2013+
2014+
if holder is not None:
2015+
# New API: holder and node explicitly provided
2016+
holderobj = holder
2017+
effective_node = node
2018+
elif node_or_obj is None:
2019+
raise TypeError("parsefactories() requires holder or node_or_obj")
2020+
elif nodeid is not NOTSET:
2021+
# Legacy: parsefactories(obj, nodeid) - string-based scoping only
2022+
# Only warn if a non-None nodeid string is passed (None means global plugin)
2023+
if nodeid is not None:
2024+
warnings.warn(
2025+
"Passing nodeid string to parsefactories is deprecated. "
2026+
"Use parsefactories(holder=obj, node=node) instead.",
2027+
PytestRemovedIn10Warning,
2028+
stacklevel=2,
2029+
)
19242030
holderobj = node_or_obj
2031+
effective_nodeid = nodeid
19252032
else:
2033+
# Legacy: parsefactories(node) - node has .obj attribute
19262034
assert isinstance(node_or_obj, nodes.Node)
19272035
holderobj = cast(object, node_or_obj.obj) # type: ignore[attr-defined]
1928-
assert isinstance(node_or_obj.nodeid, str)
1929-
nodeid = node_or_obj.nodeid
2036+
effective_node = node_or_obj
19302037
if holderobj in self._holderobjseen:
19312038
return
19322039

@@ -1959,12 +2066,13 @@ def parsefactories(
19592066

19602067
self._register_fixture(
19612068
name=fixture_name,
1962-
nodeid=nodeid,
19632069
func=func,
19642070
scope=marker.scope,
19652071
params=marker.params,
19662072
ids=marker.ids,
19672073
autouse=marker.autouse,
2074+
node=effective_node,
2075+
nodeid=effective_nodeid,
19682076
)
19692077

19702078
def getfixturedefs(
@@ -1990,9 +2098,17 @@ def getfixturedefs(
19902098
def _matchfactories(
19912099
self, fixturedefs: Iterable[FixtureDef[Any]], node: nodes.Node
19922100
) -> Iterator[FixtureDef[Any]]:
1993-
parentnodeids = {n.nodeid for n in node.iter_parents()}
2101+
# Collect parent nodes and their IDs for matching
2102+
parent_nodes = set(node.iter_parents())
2103+
parentnodeids = {n.nodeid for n in parent_nodes}
2104+
19942105
for fixturedef in fixturedefs:
1995-
if fixturedef.baseid in parentnodeids:
2106+
if fixturedef.node is not None:
2107+
# Node-based matching: check if fixture's node is a parent
2108+
if fixturedef.node in parent_nodes:
2109+
yield fixturedef
2110+
elif fixturedef.baseid in parentnodeids:
2111+
# Fallback to string-based matching for legacy/plugins
19962112
yield fixturedef
19972113

19982114

0 commit comments

Comments
 (0)