@@ -136,6 +136,23 @@ def get_scope_package(
136136 return node .session
137137
138138
139+ def fail_definition_scope_unavailable (nodeid : str , what : str ) -> NoReturn :
140+ """Fail because the ``"definition"`` scope was used where no
141+ :class:`~_pytest.nodes.ItemDefinition` node exists to anchor it on.
142+
143+ Unlike the other scopes, ``"definition"`` needs the test definition to be a
144+ node of the collection tree; there is nothing to fall back to that would
145+ preserve its meaning of "shared by all invocations of one definition".
146+ """
147+ fail (
148+ f"ScopeUnavailable: { what } needs the 'definition' scope, but { nodeid } "
149+ f"has no definition node in the collection tree.\n "
150+ f"For Python tests, set the collect_function_definition ini option to "
151+ f"'pedantic' to make function definitions part of the tree." ,
152+ pytrace = False ,
153+ )
154+
155+
139156def is_visibility_more_specific (
140157 candidate : FixtureDef [Any ], other : FixtureDef [Any ]
141158) -> bool :
@@ -174,6 +191,9 @@ def get_scope_node(node: nodes.Node, scope: Scope) -> nodes.Node | None:
174191 # Type ignored because this is actually safe, see:
175192 # https://github.com/python/mypy/issues/4717
176193 return node .getparent (nodes .Item ) # type: ignore[type-abstract]
194+ elif scope is Scope .Definition :
195+ # Type ignored for the same reason as Scope.Function above.
196+ return node .getparent (nodes .ItemDefinition ) # type: ignore[type-abstract]
177197 elif scope is Scope .Class :
178198 return node .getparent (_pytest .python .Class )
179199 elif scope is Scope .Module :
@@ -277,6 +297,9 @@ class ParamArgKey:
277297 scoped_item_path : Path | None
278298 #: For Class scope, the class where the item is defined.
279299 item_cls : type | None
300+ #: For Definition scope, the nodeid of the definition the item was
301+ #: generated from.
302+ scoped_definition_id : str | None = None
280303
281304
282305_V = TypeVar ("_V" )
@@ -293,6 +316,7 @@ def get_param_argkeys(item: nodes.Item, scope: Scope) -> Iterator[ParamArgKey]:
293316 return
294317
295318 item_cls = None
319+ scoped_definition_id = None
296320 if scope is Scope .Session :
297321 scoped_item_path = None
298322 elif scope is Scope .Package :
@@ -303,14 +327,26 @@ def get_param_argkeys(item: nodes.Item, scope: Scope) -> Iterator[ParamArgKey]:
303327 elif scope is Scope .Class :
304328 scoped_item_path = item .path
305329 item_cls = item .cls # type: ignore[attr-defined]
330+ elif scope is Scope .Definition :
331+ scoped_item_path = item .path
306332 else :
307333 assert_never (scope )
308334
309335 for argname , param in callspec .params .items ():
310336 if callspec ._arg2scope [argname ] != scope :
311337 continue
338+ if scope is Scope .Definition and scoped_definition_id is None :
339+ # Resolved only once a definition-scoped param is actually found:
340+ # items without one need not have a definition node at all. A param
341+ # at this scope can only have been created while the definition was
342+ # a node, so the lookup cannot come up empty here.
343+ definition = get_scope_node (item , Scope .Definition )
344+ assert definition is not None
345+ scoped_definition_id = definition .nodeid
312346 param_key = ParamValueKey (param , callspec .indices [argname ])
313- yield ParamArgKey (argname , param_key , scoped_item_path , item_cls )
347+ yield ParamArgKey (
348+ argname , param_key , scoped_item_path , item_cls , scoped_definition_id
349+ )
314350
315351
316352def reorder_items (items : Sequence [nodes .Item ]) -> list [nodes .Item ]:
@@ -546,7 +582,8 @@ def _scope(self) -> Scope:
546582
547583 @property
548584 def scope (self ) -> ScopeName :
549- """Scope string, one of "function", "class", "module", "package", "session"."""
585+ """Scope string, one of "function", "definition", "class", "module",
586+ "package", "session"."""
550587 return self ._scope .value
551588
552589 @abc .abstractmethod
@@ -908,6 +945,10 @@ def __init__(
908945 if node is None and scope is Scope .Class :
909946 # Fallback to function item itself.
910947 node = self ._pyfuncitem
948+ if node is None and scope is Scope .Definition :
949+ fail_definition_scope_unavailable (
950+ self ._pyfuncitem .nodeid , f"fixture { fixturedef .argname !r} "
951+ )
911952 assert node , (
912953 f'Could not obtain a node for scope "{ scope } " for function { self ._pyfuncitem !r} '
913954 )
@@ -1193,7 +1234,8 @@ def __init__(
11931234
11941235 @property
11951236 def scope (self ) -> ScopeName :
1196- """Scope string, one of "function", "class", "module", "package", "session"."""
1237+ """Scope string, one of "function", "definition", "class", "module",
1238+ "package", "session"."""
11971239 return self ._scope .value
11981240
11991241 @property
@@ -1556,7 +1598,13 @@ def fixture(
15561598
15571599 :param scope:
15581600 The scope for which this fixture is shared; one of ``"function"``
1559- (default), ``"class"``, ``"module"``, ``"package"`` or ``"session"``.
1601+ (default), ``"definition"``, ``"class"``, ``"module"``, ``"package"``
1602+ or ``"session"``.
1603+
1604+ ``"definition"`` shares the fixture across all invocations generated
1605+ from one test definition, i.e. across the parameter sets of a
1606+ parametrized test. It requires the definition to be a node of the
1607+ collection tree, see :confval:`collect_function_definition`.
15601608
15611609 This parameter may also be a callable which receives ``(fixture_name, config)``
15621610 as parameters, and must return a ``str`` with one of the values mentioned above.
@@ -1673,16 +1721,6 @@ def pytest_addoption(parser: Parser) -> None:
16731721 )
16741722
16751723
1676- def pytest_cmdline_main (config : Config ) -> int | ExitCode | None :
1677- if config .option .showfixtures :
1678- showfixtures (config )
1679- return 0
1680- if config .option .show_fixtures_per_test :
1681- show_fixtures_per_test (config )
1682- return 0
1683- return None
1684-
1685-
16861724def _resolve_args_directness (
16871725 argnames : Sequence [str ],
16881726 indirect : bool | Sequence [str ],
@@ -1722,6 +1760,16 @@ def _resolve_args_directness(
17221760 return arg_directness
17231761
17241762
1763+ def pytest_cmdline_main (config : Config ) -> int | ExitCode | None :
1764+ if config .option .showfixtures :
1765+ showfixtures (config )
1766+ return 0
1767+ if config .option .show_fixtures_per_test :
1768+ show_fixtures_per_test (config )
1769+ return 0
1770+ return None
1771+
1772+
17251773def _get_direct_parametrize_args (node : nodes .Node ) -> set [str ]:
17261774 """Return all direct parametrization arguments of a node, so we don't
17271775 mistake them for fixtures.
0 commit comments