Debian Codegraph @

src/_pytest/fixtures.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 import abc
5 from collections import defaultdict
6 from collections import deque
7 from collections import OrderedDict
8 from collections.abc import Callable
9 from collections.abc import Generator
10 from collections.abc import Iterable
11 from collections.abc import Iterator
12 from collections.abc import Mapping
13 from collections.abc import MutableMapping
14 from collections.abc import Sequence
15 from collections.abc import Set as AbstractSet
16 import dataclasses
17 import functools
18 import inspect
19 import os
20 from pathlib import Path
21 import sys
22 import types
23 from typing import Any
24 from typing import cast
25 from typing import Final
26 from typing import final
27 from typing import Generic
28 from typing import Literal
29 from typing import NoReturn
30 from typing import overload
31 from typing import TYPE_CHECKING
32 from typing import TypeVar
33 import warnings
34
35 import _pytest
36 from _pytest import nodes
37 from _pytest._code import getfslineno
38 from _pytest._code import Source
39 from _pytest._code.code import ExceptionInfoFormatter
40 from _pytest._code.code import TerminalRepr
41 from _pytest._io import TerminalWriter
42 from _pytest.compat import assert_never
43 from _pytest.compat import deprecated
44 from _pytest.compat import get_real_func
45 from _pytest.compat import getfuncargnames
46 from _pytest.compat import getimfunc
47 from _pytest.compat import getlocation
48 from _pytest.compat import NOTSET
49 from _pytest.compat import NotSetType
50 from _pytest.compat import safe_getattr
51 from _pytest.compat import safe_isclass
52 from _pytest.compat import signature
53 from _pytest.config import _PluggyPlugin
54 from _pytest.config import Config
55 from _pytest.config import ExitCode
56 from _pytest.config import hookimpl
57 from _pytest.config.argparsing import Parser
58 from _pytest.deprecated import check_ispytest
59 from _pytest.deprecated import CLASS_FIXTURE_INSTANCE_METHOD
60 from _pytest.deprecated import FIXTURE_BASEID_DEPRECATED
61 from _pytest.deprecated import FIXTURE_GETFIXTUREVALUE_DURING_TEARDOWN
62 from _pytest.deprecated import FIXTURE_NODEID_DEPRECATED
63 from _pytest.deprecated import FIXTUREDEF_HAS_LOCATION_DEPRECATED
64 from _pytest.deprecated import PARSEFACTORIES_NODEID_DEPRECATED
65 from _pytest.deprecated import YIELD_FIXTURE
66 from _pytest.main import Session
67 from _pytest.mark import Mark
68 from _pytest.mark import ParameterSet
69 from _pytest.mark.structures import MarkDecorator
70 from _pytest.outcomes import fail
71 from _pytest.outcomes import skip
72 from _pytest.outcomes import TEST_OUTCOME
73 from _pytest.pathlib import absolutepath
74 from _pytest.pathlib import bestrelpath
75 from _pytest.scope import HIGH_SCOPES
76 from _pytest.scope import Scope
77 from _pytest.scope import ScopeName
78 from _pytest.warning_types import PytestWarning
79
80
81 if sys.version_info < (3, 11):
82 from exceptiongroup import BaseExceptionGroup
83
84
85 if TYPE_CHECKING:
86 from _pytest.python import CallSpec2
87 from _pytest.python import Function
88 from _pytest.python import Metafunc
89 from _pytest.reports import CollectReport
90
91
92 # The value of the fixture -- return/yield of the fixture function (type variable).
93 FixtureValue = TypeVar("FixtureValue", covariant=True)
94 # The type of the fixture function (type alias).
95 FixtureFunction = Callable[..., object]
96 # The type of a fixture function (type alias generic in fixture value).
97 _FixtureFunc = Callable[..., FixtureValue] | Callable[..., Generator[FixtureValue]]
98 # The type of FixtureDef.cached_result (type alias generic in fixture value).
99 _FixtureCachedResult = (
100 tuple[
101 # The result.
102 FixtureValue,
103 # Cache key.
104 object,
105 None,
106 ]
107 | tuple[
108 None,
109 # Cache key.
110 object,
111 # The exception and the original traceback.
112 tuple[BaseException, types.TracebackType | None],
113 ]
114 )
115
116
117 def pytest_sessionstart(session: Session) -> None:
118 session._fixturemanager = FixtureManager(session)
119
120
121 def get_scope_package(
122 node: nodes.Item,
123 fixturedef: FixtureDef[object],
124 ) -> nodes.Node | None:
125 from _pytest.python import Package
126
127 for parent in node.iter_parents():
128 if isinstance(parent, Package):
129 if fixturedef.node is not None:
130 if parent == fixturedef.node:
131 return parent
132 else:
133 if parent.nodeid == fixturedef.baseid:
134 return parent
135 return node.session
136
137
138 def is_visibility_more_specific(
139 candidate: FixtureDef[Any], other: FixtureDef[Any]
140 ) -> bool:
141 """Return whether the visibility of ``candidate`` is strictly more specific
142 than that of ``other``, i.e. ``candidate`` is defined on a strict descendant
143 in the collection tree of where ``other`` is defined."""
144 if candidate.node is None or other.node is None:
145 # Fallback for fixtures registered with a string nodeid (deprecated).
146 # In this case compare baseids, which are nodeid prefixes.
147 # This branch can be removed once baseid deprecation is done (pytest 10).
148 if candidate.baseid == other.baseid:
149 return False
150 if other.baseid == "":
151 return True
152 # `candidate.baseid` must continue with a node separator for it to be a
153 # true descendant.
154 return candidate.baseid.startswith(other.baseid) and candidate.baseid[
155 len(other.baseid)
156 ] in ("/", ":")
157
158 return (
159 candidate.node is not other.node and other.node in candidate.node.iter_parents()
160 )
161
162
163 def get_scope_node(node: nodes.Node, scope: Scope) -> nodes.Node | None:
164 """Get the closest parent node (including self) which matches the given
165 scope.
166
167 If there is no parent node for the scope (e.g. asking for class scope on a
168 Module, or on a Function when not defined in a class), returns None.
169 """
170 import _pytest.python
171
172 if scope is Scope.Function:
173 # Type ignored because this is actually safe, see:
174 # https://github.com/python/mypy/issues/4717
175 return node.getparent(nodes.Item) # type: ignore[type-abstract]
176 elif scope is Scope.Class:
177 return node.getparent(_pytest.python.Class)
178 elif scope is Scope.Module:
179 return node.getparent(_pytest.python.Module)
180 elif scope is Scope.Package:
181 return node.getparent(_pytest.python.Package)
182 elif scope is Scope.Session:
183 return node.getparent(_pytest.main.Session)
184 else:
185 assert_never(scope)
186
187
188 # TODO: Try to use FixtureFunctionDefinition instead of the marker
189 def getfixturemarker(obj: object) -> FixtureFunctionMarker | None:
190 """Return fixturemarker or None if it doesn't exist"""
191 if isinstance(obj, FixtureFunctionDefinition):
192 return obj._fixture_function_marker
193 return None
194
195
196 # Algorithm for sorting on a per-parametrized resource setup basis.
197 # It is called for Session scope first and performs sorting
198 # down to the lower scopes such as to minimize number of "high scope"
199 # setups and teardowns.
200
201
202 @dataclasses.dataclass(frozen=True)
203 class ParamArgKey:
204 """A key for a high-scoped parameter used by an item.
205
206 For use as a hashable key in `reorder_items`. The combination of fields
207 is meant to uniquely identify a particular "instance" of a param,
208 potentially shared by multiple items in a scope.
209 """
210
211 #: The param name.
212 argname: str
213 param_index: int
214 #: For scopes Package, Module, Class, the path to the file (directory in
215 #: Package's case) of the package/module/class where the item is defined.
216 scoped_item_path: Path | None
217 #: For Class scope, the class where the item is defined.
218 item_cls: type | None
219
220
221 _V = TypeVar("_V")
222 OrderedSet = dict[_V, None]
223
224
225 def get_param_argkeys(item: nodes.Item, scope: Scope) -> Iterator[ParamArgKey]:
226 """Return all ParamArgKeys for item matching the specified high scope."""
227 assert scope is not Scope.Function
228
229 try:
230 callspec: CallSpec2 = item.callspec # type: ignore[attr-defined]
231 except AttributeError:
232 return
233
234 item_cls = None
235 if scope is Scope.Session:
236 scoped_item_path = None
237 elif scope is Scope.Package:
238 # Package key = module's directory.
239 scoped_item_path = item.path.parent
240 elif scope is Scope.Module:
241 scoped_item_path = item.path
242 elif scope is Scope.Class:
243 scoped_item_path = item.path
244 item_cls = item.cls # type: ignore[attr-defined]
245 else:
246 assert_never(scope)
247
248 for argname in callspec.indices:
249 if callspec._arg2scope[argname] != scope:
250 continue
251 param_index = callspec.indices[argname]
252 yield ParamArgKey(argname, param_index, scoped_item_path, item_cls)
253
254
255 def reorder_items(items: Sequence[nodes.Item]) -> list[nodes.Item]:
256 argkeys_by_item: dict[Scope, dict[nodes.Item, OrderedSet[ParamArgKey]]] = {}
257 items_by_argkey: dict[Scope, dict[ParamArgKey, OrderedDict[nodes.Item, None]]] = {}
258 for scope in HIGH_SCOPES:
259 scoped_argkeys_by_item = argkeys_by_item[scope] = {}
260 scoped_items_by_argkey = items_by_argkey[scope] = defaultdict(OrderedDict)
261 for item in items:
262 argkeys = dict.fromkeys(get_param_argkeys(item, scope))
263 if argkeys:
264 scoped_argkeys_by_item[item] = argkeys
265 for argkey in argkeys:
266 scoped_items_by_argkey[argkey][item] = None
267
268 items_set = dict.fromkeys(items)
269 return list(
270 reorder_items_atscope(
271 items_set, argkeys_by_item, items_by_argkey, Scope.Session
272 )
273 )
274
275
276 def reorder_items_atscope(
277 items: OrderedSet[nodes.Item],
278 argkeys_by_item: Mapping[Scope, Mapping[nodes.Item, OrderedSet[ParamArgKey]]],
279 items_by_argkey: Mapping[
280 Scope, Mapping[ParamArgKey, OrderedDict[nodes.Item, None]]
281 ],
282 scope: Scope,
283 ) -> OrderedSet[nodes.Item]:
284 if scope is Scope.Function or len(items) < 3:
285 return items
286
287 scoped_items_by_argkey = items_by_argkey[scope]
288 scoped_argkeys_by_item = argkeys_by_item[scope]
289
290 ignore: set[ParamArgKey] = set()
291 items_deque = deque(items)
292 items_done: OrderedSet[nodes.Item] = {}
293 while items_deque:
294 no_argkey_items: OrderedSet[nodes.Item] = {}
295 slicing_argkey = None
296 while items_deque:
297 item = items_deque.popleft()
298 if item in items_done or item in no_argkey_items:
299 continue
300 argkeys = dict.fromkeys(
301 k for k in scoped_argkeys_by_item.get(item, ()) if k not in ignore
302 )
303 if not argkeys:
304 no_argkey_items[item] = None
305 else:
306 slicing_argkey, _ = argkeys.popitem()
307 # We don't have to remove relevant items from later in the
308 # deque because they'll just be ignored.
309 matching_items = [
310 i for i in scoped_items_by_argkey[slicing_argkey] if i in items
311 ]
312 for i in reversed(matching_items):
313 items_deque.appendleft(i)
314 # Fix items_by_argkey order.
315 for other_scope in HIGH_SCOPES:
316 other_scoped_items_by_argkey = items_by_argkey[other_scope]
317 for argkey in argkeys_by_item[other_scope].get(i, ()):
318 argkey_dict = other_scoped_items_by_argkey[argkey]
319 if not hasattr(sys, "pypy_version_info"):
320 argkey_dict[i] = None
321 argkey_dict.move_to_end(i, last=False)
322 else:
323 # Work around a bug in PyPy:
324 # https://github.com/pypy/pypy/issues/5257
325 # https://github.com/pytest-dev/pytest/issues/13312
326 bkp = argkey_dict.copy()
327 argkey_dict.clear()
328 argkey_dict[i] = None
329 argkey_dict.update(bkp)
330 break
331 if no_argkey_items:
332 reordered_no_argkey_items = reorder_items_atscope(
333 no_argkey_items, argkeys_by_item, items_by_argkey, scope.next_lower()
334 )
335 items_done.update(reordered_no_argkey_items)
336 if slicing_argkey is not None:
337 ignore.add(slicing_argkey)
338 return items_done
339
340
341 def traverse_fixture_closure(
342 initialnames: Iterable[str],
343 *,
344 getfixturedefs: Callable[[str], Sequence[FixtureDef[Any]] | None],
345 ) -> Iterator[str]:
346 """Statically traverse the fixture dependency closure in DFS order starting
347 from initialnames, yielding all requested fixture names (argnames).
348
349 Each argname is only yielded once.
350 """
351 # Track the index for each fixture name in the simulated stack.
352 # Needed for handling override chains correctly, similar to
353 # FixtureRequest._get_active_fixturedef.
354 # Using negative indices: -1 is the most specific (last), -2 is second to
355 # last, etc.
356 current_indices: dict[str, int] = {}
357
358 def process_argname(argname: str) -> Iterator[str]:
359 index = current_indices.get(argname)
360
361 # Optimization: already processed this argname.
362 if index == -1:
363 return
364
365 # Only yield each argname once.
366 if index is None:
367 yield argname
368 current_indices[argname] = -1
369
370 fixturedefs = getfixturedefs(argname)
371 if not fixturedefs:
372 return
373
374 index = current_indices.get(argname, -1)
375 if -index > len(fixturedefs):
376 # Exhausted the override chain (will error during runtest).
377 return
378 fixturedef = fixturedefs[index]
379
380 current_indices[argname] = index - 1
381 for dep in fixturedef.argnames:
382 yield from process_argname(dep)
383 current_indices[argname] = index
384
385 for argname in initialnames:
386 yield from process_argname(argname)
387
388
389 @dataclasses.dataclass(frozen=True)
390 class FuncFixtureInfo:
391 """Fixture-related information for a fixture-requesting item (e.g. test
392 function).
393
394 This is used to examine the fixtures which an item requests statically
395 (known during collection). This includes autouse fixtures, fixtures
396 requested by the `usefixtures` marker, fixtures requested in the function
397 parameters, and the transitive closure of these.
398
399 An item may also request fixtures dynamically (using `request.getfixturevalue`);
400 these are not reflected here.
401 """
402
403 __slots__ = ("argnames", "initialnames", "name2fixturedefs", "names_closure")
404
405 # Fixture names that the item requests directly by function parameters.
406 argnames: tuple[str, ...]
407 # Fixture names that the item immediately requires. These include
408 # argnames + fixture names specified via usefixtures and via autouse=True in
409 # fixture definitions.
410 initialnames: tuple[str, ...]
411 # The transitive closure of the fixture names that the item requires.
412 # Note: can't include dynamic dependencies (`request.getfixturevalue` calls).
413 names_closure: list[str]
414 # A map from a fixture name in the transitive closure to the FixtureDefs
415 # matching the name which are applicable to this function.
416 # There may be multiple overriding fixtures with the same name. The
417 # sequence is ordered from furthest to closes to the function.
418 name2fixturedefs: dict[str, Sequence[FixtureDef[Any]]]
419
420 def prune_dependency_tree(self) -> None:
421 """Recompute names_closure from initialnames and name2fixturedefs.
422
423 Can only reduce names_closure, which means that the new closure will
424 always be a subset of the old one. The order is preserved.
425
426 This method is needed because direct parametrization may shadow some
427 of the fixtures that were included in the originally built dependency
428 tree. In this way the dependency tree can get pruned, and the closure
429 of argnames may get reduced.
430 """
431 closure = set(
432 traverse_fixture_closure(
433 self.initialnames,
434 getfixturedefs=self.name2fixturedefs.get,
435 )
436 )
437 self.names_closure[:] = (name for name in self.names_closure if name in closure)
438
439
440 class FixtureRequest(abc.ABC):
441 """The type of the ``request`` fixture.
442
443 A request object gives access to the requesting test context and has a
444 ``param`` attribute in case the fixture is parametrized.
445 """
446
447 def __init__(
448 self,
449 pyfuncitem: Function,
450 fixturename: str | None,
451 arg2fixturedefs: Mapping[str, Sequence[FixtureDef[Any]]],
452 fixture_defs: dict[str, FixtureDef[Any]],
453 *,
454 _ispytest: bool = False,
455 ) -> None:
456 check_ispytest(_ispytest)
457 #: Fixture for which this request is being performed.
458 self.fixturename: Final = fixturename
459 self._pyfuncitem: Final = pyfuncitem
460 # The FixtureDefs for each fixture name statically requested by this
461 # item (computed during collection). Dynamically requested fixtures
462 # (using `request.getfixturevalue("foo")`) are not included here.
463 self._arg2fixturedefs: Final = arg2fixturedefs
464 # The evaluated argnames so far, mapping to the FixtureDef they resolved
465 # to.
466 self._fixture_defs: Final = fixture_defs
467 # Notes on the type of `param`:
468 # -`request.param` is only defined in parametrized fixtures, and will raise
469 # AttributeError otherwise. Python typing has no notion of "undefined", so
470 # this cannot be reflected in the type.
471 # - Technically `param` is only (possibly) defined on SubRequest, not
472 # FixtureRequest, but the typing of that is still in flux so this cheats.
473 # - In the future we might consider using a generic for the param type, but
474 # for now just using Any.
475 self.param: Any
476
477 @property
478 def _fixturemanager(self) -> FixtureManager:
479 return self._pyfuncitem.session._fixturemanager
480
481 @property
482 @abc.abstractmethod
483 def _scope(self) -> Scope:
484 raise NotImplementedError()
485
486 @property
487 def scope(self) -> ScopeName:
488 """Scope string, one of "function", "class", "module", "package", "session"."""
489 return self._scope.value
490
491 @abc.abstractmethod
492 def _check_scope(
493 self,
494 requested_fixturedef: FixtureDef[object],
495 requested_scope: Scope,
496 ) -> None:
497 raise NotImplementedError()
498
499 @property
500 def fixturenames(self) -> list[str]:
501 """Names of all active fixtures in this request."""
502 result = list(self._pyfuncitem.fixturenames)
503 result.extend(set(self._fixture_defs).difference(result))
504 return result
505
506 @property
507 @abc.abstractmethod
508 def node(self):
509 """Underlying collection node (depends on current request scope)."""
510 raise NotImplementedError()
511
512 @property
513 def config(self) -> Config:
514 """The pytest config object associated with this request."""
515 return self._pyfuncitem.config
516
517 @property
518 def function(self):
519 """Test function object if the request has a per-function scope."""
520 if self.scope != "function":
521 raise AttributeError(
522 f"function not available in {self.scope}-scoped context"
523 )
524 return self._pyfuncitem.obj
525
526 @property
527 def cls(self):
528 """Class (can be None) where the test function was collected."""
529 if self.scope not in ("class", "function"):
530 raise AttributeError(f"cls not available in {self.scope}-scoped context")
531 clscol = self._pyfuncitem.getparent(_pytest.python.Class)
532 if clscol:
533 return clscol.obj
534
535 @property
536 def instance(self):
537 """Instance (can be None) on which test function was collected."""
538 if self.scope != "function":
539 return None
540 return getattr(self._pyfuncitem, "instance", None)
541
542 @property
543 def module(self):
544 """Python module object where the test function was collected."""
545 if self.scope not in ("function", "class", "module"):
546 raise AttributeError(f"module not available in {self.scope}-scoped context")
547 mod = self._pyfuncitem.getparent(_pytest.python.Module)
548 assert mod is not None
549 return mod.obj
550
551 @property
552 def path(self) -> Path:
553 """Path where the test function was collected."""
554 if self.scope not in ("function", "class", "module", "package"):
555 raise AttributeError(f"path not available in {self.scope}-scoped context")
556 return self._pyfuncitem.path
557
558 @property
559 def keywords(self) -> MutableMapping[str, Any]:
560 """Keywords/markers dictionary for the underlying node."""
561 node: nodes.Node = self.node
562 return node.keywords
563
564 @property
565 def session(self) -> Session:
566 """Pytest session object."""
567 return self._pyfuncitem.session
568
569 @abc.abstractmethod
570 def addfinalizer(self, finalizer: Callable[[], object]) -> None:
571 """Add finalizer/teardown function to be called without arguments after
572 the last test within the requesting test context finished execution."""
573 raise NotImplementedError()
574
575 def applymarker(self, marker: str | MarkDecorator) -> None:
576 """Apply a marker to a single test function invocation.
577
578 This method is useful if you don't want to have a keyword/marker
579 on all function invocations.
580
581 :param marker:
582 An object created by a call to ``pytest.mark.NAME(...)``.
583 """
584 self.node.add_marker(marker)
585
586 def raiseerror(self, msg: str | None) -> NoReturn:
587 """Raise a FixtureLookupError exception.
588
589 :param msg:
590 An optional custom error message.
591 """
592 raise FixtureLookupError(None, self, msg)
593
594 def _raise_teardown_lookup_error(self, argname: str) -> NoReturn:
595 msg = (
596 f'The fixture value for "{argname}" is not available during teardown '
597 "because it was not previously requested.\n"
598 "Only fixtures that were already active can be retrieved during teardown.\n"
599 "Request the fixture before teardown begins by declaring it in the fixture "
600 "signature or by calling request.getfixturevalue() before the fixture yields."
601 )
602 raise FixtureLookupError(argname, self, msg)
603
604 def getfixturevalue(self, argname: str) -> Any:
605 """Dynamically run a named fixture function.
606
607 Declaring fixtures via function argument is recommended where possible.
608 But if you can only decide whether to use another fixture at test
609 setup time, you may use this function to retrieve it inside a fixture
610 or test function body.
611
612 This method can be used during the test setup phase or the test run
613 phase. Avoid using it during the teardown phase.
614
615 .. versionchanged:: 9.1
616 Calling ``request.getfixturevalue()`` during teardown to request a
617 fixture that was not already requested
618 :ref:`is deprecated <dynamic-fixture-request-during-teardown>`.
619
620 :param argname:
621 The fixture name.
622 :raises pytest.FixtureLookupError:
623 If the given fixture could not be found.
624 """
625 # Note that in addition to the use case described in the docstring,
626 # getfixturevalue() is also called by pytest itself during item and fixture
627 # setup to evaluate the fixtures that are requested statically
628 # (using function parameters, autouse, etc).
629
630 fixturedef = self._get_active_fixturedef(argname)
631 assert fixturedef.cached_result is not None, (
632 f'The fixture value for "{argname}" is not available. '
633 "This can happen when the fixture has already been torn down."
634 )
635 return fixturedef.cached_result[0]
636
637 def _iter_chain(self) -> Iterator[SubRequest]:
638 """Yield all SubRequests in the chain, from self up.
639
640 Note: does *not* yield the TopRequest.
641 """
642 current = self
643 while isinstance(current, SubRequest):
644 yield current
645 current = current._parent_request
646
647 def _get_active_fixturedef(self, argname: str) -> FixtureDef[object]:
648 if argname == "request":
649 return RequestFixtureDef(self)
650
651 # If we already finished computing a fixture by this name in this item,
652 # return it.
653 fixturedef = self._fixture_defs.get(argname)
654 if fixturedef is not None:
655 self._check_scope(fixturedef, fixturedef._scope)
656 return fixturedef
657
658 # Find the appropriate fixturedef.
659 fixturedefs = self._arg2fixturedefs.get(argname, None)
660 if fixturedefs is None:
661 # We arrive here because of a dynamic call to
662 # getfixturevalue(argname) which was naturally
663 # not known at parsing/collection time.
664 fixturedefs = self._fixturemanager.getfixturedefs(argname, self._pyfuncitem)
665 # No fixtures defined with this name.
666 if fixturedefs is None:
667 raise FixtureLookupError(argname, self)
668 # The are no fixtures with this name applicable for the function.
669 if not fixturedefs:
670 raise FixtureLookupError(argname, self)
671
672 # A fixture may override another fixture with the same name, e.g. a
673 # fixture in a module can override a fixture in a conftest, a fixture in
674 # a class can override a fixture in the module, and so on.
675 # An overriding fixture can request its own name (possibly indirectly);
676 # in this case it gets the value of the fixture it overrides, one level
677 # up.
678 # Check how many `argname`s deep we are, and take the next one.
679 # `fixturedefs` is sorted from furthest to closest, so use negative
680 # indexing to go in reverse.
681 index = -1
682 for request in self._iter_chain():
683 if request.fixturename == argname:
684 index -= 1
685 # If already consumed all of the available levels, fail.
686 if -index > len(fixturedefs):
687 raise FixtureLookupError(argname, self)
688 fixturedef = fixturedefs[index]
689
690 # Prepare a SubRequest object for calling the fixture.
691 try:
692 callspec = self._pyfuncitem.callspec
693 except AttributeError:
694 callspec = None
695 if callspec is not None and argname in callspec.params:
696 param = callspec.params[argname]
697 param_index = callspec.indices[argname]
698 # The parametrize invocation scope overrides the fixture's scope.
699 scope = callspec._arg2scope[argname]
700 else:
701 param = NOTSET
702 param_index = 0
703 scope = fixturedef._scope
704 self._check_fixturedef_without_param(fixturedef)
705 # The parametrize invocation scope only controls caching behavior while
706 # allowing wider-scoped fixtures to keep depending on the parametrized
707 # fixture. Scope control is enforced for parametrized fixtures
708 # by recreating the whole fixture tree on parameter change.
709 # Hence `fixturedef._scope`, not `scope`.
710 self._check_scope(fixturedef, fixturedef._scope)
711 subrequest = SubRequest(
712 self, scope, param, param_index, fixturedef, _ispytest=True
713 )
714
715 if not self.session._setupstate.is_node_active(self.node):
716 # TODO(pytest10.1): Remove the `warn` and `if` and call
717 # _raise_teardown_lookup_error unconditionally.
718 warnings.warn(
719 FIXTURE_GETFIXTUREVALUE_DURING_TEARDOWN.format(argname=argname),
720 stacklevel=3,
721 )
722 if subrequest.node not in self.session._setupstate.stack:
723 self._raise_teardown_lookup_error(argname)
724
725 # Make sure the fixture value is cached, running it if it isn't
726 fixturedef.execute(request=subrequest)
727
728 self._fixture_defs[argname] = fixturedef
729 return fixturedef
730
731 def _check_fixturedef_without_param(self, fixturedef: FixtureDef[object]) -> None:
732 """Check that this request is allowed to execute this fixturedef without
733 a param."""
734 funcitem = self._pyfuncitem
735 has_params = fixturedef.params is not None
736 fixtures_not_supported = getattr(funcitem, "nofuncargs", False)
737 if has_params and fixtures_not_supported:
738 msg = (
739 f"{funcitem.name} does not support fixtures, maybe unittest.TestCase subclass?\n"
740 f"Node id: {funcitem.nodeid}\n"
741 f"Function type: {type(funcitem).__name__}"
742 )
743 fail(msg, pytrace=False)
744 if has_params:
745 frame = inspect.stack()[3]
746 frameinfo = inspect.getframeinfo(frame[0])
747 source_path = absolutepath(frameinfo.filename)
748 source_lineno = frameinfo.lineno
749 try:
750 source_path_str = str(source_path.relative_to(funcitem.config.rootpath))
751 except ValueError:
752 source_path_str = str(source_path)
753 location = getlocation(fixturedef.func, funcitem.config.rootpath)
754 msg = (
755 "The requested fixture has no parameter defined for test:\n"
756 f" {funcitem.nodeid}\n\n"
757 f"Requested fixture '{fixturedef.argname}' defined in:\n"
758 f"{location}\n\n"
759 f"Requested here:\n"
760 f"{source_path_str}:{source_lineno}"
761 )
762 fail(msg, pytrace=False)
763
764 def _get_fixturestack(self) -> list[FixtureDef[Any]]:
765 values = [request._fixturedef for request in self._iter_chain()]
766 values.reverse()
767 return values
768
769
770 @final
771 class TopRequest(FixtureRequest):
772 """The type of the ``request`` fixture in a test function."""
773
774 def __init__(self, pyfuncitem: Function, *, _ispytest: bool = False) -> None:
775 super().__init__(
776 fixturename=None,
777 pyfuncitem=pyfuncitem,
778 arg2fixturedefs=pyfuncitem._fixtureinfo.name2fixturedefs,
779 fixture_defs={},
780 _ispytest=_ispytest,
781 )
782
783 @property
784 def _scope(self) -> Scope:
785 return Scope.Function
786
787 def _check_scope(
788 self,
789 requested_fixturedef: FixtureDef[object],
790 requested_scope: Scope,
791 ) -> None:
792 # TopRequest always has function scope so always valid.
793 pass
794
795 @property
796 def node(self):
797 return self._pyfuncitem
798
799 def __repr__(self) -> str:
800 return f"<FixtureRequest for {self.node!r}>"
801
802 def _fillfixtures(self) -> None:
803 item = self._pyfuncitem
804 for argname in item.fixturenames:
805 if argname not in item.funcargs:
806 item.funcargs[argname] = self.getfixturevalue(argname)
807
808 def addfinalizer(self, finalizer: Callable[[], object]) -> None:
809 self.node.addfinalizer(finalizer)
810
811
812 @final
813 class SubRequest(FixtureRequest):
814 """The type of the ``request`` fixture in a fixture function requested
815 (transitively) by a test function."""
816
817 def __init__(
818 self,
819 request: FixtureRequest,
820 scope: Scope,
821 param: Any,
822 param_index: int,
823 fixturedef: FixtureDef[object],
824 *,
825 _ispytest: bool = False,
826 ) -> None:
827 super().__init__(
828 pyfuncitem=request._pyfuncitem,
829 fixturename=fixturedef.argname,
830 fixture_defs=request._fixture_defs,
831 arg2fixturedefs=request._arg2fixturedefs,
832 _ispytest=_ispytest,
833 )
834 self._parent_request: Final[FixtureRequest] = request
835 self._fixturedef: Final[FixtureDef[object]] = fixturedef
836 if param is not NOTSET:
837 self.param = param
838 self.param_index: Final = param_index
839 self._scope_field: Final = scope
840 if scope is Scope.Function:
841 # This might also be a non-function Item despite its attribute name.
842 node: nodes.Node | None = self._pyfuncitem
843 elif scope is Scope.Package:
844 node = get_scope_package(self._pyfuncitem, self._fixturedef)
845 else:
846 node = get_scope_node(self._pyfuncitem, scope)
847 if node is None and scope is Scope.Class:
848 # Fallback to function item itself.
849 node = self._pyfuncitem
850 assert node, (
851 f'Could not obtain a node for scope "{scope}" for function {self._pyfuncitem!r}'
852 )
853 self._node: Final = node
854
855 def __repr__(self) -> str:
856 return f"<SubRequest {self.fixturename!r} for {self._pyfuncitem!r}>"
857
858 @property
859 def _scope(self) -> Scope:
860 return self._scope_field
861
862 @property
863 def node(self):
864 return self._node
865
866 def _check_scope(
867 self,
868 requested_fixturedef: FixtureDef[object],
869 requested_scope: Scope,
870 ) -> None:
871 if self._scope > requested_scope:
872 # Try to report something helpful.
873 argname = requested_fixturedef.argname
874 fixture_stack = "\n".join(
875 self._format_fixturedef_line(fixturedef)
876 for fixturedef in self._get_fixturestack()
877 )
878 requested_fixture = self._format_fixturedef_line(requested_fixturedef)
879 fail(
880 f"ScopeMismatch: You tried to access the {requested_scope.value} scoped "
881 f"fixture {argname} with a {self._scope.value} scoped request object. "
882 f"Requesting fixture stack:\n{fixture_stack}\n"
883 f"Requested fixture:\n{requested_fixture}",
884 pytrace=False,
885 )
886
887 def _format_fixturedef_line(self, fixturedef: FixtureDef[object]) -> str:
888 factory = fixturedef.func
889 path, lineno = getfslineno(factory)
890 if isinstance(path, Path):
891 path = bestrelpath(self._pyfuncitem.session.path, path)
892 sig = signature(factory)
893 return f"{path}:{lineno + 1}: def {factory.__name__}{sig}"
894
895 def addfinalizer(self, finalizer: Callable[[], object]) -> None:
896 self._fixturedef.addfinalizer(finalizer)
897
898
899 @final
900 class FixtureLookupError(LookupError):
901 """Could not return a requested fixture (missing or invalid)."""
902
903 def __init__(
904 self, argname: str | None, request: FixtureRequest, msg: str | None = None
905 ) -> None:
906 self.argname = argname
907 self.request = request
908 self.fixturestack = request._get_fixturestack()
909 self.msg = msg
910
911 def formatrepr(self) -> FixtureLookupErrorRepr:
912 tblines: list[str] = []
913 addline = tblines.append
914 stack = [self.request._pyfuncitem.obj]
915 stack.extend(map(lambda x: x.func, self.fixturestack))
916 msg = self.msg
917 if msg is not None and len(stack) > 1:
918 # The last fixture raise an error, let's present
919 # it at the requesting side.
920 stack = stack[:-1]
921 for function in stack:
922 fspath, lineno = getfslineno(function)
923 try:
924 lines, _ = inspect.getsourcelines(get_real_func(function))
925 except (OSError, IndexError, TypeError):
926 error_msg = "file %s, line %s: source code not available"
927 addline(error_msg % (fspath, lineno + 1))
928 else:
929 addline(f"file {fspath}, line {lineno + 1}")
930 for i, line in enumerate(lines):
931 line = line.rstrip()
932 addline(" " + line)
933 if line.lstrip().startswith("def"):
934 break
935
936 if msg is None:
937 fm = self.request._fixturemanager
938 available = set()
939 parent = self.request._pyfuncitem.parent
940 assert parent is not None
941 for name, fixturedefs in fm._arg2fixturedefs.items():
942 faclist = list(fm._matchfactories(fixturedefs, parent))
943 if faclist:
944 available.add(name)
945 if self.argname in available:
946 msg = (
947 f" recursive dependency involving fixture '{self.argname}' detected"
948 )
949 else:
950 msg = f"fixture '{self.argname}' not found"
951 msg += "\n available fixtures: {}".format(", ".join(sorted(available)))
952 msg += "\n use 'pytest --fixtures [testpath]' for help on them."
953
954 return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname)
955
956
957 class FixtureLookupErrorRepr(TerminalRepr):
958 def __init__(
959 self,
960 filename: str | os.PathLike[str],
961 firstlineno: int,
962 tblines: Sequence[str],
963 errorstring: str,
964 argname: str | None,
965 ) -> None:
966 self.tblines = tblines
967 self.errorstring = errorstring
968 self.filename = filename
969 self.firstlineno = firstlineno
970 self.argname = argname
971
972 def toterminal(self, tw: TerminalWriter) -> None:
973 # tw.line("FixtureLookupError: %s" %(self.argname), red=True)
974 for tbline in self.tblines:
975 tw.line(tbline.rstrip())
976 lines = self.errorstring.split("\n")
977 if lines:
978 tw.line(
979 f"{ExceptionInfoFormatter.fail_marker} {lines[0].strip()}",
980 red=True,
981 )
982 for line in lines[1:]:
983 tw.line(
984 f"{ExceptionInfoFormatter.flow_marker} {line.strip()}",
985 red=True,
986 )
987 tw.line()
988 tw.line(f"{os.fspath(self.filename)}:{self.firstlineno + 1}")
989
990
991 def call_fixture_func(
992 fixturefunc: _FixtureFunc[FixtureValue], request: FixtureRequest, kwargs
993 ) -> FixtureValue:
994 if inspect.isgeneratorfunction(fixturefunc):
995 fixturefunc = cast(Callable[..., Generator[FixtureValue]], fixturefunc)
996 generator = fixturefunc(**kwargs)
997 try:
998 fixture_result = next(generator)
999 except StopIteration:
1000 raise ValueError(f"{request.fixturename} did not yield a value") from None
1001 finalizer = functools.partial(_teardown_yield_fixture, fixturefunc, generator)
1002 request.addfinalizer(finalizer)
1003 else:
1004 fixturefunc = cast(Callable[..., FixtureValue], fixturefunc)
1005 fixture_result = fixturefunc(**kwargs)
1006 return fixture_result
1007
1008
1009 def _teardown_yield_fixture(fixturefunc, it) -> None:
1010 """Execute the teardown of a fixture function by advancing the iterator
1011 after the yield and ensure the iteration ends (if not it means there is
1012 more than one yield in the function)."""
1013 try:
1014 next(it)
1015 except StopIteration:
1016 pass
1017 else:
1018 fs, lineno = getfslineno(fixturefunc)
1019 fail(
1020 f"fixture function has more than one 'yield':\n\n"
1021 f"{Source(fixturefunc).indent()}\n"
1022 f"{fs}:{lineno + 1}",
1023 pytrace=False,
1024 )
1025
1026
1027 def _eval_scope_callable(
1028 scope_callable: Callable[[str, Config], ScopeName],
1029 fixture_name: str,
1030 config: Config,
1031 ) -> ScopeName:
1032 try:
1033 # Type ignored because there is no typing mechanism to specify
1034 # keyword arguments, currently.
1035 result = scope_callable(fixture_name=fixture_name, config=config) # type: ignore[call-arg]
1036 except Exception as e:
1037 raise TypeError(
1038 f"Error evaluating {scope_callable} while defining fixture '{fixture_name}'.\n"
1039 "Expected a function with the signature (*, fixture_name, config)"
1040 ) from e
1041 if not isinstance(result, str):
1042 fail(
1043 f"Expected {scope_callable} to return a 'str' while defining fixture '{fixture_name}', but it returned:\n"
1044 f"{result!r}",
1045 pytrace=False,
1046 )
1047 return result
1048
1049
1050 class FixtureDef(Generic[FixtureValue]):
1051 """A container for a fixture definition.
1052
1053 Note: At this time, only explicitly documented fields and methods are
1054 considered public stable API.
1055 """
1056
1057 def __init__(
1058 self,
1059 config: Config,
1060 baseid: str | None | NotSetType,
1061 argname: str,
1062 func: _FixtureFunc[FixtureValue],
1063 scope: Scope | ScopeName | Callable[[str, Config], ScopeName] | None,
1064 params: Sequence[object] | None,
1065 ids: tuple[object | None, ...] | Callable[[Any], object | None] | None = None,
1066 *,
1067 node: nodes.Node | NotSetType = NOTSET,
1068 # only used in a deprecationwarning msg, can be removed in pytest9
1069 _autouse: bool = False,
1070 _ispytest: bool = False,
1071 ) -> None:
1072 check_ispytest(_ispytest)
1073 # Emit deprecation warning if deprecated baseid string is used.
1074 if node is NOTSET:
1075 warnings.warn(FIXTURE_BASEID_DEPRECATED, stacklevel=2)
1076 if baseid is NOTSET:
1077 baseid = None
1078 # The node where this fixture was defined, if available.
1079 # Used for node-based matching which is more robust than string matching.
1080 self.node: Final = node if node is not NOTSET else None
1081 # The "base" node ID for the fixture.
1082 #
1083 # This is a node ID prefix. A fixture is only available to a node (e.g.
1084 # a `Function` item) if the fixture's baseid is a nodeid of a parent of
1085 # node.
1086 #
1087 # For a fixture found in a Collector's object (e.g. a `Module`s module,
1088 # a `Class`'s class), the baseid is the Collector's nodeid.
1089 #
1090 # For a fixture found in a conftest plugin, the baseid is the conftest's
1091 # directory path relative to the rootdir.
1092 #
1093 # For other plugins, the baseid is the empty string (always matches).
1094 # When node is available, baseid is derived from node.nodeid.
1095 #
1096 # Deprecated: replaced by ``node``.
1097 self.baseid: Final = node.nodeid if node is not NOTSET else (baseid or "")
1098 # Whether the fixture was found from a node or a conftest in the
1099 # collection tree. Will be false for fixtures defined in non-conftest
1100 # plugins.
1101 #
1102 # Deprecated: kept only to back the deprecated ``has_location`` property.
1103 self._has_location: Final = node is not NOTSET or baseid is not None
1104 # The fixture factory function.
1105 self.func: Final = func
1106 # The name by which the fixture may be requested.
1107 self.argname: Final = argname
1108 if scope is None:
1109 scope = Scope.Function
1110 elif callable(scope):
1111 scope = _eval_scope_callable(scope, argname, config)
1112 if isinstance(scope, str):
1113 scope = Scope.from_user(
1114 scope, descr=f"Fixture '{func.__name__}'", where=self.baseid
1115 )
1116 self._scope: Final = scope
1117 # If the fixture is directly parametrized, the parameter values.
1118 self.params: Final = params
1119 # If the fixture is directly parametrized, a tuple of explicit IDs to
1120 # assign to the parameter values, or a callable to generate an ID given
1121 # a parameter value.
1122 self.ids: Final = ids
1123 # The names requested by the fixtures.
1124 self.argnames: Final = getfuncargnames(func, name=argname)
1125 # If the fixture was executed, the current value of the fixture.
1126 # Can change if the fixture is executed with different parameters.
1127 self.cached_result: _FixtureCachedResult[FixtureValue] | None = None
1128 self._finalizers: Final[list[Callable[[], object]]] = []
1129
1130 # only used to emit a deprecationwarning, can be removed in pytest9
1131 self._autouse = _autouse
1132
1133 @property
1134 def scope(self) -> ScopeName:
1135 """Scope string, one of "function", "class", "module", "package", "session"."""
1136 return self._scope.value
1137
1138 @property
1139 def has_location(self) -> bool:
1140 warnings.warn(FIXTUREDEF_HAS_LOCATION_DEPRECATED, stacklevel=2)
1141 return self._has_location
1142
1143 def addfinalizer(self, finalizer: Callable[[], object]) -> None:
1144 self._finalizers.append(finalizer)
1145
1146 def finish(self, request: SubRequest) -> None:
1147 if self.cached_result is None:
1148 # Already finished. It is assumed that finalizers cannot be added in
1149 # this state.
1150 return
1151
1152 exceptions: list[BaseException] = []
1153 while self._finalizers:
1154 fin = self._finalizers.pop()
1155 try:
1156 fin()
1157 except BaseException as e:
1158 exceptions.append(e)
1159 node = request.node
1160 # Even if finalization fails, we invalidate the cached fixture
1161 # value and remove all finalizers because they may be bound methods
1162 # which will keep instances alive.
1163 self.cached_result = None
1164 self._finalizers.clear()
1165 if len(exceptions) == 1:
1166 raise exceptions[0]
1167 elif len(exceptions) > 1:
1168 msg = f'errors while tearing down fixture "{self.argname}" of {node}'
1169 raise BaseExceptionGroup(msg, exceptions[::-1])
1170
1171 def execute(self, request: SubRequest) -> FixtureValue:
1172 """Return the value of this fixture, executing it if not cached."""
1173 # Ensure that the dependent fixtures requested by this fixture are loaded.
1174 # This needs to be done before checking if we have a cached value, since
1175 # if a dependent fixture has their cache invalidated, e.g. due to
1176 # parametrization, they finalize themselves and fixtures depending on it
1177 # (which will likely include this fixture) setting `self.cached_result = None`.
1178 # See #4871
1179 requested_fixtures_that_should_finalize_us = []
1180 for argname in self.argnames:
1181 fixturedef = request._get_active_fixturedef(argname)
1182 # Saves requested fixtures in a list so we later can add our finalizer
1183 # to them, ensuring that if a requested fixture gets torn down we get torn
1184 # down first. This is generally handled by SetupState, but still currently
1185 # needed when this fixture is not parametrized but depends on a parametrized
1186 # fixture.
1187 requested_fixtures_that_should_finalize_us.append(fixturedef)
1188
1189 # Check for (and return) cached value/exception.
1190 if self.cached_result is not None:
1191 request_cache_key = self.cache_key(request)
1192 cache_key = self.cached_result[1]
1193 try:
1194 # Attempt to make a normal == check: this might fail for objects
1195 # which do not implement the standard comparison (like numpy arrays -- #6497).
1196 cache_hit = bool(request_cache_key == cache_key)
1197 except (ValueError, RuntimeError):
1198 # If the comparison raises, use 'is' as fallback.
1199 cache_hit = request_cache_key is cache_key
1200
1201 if cache_hit:
1202 if self.cached_result[2] is not None:
1203 exc, exc_tb = self.cached_result[2]
1204 raise exc.with_traceback(exc_tb)
1205 else:
1206 return self.cached_result[0]
1207 # We have a previous but differently parametrized fixture instance
1208 # so we need to tear it down before creating a new one.
1209 self.finish(request)
1210 assert self.cached_result is None
1211
1212 # Add finalizer to requested fixtures we saved previously.
1213 # We make sure to do this after checking for cached value to avoid
1214 # adding our finalizer multiple times. (#12135)
1215 finalizer = functools.partial(self.finish, request=request)
1216 for parent_fixture in requested_fixtures_that_should_finalize_us:
1217 parent_fixture.addfinalizer(finalizer)
1218
1219 # Register the pytest_fixture_post_finalizer as the first finalizer,
1220 # which is executed last.
1221 assert not self._finalizers
1222 self.addfinalizer(
1223 lambda: request.node.ihook.pytest_fixture_post_finalizer(
1224 fixturedef=self, request=request
1225 )
1226 )
1227
1228 ihook = request.node.ihook
1229 try:
1230 # Setup the fixture, run the code in it, and cache the value
1231 # in self.cached_result.
1232 result: FixtureValue = ihook.pytest_fixture_setup(
1233 fixturedef=self, request=request
1234 )
1235 finally:
1236 # Schedule our finalizer, even if the setup failed.
1237 request.node.addfinalizer(finalizer)
1238
1239 return result
1240
1241 def cache_key(self, request: SubRequest) -> object:
1242 return getattr(request, "param", None)
1243
1244 def __repr__(self) -> str:
1245 return f"<FixtureDef argname={self.argname!r} scope={self.scope!r} baseid={self.baseid!r}>"
1246
1247
1248 class RequestFixtureDef(FixtureDef[FixtureRequest]):
1249 """A custom FixtureDef for the special "request" fixture.
1250
1251 A new one is generated on-demand whenever "request" is requested.
1252 """
1253
1254 def __init__(self, request: FixtureRequest) -> None:
1255 super().__init__(
1256 config=request.config,
1257 baseid=NOTSET,
1258 argname="request",
1259 func=lambda: request,
1260 scope=Scope.Function,
1261 params=None,
1262 node=request.node,
1263 _ispytest=True,
1264 )
1265 self.cached_result = (request, [0], None)
1266
1267 def addfinalizer(self, finalizer: Callable[[], object]) -> None:
1268 pass
1269
1270
1271 def resolve_fixture_function(
1272 fixturedef: FixtureDef[FixtureValue], request: FixtureRequest
1273 ) -> _FixtureFunc[FixtureValue]:
1274 """Get the actual callable that can be called to obtain the fixture
1275 value."""
1276 fixturefunc = fixturedef.func
1277 # The fixture function needs to be bound to the actual
1278 # request.instance so that code working with "fixturedef" behaves
1279 # as expected.
1280 instance = request.instance
1281
1282 if fixturedef._scope is Scope.Class:
1283 # Check if fixture is an instance method (bound to instance, not class)
1284 if hasattr(fixturefunc, "__self__"):
1285 bound_to = fixturefunc.__self__
1286 # classmethod: bound_to is the class itself (a type)
1287 # instance method: bound_to is an instance (not a type)
1288 if not isinstance(bound_to, type):
1289 warnings.warn(CLASS_FIXTURE_INSTANCE_METHOD, stacklevel=2)
1290
1291 if instance is not None:
1292 # Handle the case where fixture is defined not in a test class, but some other class
1293 # (for example a plugin class with a fixture), see #2270.
1294 if hasattr(fixturefunc, "__self__") and not isinstance(
1295 instance,
1296 fixturefunc.__self__.__class__,
1297 ):
1298 return fixturefunc
1299 fixturefunc = getimfunc(fixturedef.func)
1300 if fixturefunc != fixturedef.func:
1301 fixturefunc = fixturefunc.__get__(instance)
1302 return fixturefunc
1303
1304
1305 def pytest_fixture_setup(
1306 fixturedef: FixtureDef[FixtureValue], request: SubRequest
1307 ) -> FixtureValue:
1308 """Execution of fixture setup."""
1309 kwargs = {}
1310 for argname in fixturedef.argnames:
1311 kwargs[argname] = request.getfixturevalue(argname)
1312
1313 fixturefunc = resolve_fixture_function(fixturedef, request)
1314 my_cache_key = fixturedef.cache_key(request)
1315
1316 if inspect.isasyncgenfunction(fixturefunc) or inspect.iscoroutinefunction(
1317 fixturefunc
1318 ):
1319 auto_str = " with autouse=True" if fixturedef._autouse else ""
1320 fail(
1321 f"{request.node.name!r} requested an async fixture {request.fixturename!r}{auto_str}, "
1322 "with no plugin or hook that handled it. This is an error, as pytest does not natively support it.\n"
1323 "See: https://docs.pytest.org/en/stable/deprecations.html#sync-test-depending-on-async-fixture",
1324 pytrace=False,
1325 )
1326
1327 try:
1328 result = call_fixture_func(fixturefunc, request, kwargs)
1329 except TEST_OUTCOME as e:
1330 if isinstance(e, skip.Exception):
1331 # The test requested a fixture which caused a skip.
1332 # Don't show the fixture as the skip location, as then the user
1333 # wouldn't know which test skipped.
1334 e._use_item_location = True
1335 fixturedef.cached_result = (None, my_cache_key, (e, e.__traceback__))
1336 raise
1337 fixturedef.cached_result = (result, my_cache_key, None)
1338 return result
1339
1340
1341 @final
1342 @dataclasses.dataclass(frozen=True)
1343 class FixtureFunctionMarker:
1344 scope: ScopeName | Callable[[str, Config], ScopeName]
1345 params: tuple[object, ...] | None
1346 autouse: bool = False
1347 ids: tuple[object | None, ...] | Callable[[Any], object | None] | None = None
1348 name: str | None = None
1349
1350 _ispytest: dataclasses.InitVar[bool] = False
1351
1352 def __post_init__(self, _ispytest: bool) -> None:
1353 check_ispytest(_ispytest)
1354
1355 def __call__(self, function: FixtureFunction) -> FixtureFunctionDefinition:
1356 if inspect.isclass(function):
1357 raise ValueError("class fixtures not supported (maybe in the future)")
1358
1359 if isinstance(function, FixtureFunctionDefinition):
1360 raise ValueError(
1361 f"@pytest.fixture is being applied more than once to the same function {function.__name__!r}"
1362 )
1363
1364 if hasattr(function, "pytestmark"):
1365 fail(
1366 "Marks cannot be applied to fixtures.\n"
1367 "See docs: https://docs.pytest.org/en/stable/deprecations.html#applying-a-mark-to-a-fixture-function"
1368 )
1369
1370 fixture_definition = FixtureFunctionDefinition(
1371 function=function, fixture_function_marker=self, _ispytest=True
1372 )
1373
1374 name = self.name or function.__name__
1375 if name == "request":
1376 location = getlocation(function)
1377 fail(
1378 f"'request' is a reserved word for fixtures, use another name:\n {location}",
1379 pytrace=False,
1380 )
1381
1382 return fixture_definition
1383
1384
1385 # TODO: paramspec/return type annotation tracking and storing
1386 class FixtureFunctionDefinition:
1387 def __init__(
1388 self,
1389 *,
1390 function: Callable[..., Any],
1391 fixture_function_marker: FixtureFunctionMarker,
1392 instance: object | None = None,
1393 _ispytest: bool = False,
1394 ) -> None:
1395 check_ispytest(_ispytest)
1396 self.name = fixture_function_marker.name or function.__name__
1397 # In order to show the function that this fixture contains in messages.
1398 # Set the __name__ to be same as the function __name__ or the given fixture name.
1399 self.__name__ = self.name
1400 self._fixture_function_marker = fixture_function_marker
1401 if instance is not None:
1402 self._fixture_function = cast(
1403 Callable[..., Any], function.__get__(instance)
1404 )
1405 else:
1406 self._fixture_function = function
1407 functools.update_wrapper(self, function)
1408
1409 def __repr__(self) -> str:
1410 return f"<pytest_fixture({self._fixture_function})>"
1411
1412 def __get__(self, instance, owner=None):
1413 """Behave like a method if the function it was applied to was a method."""
1414 return FixtureFunctionDefinition(
1415 function=self._fixture_function,
1416 fixture_function_marker=self._fixture_function_marker,
1417 instance=instance,
1418 _ispytest=True,
1419 )
1420
1421 def __call__(self, *args: Any, **kwds: Any) -> Any:
1422 message = (
1423 f'Fixture "{self.name}" called directly. Fixtures are not meant to be called directly,\n'
1424 "but are created automatically when test functions request them as parameters.\n"
1425 "See https://docs.pytest.org/en/stable/explanation/fixtures.html for more information about fixtures, and\n"
1426 "https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly"
1427 )
1428 fail(message, pytrace=False)
1429
1430 def _get_wrapped_function(self) -> Callable[..., Any]:
1431 return self._fixture_function
1432
1433
1434 @overload
1435 def fixture(
1436 fixture_function: Callable[..., object],
1437 *,
1438 scope: ScopeName | Callable[[str, Config], ScopeName] = ...,
1439 params: Iterable[object] | None = ...,
1440 autouse: bool = ...,
1441 ids: Sequence[object | None] | Callable[[Any], object | None] | None = ...,
1442 name: str | None = ...,
1443 ) -> FixtureFunctionDefinition: ...
1444
1445
1446 @overload
1447 def fixture(
1448 fixture_function: None = ...,
1449 *,
1450 scope: ScopeName | Callable[[str, Config], ScopeName] = ...,
1451 params: Iterable[object] | None = ...,
1452 autouse: bool = ...,
1453 ids: Sequence[object | None] | Callable[[Any], object | None] | None = ...,
1454 name: str | None = None,
1455 ) -> FixtureFunctionMarker: ...
1456
1457
1458 def fixture(
1459 fixture_function: FixtureFunction | None = None,
1460 *,
1461 scope: ScopeName | Callable[[str, Config], ScopeName] = "function",
1462 params: Iterable[object] | None = None,
1463 autouse: bool = False,
1464 ids: Sequence[object | None] | Callable[[Any], object | None] | None = None,
1465 name: str | None = None,
1466 ) -> FixtureFunctionMarker | FixtureFunctionDefinition:
1467 """Decorator to mark a fixture factory function.
1468
1469 This decorator can be used, with or without parameters, to define a
1470 fixture function.
1471
1472 The name of the fixture function can later be referenced to cause its
1473 invocation ahead of running tests: test modules or classes can use the
1474 ``pytest.mark.usefixtures(fixturename)`` marker.
1475
1476 Test functions can directly use fixture names as input arguments in which
1477 case the fixture instance returned from the fixture function will be
1478 injected.
1479
1480 Fixtures can provide their values to test functions using ``return`` or
1481 ``yield`` statements. When using ``yield`` the code block after the
1482 ``yield`` statement is executed as teardown code regardless of the test
1483 outcome, and must yield exactly once.
1484
1485 :param scope:
1486 The scope for which this fixture is shared; one of ``"function"``
1487 (default), ``"class"``, ``"module"``, ``"package"`` or ``"session"``.
1488
1489 This parameter may also be a callable which receives ``(fixture_name, config)``
1490 as parameters, and must return a ``str`` with one of the values mentioned above.
1491
1492 See :ref:`dynamic scope` in the docs for more information.
1493
1494 :param params:
1495 An optional list of parameters which will cause multiple invocations
1496 of the fixture function and all of the tests using it. The current
1497 parameter is available in ``request.param``.
1498
1499 :param autouse:
1500 If True, the fixture func is activated for all tests that can see it.
1501 If False (the default), an explicit reference is needed to activate
1502 the fixture.
1503
1504 :param ids:
1505 Sequence of ids each corresponding to the params so that they are
1506 part of the test id. If no ids are provided they will be generated
1507 automatically from the params.
1508
1509 :param name:
1510 The name of the fixture. This defaults to the name of the decorated
1511 function. If a fixture is used in the same module in which it is
1512 defined, the function name of the fixture will be shadowed by the
1513 function arg that requests the fixture; one way to resolve this is to
1514 name the decorated function ``fixture_<fixturename>`` and then use
1515 ``@pytest.fixture(name='<fixturename>')``.
1516 """
1517 fixture_marker = FixtureFunctionMarker(
1518 scope=scope,
1519 params=tuple(params) if params is not None else None,
1520 autouse=autouse,
1521 ids=None if ids is None else ids if callable(ids) else tuple(ids),
1522 name=name,
1523 _ispytest=True,
1524 )
1525
1526 # Direct decoration.
1527 if fixture_function:
1528 return fixture_marker(fixture_function)
1529
1530 return fixture_marker
1531
1532
1533 @deprecated(
1534 "@pytest.yield_fixture is deprecated. Use @pytest.fixture instead; they are the same.",
1535 category=None, # We have our own runtime warning logic
1536 )
1537 def yield_fixture(
1538 fixture_function=None,
1539 *args,
1540 scope="function",
1541 params=None,
1542 autouse=False,
1543 ids=None,
1544 name=None,
1545 ):
1546 """(Return a) decorator to mark a yield-fixture factory function.
1547
1548 .. deprecated:: 3.0
1549 Use :py:func:`pytest.fixture` directly instead.
1550 """
1551 warnings.warn(YIELD_FIXTURE, stacklevel=2)
1552 return fixture(
1553 fixture_function,
1554 *args,
1555 scope=scope,
1556 params=params,
1557 autouse=autouse,
1558 ids=ids,
1559 name=name,
1560 )
1561
1562
1563 @fixture(scope="session")
1564 def pytestconfig(request: FixtureRequest) -> Config:
1565 """Session-scoped fixture that returns the session's :class:`pytest.Config`
1566 object.
1567
1568 Example::
1569
1570 def test_foo(pytestconfig):
1571 if pytestconfig.get_verbosity() > 0:
1572 ...
1573
1574 """
1575 return request.config
1576
1577
1578 def pytest_addoption(parser: Parser) -> None:
1579 parser.addini(
1580 "usefixtures",
1581 type="args",
1582 default=[],
1583 help="List of default fixtures to be used with this project",
1584 )
1585 group = parser.getgroup("general")
1586 group.addoption(
1587 "--fixtures",
1588 "--funcargs",
1589 action="store_true",
1590 dest="showfixtures",
1591 default=False,
1592 help="Show available fixtures, sorted by plugin appearance "
1593 "(fixtures with leading '_' are only shown with '-v')",
1594 )
1595 group.addoption(
1596 "--fixtures-per-test",
1597 action="store_true",
1598 dest="show_fixtures_per_test",
1599 default=False,
1600 help="Show fixtures per test",
1601 )
1602
1603
1604 def pytest_cmdline_main(config: Config) -> int | ExitCode | None:
1605 if config.option.showfixtures:
1606 showfixtures(config)
1607 return 0
1608 if config.option.show_fixtures_per_test:
1609 show_fixtures_per_test(config)
1610 return 0
1611 return None
1612
1613
1614 def _resolve_args_directness(
1615 argnames: Sequence[str],
1616 indirect: bool | Sequence[str],
1617 nodeid: str,
1618 ) -> dict[str, Literal["indirect", "direct"]]:
1619 """Resolve if each parametrized argument must be considered an indirect
1620 parameter to a fixture of the same name, or a direct parameter to the
1621 parametrized function, based on the ``indirect`` parameter of the
1622 parametrize() call.
1623
1624 :param argnames:
1625 List of argument names passed to ``parametrize()``.
1626 :param indirect:
1627 Same as the ``indirect`` parameter of ``parametrize()``.
1628 :param nodeid:
1629 Node ID to which the parametrization is applied.
1630 :returns:
1631 A dict mapping each arg name to either "indirect" or "direct".
1632 """
1633 arg_directness: dict[str, Literal["indirect", "direct"]]
1634 if isinstance(indirect, bool):
1635 arg_directness = dict.fromkeys(argnames, "indirect" if indirect else "direct")
1636 elif isinstance(indirect, Sequence):
1637 arg_directness = dict.fromkeys(argnames, "direct")
1638 for arg in indirect:
1639 if arg not in argnames:
1640 fail(
1641 f"In {nodeid}: indirect fixture '{arg}' doesn't exist",
1642 pytrace=False,
1643 )
1644 arg_directness[arg] = "indirect"
1645 else:
1646 fail(
1647 f"In {nodeid}: expected Sequence or boolean for indirect, got {type(indirect).__name__}",
1648 pytrace=False,
1649 )
1650 return arg_directness
1651
1652
1653 def _get_direct_parametrize_args(node: nodes.Node) -> set[str]:
1654 """Return all direct parametrization arguments of a node, so we don't
1655 mistake them for fixtures.
1656
1657 Check https://github.com/pytest-dev/pytest/issues/5036.
1658
1659 These things are done later as well when dealing with parametrization
1660 so this could be improved.
1661 """
1662 parametrize_argnames: set[str] = set()
1663 for marker in node.iter_markers(name="parametrize"):
1664 indirect = marker.kwargs.get("indirect", False)
1665 p_argnames, _ = ParameterSet._parse_parametrize_args(
1666 *marker.args, **marker.kwargs
1667 )
1668 p_directness = _resolve_args_directness(p_argnames, indirect, node.nodeid)
1669 parametrize_argnames.update(
1670 argname
1671 for argname, directness in p_directness.items()
1672 if directness == "direct"
1673 )
1674 return parametrize_argnames
1675
1676
1677 def deduplicate_names(*seqs: Iterable[str]) -> tuple[str, ...]:
1678 """De-duplicate the sequence of names while keeping the original order."""
1679 # Ideally we would use a set, but it does not preserve insertion order.
1680 return tuple(dict.fromkeys(name for seq in seqs for name in seq))
1681
1682
1683 class FixtureManager:
1684 """pytest fixture definitions and information is stored and managed
1685 from this class.
1686
1687 During collection fm.parsefactories() is called multiple times to parse
1688 fixture function definitions into FixtureDef objects and internal
1689 data structures.
1690
1691 During collection of test functions, metafunc-mechanics instantiate
1692 a FuncFixtureInfo object which is cached per node/func-name.
1693 This FuncFixtureInfo object is later retrieved by Function nodes
1694 which themselves offer a fixturenames attribute.
1695
1696 The FuncFixtureInfo object holds information about fixtures and FixtureDefs
1697 relevant for a particular function. An initial list of fixtures is
1698 assembled like this:
1699
1700 - config-defined usefixtures
1701 - autouse-marked fixtures along the collection chain up from the function
1702 - usefixtures markers at module/class/function level
1703 - test function funcargs
1704
1705 Subsequently the funcfixtureinfo.fixturenames attribute is computed
1706 as the closure of the fixtures needed to setup the initial fixtures,
1707 i.e. fixtures needed by fixture functions themselves are appended
1708 to the fixturenames list.
1709
1710 Upon the test-setup phases all fixturenames are instantiated, retrieved
1711 by a lookup of their FuncFixtureInfo.
1712 """
1713
1714 def __init__(self, session: Session) -> None:
1715 self.session = session
1716 self.config: Config = session.config
1717 # Maps a fixture name (argname) to all of the FixtureDefs in the test
1718 # suite/plugins defined with this name. Populated by parsefactories().
1719 # TODO: The order of the FixtureDefs list of each arg is significant,
1720 # explain.
1721 self._arg2fixturedefs: Final[dict[str, list[FixtureDef[Any]]]] = {}
1722 # A mapping from a node to a list of autouse fixture names it defines.
1723 # The Session entry holds global usefixtures from config.
1724 self._node_autousenames: Final[dict[nodes.Node, list[str]]] = {
1725 session: list(self.config.getini("usefixtures")),
1726 }
1727 # Legacy fallback: nodeid string -> autouse names, for plugins still
1728 # using the deprecated nodeid-based API without a node reference.
1729 self._nodeid_autousenames: Final[dict[str, list[str]]] = {}
1730 # Pending conftest modules waiting to be parsed when their Directory is collected.
1731 # Maps directory path -> conftest plugin module.
1732 self._pending_conftests: Final[dict[Path, object]] = {}
1733 session.config.pluginmanager.register(self, "funcmanage")
1734 # Flush initial conftests from directories above rootpath immediately.
1735 # These will never get a Directory collector, so they need Session scope.
1736 # This must happen here (not in pytest_make_collect_report) because
1737 # collection may fail before Session collection starts (e.g. bad args).
1738 self._flush_pending_conftests_to_session(session)
1739
1740 def getfixtureinfo(
1741 self,
1742 node: nodes.Item,
1743 func: Callable[..., object] | None,
1744 cls: type | None,
1745 ) -> FuncFixtureInfo:
1746 """Calculate the :class:`FuncFixtureInfo` for an item.
1747
1748 If ``func`` is None, or if the item sets an attribute
1749 ``nofuncargs = True``, then ``func`` is not examined at all.
1750
1751 :param node:
1752 The item requesting the fixtures.
1753 :param func:
1754 The item's function.
1755 :param cls:
1756 If the function is a method, the method's class.
1757 """
1758 if func is not None and not getattr(node, "nofuncargs", False):
1759 argnames = getfuncargnames(func, name=node.name, cls=cls)
1760 else:
1761 argnames = ()
1762 usefixturesnames = self._getusefixturesnames(node)
1763 autousenames = self._getautousenames(node)
1764 initialnames = deduplicate_names(autousenames, usefixturesnames, argnames)
1765
1766 direct_parametrize_args = _get_direct_parametrize_args(node)
1767
1768 names_closure, arg2fixturedefs = self.getfixtureclosure(
1769 parentnode=node,
1770 initialnames=initialnames,
1771 ignore_args=direct_parametrize_args,
1772 )
1773
1774 return FuncFixtureInfo(argnames, initialnames, names_closure, arg2fixturedefs)
1775
1776 def pytest_plugin_registered(self, plugin: _PluggyPlugin, plugin_name: str) -> None:
1777 # Fixtures defined in conftest plugins are only visible to within the
1778 # conftest's directory. This is unlike fixtures in non-conftest plugins
1779 # which have global visibility. Conftest fixtures are deferred until
1780 # their Directory is collected, so we can use the Directory's nodeid.
1781 if plugin_name and plugin_name.endswith("conftest.py"):
1782 # Note: we explicitly do *not* use `plugin.__file__` here -- The
1783 # difference is that plugin_name has the correct capitalization on
1784 # case-insensitive systems (Windows) and other normalization issues
1785 # (issue #11816).
1786 conftestpath = absolutepath(plugin_name)
1787 conftest_dir = conftestpath.parent
1788 # Store conftest for deferred parsing when its Directory is collected.
1789 self._pending_conftests[conftest_dir] = plugin
1790 else:
1791 # Non-conftest plugins have global visibility.
1792 self.parsefactories(holder=plugin, node=self.session)
1793
1794 @hookimpl(wrapper=True)
1795 def pytest_make_collect_report(
1796 self, collector: nodes.Collector
1797 ) -> Generator[None, CollectReport, CollectReport]:
1798 result = yield
1799 if isinstance(collector, nodes.Directory):
1800 plugin = self._pending_conftests.pop(collector.path, None)
1801 if plugin is not None:
1802 self.parsefactories(holder=plugin, node=collector)
1803 return result
1804
1805 def _flush_pending_conftests_to_session(self, session: Session) -> None:
1806 """Assign Session scope to initial conftests whose directories won't
1807 be collected as Directory nodes (e.g. ancestors above rootdir)."""
1808 rootpath = session.config.rootpath
1809 orphaned: list[tuple[Path, object]] = []
1810 for conftest_dir, plugin in list(self._pending_conftests.items()):
1811 # If the conftest dir is not under rootpath, it will never get
1812 # a Directory collector — assign it to Session now.
1813 try:
1814 conftest_dir.relative_to(rootpath)
1815 except ValueError:
1816 orphaned.append((conftest_dir, plugin))
1817 for conftest_dir, plugin in orphaned:
1818 del self._pending_conftests[conftest_dir]
1819 self.parsefactories(holder=plugin, node=session)
1820
1821 def pytest_collection_finish(self) -> None:
1822 """Clean up any conftests that were never collected by a Directory.
1823
1824 After __init__ flushes above-rootdir conftests and collection pops
1825 under-rootdir ones, remaining entries mean collection was interrupted
1826 (e.g. UsageError for a bad path). These conftests' fixtures aren't
1827 needed since their directories' tests weren't collected either.
1828 """
1829 self._pending_conftests.clear()
1830
1831 def _getautousenames(self, node: nodes.Node) -> Iterator[str]:
1832 """Return the names of autouse fixtures applicable to node."""
1833 for parentnode in node.listchain():
1834 basenames = self._node_autousenames.get(parentnode)
1835 if basenames:
1836 yield from basenames
1837 # Legacy fallback: check string-based nodeid autouse names.
1838 nodeid_basenames = self._nodeid_autousenames.get(parentnode.nodeid)
1839 if nodeid_basenames:
1840 yield from nodeid_basenames
1841
1842 def _getusefixturesnames(self, node: nodes.Item) -> Iterator[str]:
1843 """Return the names of usefixtures fixtures applicable to node."""
1844 for marker_node, mark in node.iter_markers_with_node(name="usefixtures"):
1845 if not mark.args:
1846 marker_node.warn(
1847 PytestWarning(
1848 f"usefixtures() in {node.nodeid} without arguments has no effect"
1849 )
1850 )
1851 yield from mark.args
1852
1853 def getfixtureclosure(
1854 self,
1855 parentnode: nodes.Node,
1856 initialnames: tuple[str, ...],
1857 ignore_args: AbstractSet[str],
1858 ) -> tuple[list[str], dict[str, Sequence[FixtureDef[Any]]]]:
1859 # Collect the closure of all fixtures, starting with the given
1860 # fixturenames as the initial set. As we have to visit all
1861 # factory definitions anyway, we also return an arg2fixturedefs
1862 # mapping so that the caller can reuse it and does not have
1863 # to re-discover fixturedefs again for each fixturename
1864 # (discovering matching fixtures for a given name/node is expensive).
1865
1866 arg2fixturedefs: dict[str, Sequence[FixtureDef[Any]]] = {}
1867
1868 def getfixturedefs(argname: str) -> Sequence[FixtureDef[Any]] | None:
1869 if argname in ignore_args:
1870 return None
1871
1872 fixturedefs = arg2fixturedefs.get(argname)
1873 if not fixturedefs:
1874 fixturedefs = self.getfixturedefs(argname, parentnode)
1875 if not fixturedefs:
1876 # Fixture not defined or not visible (will error during runtest).
1877 return None
1878 arg2fixturedefs[argname] = fixturedefs
1879 return fixturedefs
1880
1881 def sort_by_scope(arg_name: str) -> Scope:
1882 try:
1883 fixturedefs = arg2fixturedefs[arg_name]
1884 except KeyError:
1885 return Scope.Function
1886 else:
1887 return fixturedefs[-1]._scope
1888
1889 fixturenames_closure = sorted(
1890 traverse_fixture_closure(
1891 initialnames,
1892 getfixturedefs=getfixturedefs,
1893 ),
1894 key=sort_by_scope,
1895 reverse=True,
1896 )
1897
1898 return fixturenames_closure, arg2fixturedefs
1899
1900 def pytest_generate_tests(self, metafunc: Metafunc) -> None:
1901 """Generate new tests based on parametrized fixtures used by the given metafunc"""
1902
1903 def get_parametrize_mark_argnames(mark: Mark) -> Sequence[str]:
1904 args, _ = ParameterSet._parse_parametrize_args(*mark.args, **mark.kwargs)
1905 return args
1906
1907 for argname in metafunc.fixturenames:
1908 # Get the FixtureDefs for the argname.
1909 fixture_defs = metafunc._arg2fixturedefs.get(argname, ())
1910
1911 # If the test itself parametrizes using this argname, give it
1912 # precedence.
1913 if any(
1914 argname in get_parametrize_mark_argnames(mark)
1915 for mark in metafunc.definition.iter_markers("parametrize")
1916 ):
1917 continue
1918
1919 # In the common case we only look at the fixture def with the
1920 # closest scope (last in the list). But if the fixture overrides
1921 # another fixture, while requesting the super fixture, keep going
1922 # in case the super fixture is parametrized (#1953).
1923 for fixturedef in reversed(fixture_defs):
1924 # Fixture is parametrized, apply it and stop.
1925 if fixturedef.params is not None:
1926 metafunc.parametrize(
1927 argname,
1928 fixturedef.params,
1929 indirect=True,
1930 scope=fixturedef.scope,
1931 ids=fixturedef.ids,
1932 )
1933 break
1934
1935 # Not requesting the overridden super fixture, stop.
1936 #
1937 # TODO: Handle the case where the super-fixture is transitively
1938 # requested (see #7737 and the xfail'd test
1939 # test_override_parametrized_fixture_via_transitive_fixture).
1940 if argname not in fixturedef.argnames:
1941 break
1942
1943 # Try next super fixture, if any.
1944
1945 def pytest_collection_modifyitems(self, items: list[nodes.Item]) -> None:
1946 # Separate parametrized setups.
1947 items[:] = reorder_items(items)
1948
1949 def _register_fixture(
1950 self,
1951 *,
1952 name: str,
1953 func: _FixtureFunc[object],
1954 nodeid: str | None | NotSetType = NOTSET,
1955 scope: Scope | ScopeName | Callable[[str, Config], ScopeName] = "function",
1956 params: Sequence[object] | None = None,
1957 ids: tuple[object | None, ...] | Callable[[Any], object | None] | None = None,
1958 autouse: bool = False,
1959 node: nodes.Node | NotSetType = NOTSET,
1960 ) -> None:
1961 """Register a fixture
1962
1963 :param name:
1964 The fixture's name.
1965 :param func:
1966 The fixture's implementation function.
1967 :param nodeid:
1968 The visibility of the fixture (deprecated, use node instead).
1969 The fixture will be available to the node with this nodeid and
1970 its children in the collection tree. None means global visibility.
1971 :param node:
1972 The node where the fixture is defined (preferred over nodeid).
1973 When provided, enables node-based matching which is more robust.
1974 :param scope:
1975 The fixture's scope.
1976 :param params:
1977 The fixture's parametrization params.
1978 :param ids:
1979 The fixture's IDs.
1980 :param autouse:
1981 Whether this is an autouse fixture.
1982 """
1983 # Emit deprecation warning if nodeid string.
1984 if nodeid is not NOTSET or node is NOTSET:
1985 warnings.warn(FIXTURE_NODEID_DEPRECATED, stacklevel=2)
1986 fixture_def = FixtureDef(
1987 config=self.config,
1988 baseid=nodeid,
1989 argname=name,
1990 func=func,
1991 scope=scope,
1992 params=params,
1993 ids=ids,
1994 _ispytest=True,
1995 _autouse=autouse,
1996 node=node,
1997 )
1998
1999 faclist = self._arg2fixturedefs.setdefault(name, [])
2000 # Insert the fixturedef into the list while maintaining a partial order
2001 # based on visibility: a fixturedef whose visibility is more specific
2002 # sorts after a more general one, so that it takes precedence in the
2003 # override chain (the last applicable fixturedef in the list is used
2004 # first, see getfixturedefs).
2005 # fixturedefs with the same visibility keep registration order, i.e. the
2006 # last registered wins.
2007 # The order between non-comparable fixturedefs doesn't matter since they
2008 # cannot be visible together.
2009 # The idea is that a fixture that is defined closer to the item should
2010 # take precedence.
2011 for i, existing in enumerate(faclist):
2012 if is_visibility_more_specific(existing, fixture_def):
2013 faclist.insert(i, fixture_def)
2014 break
2015 else:
2016 faclist.append(fixture_def)
2017 if autouse:
2018 if node is not NOTSET:
2019 self._node_autousenames.setdefault(node, []).append(name)
2020 elif nodeid is not NOTSET and nodeid is not None:
2021 # Legacy: plugin passed nodeid string without node reference.
2022 self._nodeid_autousenames.setdefault(nodeid, []).append(name)
2023 else:
2024 # Global plugin autouse fixtures go under Session.
2025 self._node_autousenames.setdefault(self.session, []).append(name)
2026
2027 @overload
2028 def parsefactories(
2029 self,
2030 node_or_obj: nodes.Node,
2031 ) -> None:
2032 raise NotImplementedError()
2033
2034 @overload
2035 @deprecated(
2036 "parsefactories(obj, nodeid) is deprecated, use parsefactories(holder=obj, node=node) instead"
2037 )
2038 def parsefactories(
2039 self,
2040 node_or_obj: object,
2041 nodeid: str | None,
2042 ) -> None:
2043 raise NotImplementedError()
2044
2045 @overload
2046 def parsefactories(
2047 self,
2048 node_or_obj: NotSetType = ...,
2049 nodeid: NotSetType = ...,
2050 *,
2051 holder: object,
2052 node: nodes.Node,
2053 ) -> None:
2054 raise NotImplementedError()
2055
2056 def parsefactories(
2057 self,
2058 node_or_obj: nodes.Node | object | NotSetType = NOTSET,
2059 nodeid: str | None | NotSetType = NOTSET,
2060 *,
2061 holder: object | NotSetType = NOTSET,
2062 node: nodes.Node | NotSetType = NOTSET,
2063 ) -> None:
2064 """Collect fixtures from a collection node or object.
2065
2066 Found fixtures are parsed into `FixtureDef`s and saved.
2067
2068 The preferred API uses keyword-only arguments:
2069 - ``holder``: The object to scan for fixtures.
2070 - ``node``: The node determining fixture visibility.
2071
2072 Legacy positional API (translated internally):
2073 - ``parsefactories(node)``: Uses node.obj as holder, node for scope.
2074 - ``parsefactories(obj, nodeid)``: Uses obj as holder, nodeid string for scope.
2075 """
2076 # Translate legacy API to holder/node sources of truth
2077 # Either effective_node or effective_nodeid will be set, not both
2078 effective_node: nodes.Node | NotSetType = NOTSET
2079 effective_nodeid: str | None | NotSetType = NOTSET
2080
2081 if holder is not NOTSET:
2082 # New API: holder and node explicitly provided
2083 holderobj = holder
2084 effective_node = node
2085 elif node_or_obj is NOTSET:
2086 raise TypeError("parsefactories() requires holder or node_or_obj")
2087 elif nodeid is not NOTSET:
2088 # Legacy: parsefactories(obj, nodeid) - string-based scoping only.
2089 warnings.warn(PARSEFACTORIES_NODEID_DEPRECATED, stacklevel=2)
2090 holderobj = node_or_obj
2091 effective_nodeid = nodeid
2092 else:
2093 # parsefactories(node) - node has .obj attribute
2094 assert isinstance(node_or_obj, nodes.Node)
2095 holderobj = cast(object, node_or_obj.obj) # type: ignore[attr-defined]
2096 effective_node = node_or_obj
2097
2098 # Avoid accessing `@property` (and other descriptors) when iterating fixtures.
2099 if not safe_isclass(holderobj) and not isinstance(holderobj, types.ModuleType):
2100 holderobj_tp: object = type(holderobj)
2101 else:
2102 holderobj_tp = holderobj
2103
2104 for name in dir(holderobj):
2105 # The attribute can be an arbitrary descriptor, so the attribute
2106 # access below can raise. safe_getattr() ignores such exceptions.
2107 obj_ub = safe_getattr(holderobj_tp, name, None)
2108 if type(obj_ub) is FixtureFunctionDefinition:
2109 marker = obj_ub._fixture_function_marker
2110 if marker.name:
2111 fixture_name = marker.name
2112 else:
2113 fixture_name = name
2114
2115 # OK we know it is a fixture -- now safe to look up on the _instance_.
2116 try:
2117 obj = getattr(holderobj, name)
2118 # if the fixture is named in the decorator we cannot find it in the module
2119 except AttributeError:
2120 obj = obj_ub
2121
2122 func = obj._get_wrapped_function()
2123
2124 self._register_fixture(
2125 name=fixture_name,
2126 func=func,
2127 scope=marker.scope,
2128 params=marker.params,
2129 ids=marker.ids,
2130 autouse=marker.autouse,
2131 node=effective_node,
2132 nodeid=effective_nodeid,
2133 )
2134
2135 def getfixturedefs(
2136 self, argname: str, node: nodes.Node
2137 ) -> Sequence[FixtureDef[Any]] | None:
2138 """Get FixtureDefs for a fixture name which are applicable
2139 to a given node.
2140
2141 Returns None if there are no fixtures at all defined with the given
2142 name. (This is different from the case in which there are fixtures
2143 with the given name, but none applicable to the node. In this case,
2144 an empty result is returned).
2145
2146 :param argname: Name of the fixture to search for.
2147 :param node: The requesting Node.
2148 """
2149 try:
2150 fixturedefs = self._arg2fixturedefs[argname]
2151 except KeyError:
2152 return None
2153 return tuple(self._matchfactories(fixturedefs, node))
2154
2155 def _matchfactories(
2156 self, fixturedefs: Iterable[FixtureDef[Any]], node: nodes.Node
2157 ) -> Iterator[FixtureDef[Any]]:
2158 # Collect parent nodes and their IDs for matching
2159 parent_nodes = set(node.iter_parents())
2160 parentnodeids = {n.nodeid for n in parent_nodes}
2161
2162 for fixturedef in fixturedefs:
2163 if fixturedef.node is not None:
2164 # Node-based matching: check if fixture's node is a parent
2165 if fixturedef.node in parent_nodes:
2166 yield fixturedef
2167 elif fixturedef.baseid in parentnodeids:
2168 # Fallback to string-based matching for legacy/plugins
2169 yield fixturedef
2170
2171
2172 def show_fixtures_per_test(config: Config) -> int | ExitCode:
2173 from _pytest.main import wrap_session
2174
2175 return wrap_session(config, _show_fixtures_per_test)
2176
2177
2178 _PYTEST_DIR = Path(_pytest.__file__).parent
2179
2180
2181 def _pretty_fixture_path(invocation_dir: Path, func) -> str:
2182 loc = Path(getlocation(func, invocation_dir))
2183 prefix = Path("...", "_pytest")
2184 try:
2185 return str(prefix / loc.relative_to(_PYTEST_DIR))
2186 except ValueError:
2187 return bestrelpath(invocation_dir, loc)
2188
2189
2190 def _get_fixtures_per_test(test: nodes.Item) -> Iterator[FixtureDef[object]]:
2191 """Returns all fixtures used by the test item except for those created by
2192 direct parametrization and those requested dynamically with
2193 ``request.getfixturevalue``.
2194
2195 The justification for excluding fixtures created by direct parametrization
2196 is that for users, they are internal implementation detail.
2197
2198 Dynamically requested fixtures are excluded because they are not known
2199 statically.
2200 """
2201 from _pytest.python import DirectParamFixtureDef
2202
2203 # Custom Items may not have _fixtureinfo attribute.
2204 fixture_info: FuncFixtureInfo | None = getattr(test, "_fixtureinfo", None)
2205 if fixture_info is None:
2206 return # pragma: no cover
2207
2208 # dict key not used in loop but needed for sorting.
2209 for argname, fixturedefs in sorted(fixture_info.name2fixturedefs.items()):
2210 if not fixturedefs:
2211 # Not supposed to be empty, but for safety.
2212 continue # pragma: no cover
2213 # Last item is expected to be the one directly used by the test item.
2214 fixturedef = fixturedefs[-1]
2215 if isinstance(fixturedef, DirectParamFixtureDef):
2216 continue
2217 yield fixturedef
2218
2219
2220 def _show_fixtures_per_test(config: Config, session: Session) -> None:
2221 import _pytest.config
2222
2223 session.perform_collect()
2224 invocation_dir = config.invocation_params.dir
2225 tw = _pytest.config.create_terminal_writer(config)
2226 verbose = config.get_verbosity()
2227
2228 def get_best_relpath(func) -> str:
2229 loc = getlocation(func, invocation_dir)
2230 return bestrelpath(invocation_dir, Path(loc))
2231
2232 def write_fixture(fixture_def: FixtureDef[object]) -> None:
2233 argname = fixture_def.argname
2234 if verbose <= 0 and argname.startswith("_"):
2235 return
2236 prettypath = _pretty_fixture_path(invocation_dir, fixture_def.func)
2237 tw.write(f"{argname}", green=True)
2238 tw.write(f" -- {prettypath}", yellow=True)
2239 tw.write("\n")
2240 fixture_doc = inspect.getdoc(fixture_def.func)
2241 if fixture_doc:
2242 write_docstring(
2243 tw,
2244 fixture_doc.split("\n\n", maxsplit=1)[0]
2245 if verbose <= 0
2246 else fixture_doc,
2247 )
2248 else:
2249 tw.line(" no docstring available", red=True)
2250
2251 def write_item(item: nodes.Item) -> None:
2252 fixturedefs = list(_get_fixtures_per_test(item))
2253 if not fixturedefs:
2254 # This test item does not use any fixtures.
2255 return
2256
2257 tw.line()
2258 tw.sep("-", f"fixtures used by {item.name}")
2259 # TODO: Fix this type ignore.
2260 tw.sep("-", f"({get_best_relpath(item.function)})") # type: ignore[attr-defined]
2261
2262 for fixturedef in fixturedefs:
2263 write_fixture(fixturedef)
2264
2265 for session_item in session.items:
2266 write_item(session_item)
2267
2268
2269 def showfixtures(config: Config) -> int | ExitCode:
2270 from _pytest.main import wrap_session
2271
2272 return wrap_session(config, _showfixtures_main)
2273
2274
2275 def _showfixtures_main(config: Config, session: Session) -> None:
2276 import _pytest.config
2277
2278 session.perform_collect()
2279 invocation_dir = config.invocation_params.dir
2280 tw = _pytest.config.create_terminal_writer(config)
2281 verbose = config.get_verbosity()
2282
2283 fm = session._fixturemanager
2284
2285 available = []
2286 seen: set[tuple[str, str]] = set()
2287
2288 for argname, fixturedefs in fm._arg2fixturedefs.items():
2289 assert fixturedefs is not None
2290 if not fixturedefs:
2291 continue
2292 for fixturedef in fixturedefs:
2293 loc = getlocation(fixturedef.func, invocation_dir)
2294 if (fixturedef.argname, loc) in seen:
2295 continue
2296 seen.add((fixturedef.argname, loc))
2297 available.append(
2298 (
2299 len(fixturedef.baseid),
2300 fixturedef.func.__module__,
2301 _pretty_fixture_path(invocation_dir, fixturedef.func),
2302 fixturedef.argname,
2303 fixturedef,
2304 )
2305 )
2306
2307 available.sort()
2308 currentmodule = None
2309 for baseid, module, prettypath, argname, fixturedef in available:
2310 if currentmodule != module:
2311 if not module.startswith("_pytest."):
2312 tw.line()
2313 tw.sep("-", f"fixtures defined from {module}")
2314 currentmodule = module
2315 if verbose <= 0 and argname.startswith("_"):
2316 continue
2317 tw.write(f"{argname}", green=True)
2318 if fixturedef.scope != "function":
2319 tw.write(f" [{fixturedef.scope} scope]", cyan=True)
2320 tw.write(f" -- {prettypath}", yellow=True)
2321 tw.write("\n")
2322 doc = inspect.getdoc(fixturedef.func)
2323 if doc:
2324 write_docstring(
2325 tw, doc.split("\n\n", maxsplit=1)[0] if verbose <= 0 else doc
2326 )
2327 else:
2328 tw.line(" no docstring available", red=True)
2329 tw.line()
2330
2331
2332 def write_docstring(tw: TerminalWriter, doc: str, indent: str = " ") -> None:
2333 for line in doc.split("\n"):
2334 tw.line(indent + line)
2335
2336
2337 def register_fixture(
2338 *,
2339 name: str,
2340 func: _FixtureFunc[object],
2341 node: nodes.Node,
2342 scope: ScopeName | Callable[[str, Config], ScopeName] = "function",
2343 params: Sequence[object] | None = None,
2344 ids: tuple[object | None, ...] | Callable[[Any], object | None] | None = None,
2345 autouse: bool = False,
2346 ) -> None:
2347 """Register a fixture imperatively.
2348
2349 This is an advanced function intended for use by plugins.
2350
2351 Normally, fixtures should be registered declaratively using the
2352 :func:`@pytest.fixture <pytest.fixture>` decorator. Pytest looks for these
2353 fixture definitions during the collection phase and registers them
2354 automatically. For some plugin usecases the declarative interface can be
2355 cumbersome or nonviable, in which case the imperative interface can be used.
2356
2357 Fixture registration is expected to happen during the collection phase, and
2358 this is the only sanctioned use. However, to allow for more creative uses,
2359 this is not enforced. But do so at your own risk!
2360
2361 .. versionadded: 9.1
2362
2363 :param name:
2364 The fixture's name.
2365 :param func:
2366 The fixture's implementation function.
2367 :param node:
2368 The visibility of the fixture.
2369
2370 Only items that are descendents of this node in the collection tree will
2371 be able to request this fixture. You can think of this as the place
2372 where you would put the `@pytest.fixture`.
2373
2374 For global visibility, pass the :class:`session <pytest.Session>` node,
2375 which is the root of the collection tree.
2376 :param scope:
2377 The fixture's scope.
2378 :param params:
2379 The fixture's parametrization params.
2380 :param ids:
2381 The fixture's IDs.
2382 :param autouse:
2383 Whether this is an autouse fixture.
2384 """
2385 node.session._fixturemanager._register_fixture(
2386 name=name,
2387 func=func,
2388 node=node,
2389 scope=scope,
2390 params=params,
2391 ids=ids,
2392 autouse=autouse,
2393 )