Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/src/_pytest/fixtures.py

raw
1 # mypy: allow-untyped-defs
2 import abc
3 from collections import defaultdict
4 from collections import deque
5 import dataclasses
6 import functools
7 import inspect
8 import os
9 from pathlib import Path
10 import sys
11 from typing import AbstractSet
12 from typing import Any
13 from typing import Callable
14 from typing import cast
15 from typing import Dict
16 from typing import Final
17 from typing import final
18 from typing import Generator
19 from typing import Generic
20 from typing import Iterable
21 from typing import Iterator
22 from typing import List
23 from typing import MutableMapping
24 from typing import NoReturn
25 from typing import Optional
26 from typing import overload
27 from typing import Sequence
28 from typing import Set
29 from typing import Tuple
30 from typing import TYPE_CHECKING
31 from typing import TypeVar
32 from typing import Union
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 FormattedExcinfo
40 from _pytest._code.code import TerminalRepr
41 from _pytest._io import TerminalWriter
42 from _pytest.compat import _PytestWrapper
43 from _pytest.compat import assert_never
44 from _pytest.compat import get_real_func
45 from _pytest.compat import get_real_method
46 from _pytest.compat import getfuncargnames
47 from _pytest.compat import getimfunc
48 from _pytest.compat import getlocation
49 from _pytest.compat import is_generator
50 from _pytest.compat import NOTSET
51 from _pytest.compat import NotSetType
52 from _pytest.compat import safe_getattr
53 from _pytest.config import _PluggyPlugin
54 from _pytest.config import Config
55 from _pytest.config import ExitCode
56 from _pytest.config.argparsing import Parser
57 from _pytest.deprecated import check_ispytest
58 from _pytest.deprecated import MARKED_FIXTURE
59 from _pytest.deprecated import YIELD_FIXTURE
60 from _pytest.mark import Mark
61 from _pytest.mark import ParameterSet
62 from _pytest.mark.structures import MarkDecorator
63 from _pytest.outcomes import fail
64 from _pytest.outcomes import skip
65 from _pytest.outcomes import TEST_OUTCOME
66 from _pytest.pathlib import absolutepath
67 from _pytest.pathlib import bestrelpath
68 from _pytest.scope import _ScopeName
69 from _pytest.scope import HIGH_SCOPES
70 from _pytest.scope import Scope
71
72
73 if sys.version_info < (3, 11):
74 from exceptiongroup import BaseExceptionGroup
75
76
77 if TYPE_CHECKING:
78 from typing import Deque
79
80 from _pytest.main import Session
81 from _pytest.python import CallSpec2
82 from _pytest.python import Function
83 from _pytest.python import Metafunc
84
85
86 # The value of the fixture -- return/yield of the fixture function (type variable).
87 FixtureValue = TypeVar("FixtureValue")
88 # The type of the fixture function (type variable).
89 FixtureFunction = TypeVar("FixtureFunction", bound=Callable[..., object])
90 # The type of a fixture function (type alias generic in fixture value).
91 _FixtureFunc = Union[
92 Callable[..., FixtureValue], Callable[..., Generator[FixtureValue, None, None]]
93 ]
94 # The type of FixtureDef.cached_result (type alias generic in fixture value).
95 _FixtureCachedResult = Union[
96 Tuple[
97 # The result.
98 FixtureValue,
99 # Cache key.
100 object,
101 None,
102 ],
103 Tuple[
104 None,
105 # Cache key.
106 object,
107 # Exception if raised.
108 BaseException,
109 ],
110 ]
111
112
113 @dataclasses.dataclass(frozen=True)
114 class PseudoFixtureDef(Generic[FixtureValue]):
115 cached_result: "_FixtureCachedResult[FixtureValue]"
116 _scope: Scope
117
118
119 def pytest_sessionstart(session: "Session") -> None:
120 session._fixturemanager = FixtureManager(session)
121
122
123 def get_scope_package(
124 node: nodes.Item,
125 fixturedef: "FixtureDef[object]",
126 ) -> Optional[nodes.Node]:
127 from _pytest.python import Package
128
129 for parent in node.iter_parents():
130 if isinstance(parent, Package) and parent.nodeid == fixturedef.baseid:
131 return parent
132 return node.session
133
134
135 def get_scope_node(node: nodes.Node, scope: Scope) -> Optional[nodes.Node]:
136 import _pytest.python
137
138 if scope is Scope.Function:
139 # Type ignored because this is actually safe, see:
140 # https://github.com/python/mypy/issues/4717
141 return node.getparent(nodes.Item) # type: ignore[type-abstract]
142 elif scope is Scope.Class:
143 return node.getparent(_pytest.python.Class)
144 elif scope is Scope.Module:
145 return node.getparent(_pytest.python.Module)
146 elif scope is Scope.Package:
147 return node.getparent(_pytest.python.Package)
148 elif scope is Scope.Session:
149 return node.getparent(_pytest.main.Session)
150 else:
151 assert_never(scope)
152
153
154 def getfixturemarker(obj: object) -> Optional["FixtureFunctionMarker"]:
155 """Return fixturemarker or None if it doesn't exist or raised
156 exceptions."""
157 return cast(
158 Optional[FixtureFunctionMarker],
159 safe_getattr(obj, "_pytestfixturefunction", None),
160 )
161
162
163 @dataclasses.dataclass(frozen=True)
164 class FixtureArgKey:
165 argname: str
166 param_index: int
167 scoped_item_path: Optional[Path]
168 item_cls: Optional[type]
169
170
171 def get_parametrized_fixture_keys(
172 item: nodes.Item, scope: Scope
173 ) -> Iterator[FixtureArgKey]:
174 """Return list of keys for all parametrized arguments which match
175 the specified scope."""
176 assert scope is not Scope.Function
177 try:
178 callspec: CallSpec2 = item.callspec # type: ignore[attr-defined]
179 except AttributeError:
180 return
181 for argname in callspec.indices:
182 if callspec._arg2scope[argname] != scope:
183 continue
184
185 item_cls = None
186 if scope is Scope.Session:
187 scoped_item_path = None
188 elif scope is Scope.Package:
189 scoped_item_path = item.path
190 elif scope is Scope.Module:
191 scoped_item_path = item.path
192 elif scope is Scope.Class:
193 scoped_item_path = item.path
194 item_cls = item.cls # type: ignore[attr-defined]
195 else:
196 assert_never(scope)
197
198 param_index = callspec.indices[argname]
199 yield FixtureArgKey(argname, param_index, scoped_item_path, item_cls)
200
201
202 # Algorithm for sorting on a per-parametrized resource setup basis.
203 # It is called for Session scope first and performs sorting
204 # down to the lower scopes such as to minimize number of "high scope"
205 # setups and teardowns.
206
207
208 def reorder_items(items: Sequence[nodes.Item]) -> List[nodes.Item]:
209 argkeys_cache: Dict[Scope, Dict[nodes.Item, Dict[FixtureArgKey, None]]] = {}
210 items_by_argkey: Dict[Scope, Dict[FixtureArgKey, Deque[nodes.Item]]] = {}
211 for scope in HIGH_SCOPES:
212 scoped_argkeys_cache = argkeys_cache[scope] = {}
213 scoped_items_by_argkey = items_by_argkey[scope] = defaultdict(deque)
214 for item in items:
215 keys = dict.fromkeys(get_parametrized_fixture_keys(item, scope), None)
216 if keys:
217 scoped_argkeys_cache[item] = keys
218 for key in keys:
219 scoped_items_by_argkey[key].append(item)
220 items_dict = dict.fromkeys(items, None)
221 return list(
222 reorder_items_atscope(items_dict, argkeys_cache, items_by_argkey, Scope.Session)
223 )
224
225
226 def fix_cache_order(
227 item: nodes.Item,
228 argkeys_cache: Dict[Scope, Dict[nodes.Item, Dict[FixtureArgKey, None]]],
229 items_by_argkey: Dict[Scope, Dict[FixtureArgKey, "Deque[nodes.Item]"]],
230 ) -> None:
231 for scope in HIGH_SCOPES:
232 for key in argkeys_cache[scope].get(item, []):
233 items_by_argkey[scope][key].appendleft(item)
234
235
236 def reorder_items_atscope(
237 items: Dict[nodes.Item, None],
238 argkeys_cache: Dict[Scope, Dict[nodes.Item, Dict[FixtureArgKey, None]]],
239 items_by_argkey: Dict[Scope, Dict[FixtureArgKey, "Deque[nodes.Item]"]],
240 scope: Scope,
241 ) -> Dict[nodes.Item, None]:
242 if scope is Scope.Function or len(items) < 3:
243 return items
244 ignore: Set[Optional[FixtureArgKey]] = set()
245 items_deque = deque(items)
246 items_done: Dict[nodes.Item, None] = {}
247 scoped_items_by_argkey = items_by_argkey[scope]
248 scoped_argkeys_cache = argkeys_cache[scope]
249 while items_deque:
250 no_argkey_group: Dict[nodes.Item, None] = {}
251 slicing_argkey = None
252 while items_deque:
253 item = items_deque.popleft()
254 if item in items_done or item in no_argkey_group:
255 continue
256 argkeys = dict.fromkeys(
257 (k for k in scoped_argkeys_cache.get(item, []) if k not in ignore), None
258 )
259 if not argkeys:
260 no_argkey_group[item] = None
261 else:
262 slicing_argkey, _ = argkeys.popitem()
263 # We don't have to remove relevant items from later in the
264 # deque because they'll just be ignored.
265 matching_items = [
266 i for i in scoped_items_by_argkey[slicing_argkey] if i in items
267 ]
268 for i in reversed(matching_items):
269 fix_cache_order(i, argkeys_cache, items_by_argkey)
270 items_deque.appendleft(i)
271 break
272 if no_argkey_group:
273 no_argkey_group = reorder_items_atscope(
274 no_argkey_group, argkeys_cache, items_by_argkey, scope.next_lower()
275 )
276 for item in no_argkey_group:
277 items_done[item] = None
278 ignore.add(slicing_argkey)
279 return items_done
280
281
282 @dataclasses.dataclass(frozen=True)
283 class FuncFixtureInfo:
284 """Fixture-related information for a fixture-requesting item (e.g. test
285 function).
286
287 This is used to examine the fixtures which an item requests statically
288 (known during collection). This includes autouse fixtures, fixtures
289 requested by the `usefixtures` marker, fixtures requested in the function
290 parameters, and the transitive closure of these.
291
292 An item may also request fixtures dynamically (using `request.getfixturevalue`);
293 these are not reflected here.
294 """
295
296 __slots__ = ("argnames", "initialnames", "names_closure", "name2fixturedefs")
297
298 # Fixture names that the item requests directly by function parameters.
299 argnames: Tuple[str, ...]
300 # Fixture names that the item immediately requires. These include
301 # argnames + fixture names specified via usefixtures and via autouse=True in
302 # fixture definitions.
303 initialnames: Tuple[str, ...]
304 # The transitive closure of the fixture names that the item requires.
305 # Note: can't include dynamic dependencies (`request.getfixturevalue` calls).
306 names_closure: List[str]
307 # A map from a fixture name in the transitive closure to the FixtureDefs
308 # matching the name which are applicable to this function.
309 # There may be multiple overriding fixtures with the same name. The
310 # sequence is ordered from furthest to closes to the function.
311 name2fixturedefs: Dict[str, Sequence["FixtureDef[Any]"]]
312
313 def prune_dependency_tree(self) -> None:
314 """Recompute names_closure from initialnames and name2fixturedefs.
315
316 Can only reduce names_closure, which means that the new closure will
317 always be a subset of the old one. The order is preserved.
318
319 This method is needed because direct parametrization may shadow some
320 of the fixtures that were included in the originally built dependency
321 tree. In this way the dependency tree can get pruned, and the closure
322 of argnames may get reduced.
323 """
324 closure: Set[str] = set()
325 working_set = set(self.initialnames)
326 while working_set:
327 argname = working_set.pop()
328 # Argname may be something not included in the original names_closure,
329 # in which case we ignore it. This currently happens with pseudo
330 # FixtureDefs which wrap 'get_direct_param_fixture_func(request)'.
331 # So they introduce the new dependency 'request' which might have
332 # been missing in the original tree (closure).
333 if argname not in closure and argname in self.names_closure:
334 closure.add(argname)
335 if argname in self.name2fixturedefs:
336 working_set.update(self.name2fixturedefs[argname][-1].argnames)
337
338 self.names_closure[:] = sorted(closure, key=self.names_closure.index)
339
340
341 class FixtureRequest(abc.ABC):
342 """The type of the ``request`` fixture.
343
344 A request object gives access to the requesting test context and has a
345 ``param`` attribute in case the fixture is parametrized.
346 """
347
348 def __init__(
349 self,
350 pyfuncitem: "Function",
351 fixturename: Optional[str],
352 arg2fixturedefs: Dict[str, Sequence["FixtureDef[Any]"]],
353 fixture_defs: Dict[str, "FixtureDef[Any]"],
354 *,
355 _ispytest: bool = False,
356 ) -> None:
357 check_ispytest(_ispytest)
358 #: Fixture for which this request is being performed.
359 self.fixturename: Final = fixturename
360 self._pyfuncitem: Final = pyfuncitem
361 # The FixtureDefs for each fixture name requested by this item.
362 # Starts from the statically-known fixturedefs resolved during
363 # collection. Dynamically requested fixtures (using
364 # `request.getfixturevalue("foo")`) are added dynamically.
365 self._arg2fixturedefs: Final = arg2fixturedefs
366 # The evaluated argnames so far, mapping to the FixtureDef they resolved
367 # to.
368 self._fixture_defs: Final = fixture_defs
369 # Notes on the type of `param`:
370 # -`request.param` is only defined in parametrized fixtures, and will raise
371 # AttributeError otherwise. Python typing has no notion of "undefined", so
372 # this cannot be reflected in the type.
373 # - Technically `param` is only (possibly) defined on SubRequest, not
374 # FixtureRequest, but the typing of that is still in flux so this cheats.
375 # - In the future we might consider using a generic for the param type, but
376 # for now just using Any.
377 self.param: Any
378
379 @property
380 def _fixturemanager(self) -> "FixtureManager":
381 return self._pyfuncitem.session._fixturemanager
382
383 @property
384 @abc.abstractmethod
385 def _scope(self) -> Scope:
386 raise NotImplementedError()
387
388 @property
389 def scope(self) -> _ScopeName:
390 """Scope string, one of "function", "class", "module", "package", "session"."""
391 return self._scope.value
392
393 @abc.abstractmethod
394 def _check_scope(
395 self,
396 requested_fixturedef: Union["FixtureDef[object]", PseudoFixtureDef[object]],
397 requested_scope: Scope,
398 ) -> None:
399 raise NotImplementedError()
400
401 @property
402 def fixturenames(self) -> List[str]:
403 """Names of all active fixtures in this request."""
404 result = list(self._pyfuncitem.fixturenames)
405 result.extend(set(self._fixture_defs).difference(result))
406 return result
407
408 @property
409 @abc.abstractmethod
410 def node(self):
411 """Underlying collection node (depends on current request scope)."""
412 raise NotImplementedError()
413
414 @property
415 def config(self) -> Config:
416 """The pytest config object associated with this request."""
417 return self._pyfuncitem.config
418
419 @property
420 def function(self):
421 """Test function object if the request has a per-function scope."""
422 if self.scope != "function":
423 raise AttributeError(
424 f"function not available in {self.scope}-scoped context"
425 )
426 return self._pyfuncitem.obj
427
428 @property
429 def cls(self):
430 """Class (can be None) where the test function was collected."""
431 if self.scope not in ("class", "function"):
432 raise AttributeError(f"cls not available in {self.scope}-scoped context")
433 clscol = self._pyfuncitem.getparent(_pytest.python.Class)
434 if clscol:
435 return clscol.obj
436
437 @property
438 def instance(self):
439 """Instance (can be None) on which test function was collected."""
440 if self.scope != "function":
441 return None
442 return getattr(self._pyfuncitem, "instance", None)
443
444 @property
445 def module(self):
446 """Python module object where the test function was collected."""
447 if self.scope not in ("function", "class", "module"):
448 raise AttributeError(f"module not available in {self.scope}-scoped context")
449 mod = self._pyfuncitem.getparent(_pytest.python.Module)
450 assert mod is not None
451 return mod.obj
452
453 @property
454 def path(self) -> Path:
455 """Path where the test function was collected."""
456 if self.scope not in ("function", "class", "module", "package"):
457 raise AttributeError(f"path not available in {self.scope}-scoped context")
458 return self._pyfuncitem.path
459
460 @property
461 def keywords(self) -> MutableMapping[str, Any]:
462 """Keywords/markers dictionary for the underlying node."""
463 node: nodes.Node = self.node
464 return node.keywords
465
466 @property
467 def session(self) -> "Session":
468 """Pytest session object."""
469 return self._pyfuncitem.session
470
471 @abc.abstractmethod
472 def addfinalizer(self, finalizer: Callable[[], object]) -> None:
473 """Add finalizer/teardown function to be called without arguments after
474 the last test within the requesting test context finished execution."""
475 raise NotImplementedError()
476
477 def applymarker(self, marker: Union[str, MarkDecorator]) -> None:
478 """Apply a marker to a single test function invocation.
479
480 This method is useful if you don't want to have a keyword/marker
481 on all function invocations.
482
483 :param marker:
484 An object created by a call to ``pytest.mark.NAME(...)``.
485 """
486 self.node.add_marker(marker)
487
488 def raiseerror(self, msg: Optional[str]) -> NoReturn:
489 """Raise a FixtureLookupError exception.
490
491 :param msg:
492 An optional custom error message.
493 """
494 raise FixtureLookupError(None, self, msg)
495
496 def getfixturevalue(self, argname: str) -> Any:
497 """Dynamically run a named fixture function.
498
499 Declaring fixtures via function argument is recommended where possible.
500 But if you can only decide whether to use another fixture at test
501 setup time, you may use this function to retrieve it inside a fixture
502 or test function body.
503
504 This method can be used during the test setup phase or the test run
505 phase, but during the test teardown phase a fixture's value may not
506 be available.
507
508 :param argname:
509 The fixture name.
510 :raises pytest.FixtureLookupError:
511 If the given fixture could not be found.
512 """
513 # Note that in addition to the use case described in the docstring,
514 # getfixturevalue() is also called by pytest itself during item and fixture
515 # setup to evaluate the fixtures that are requested statically
516 # (using function parameters, autouse, etc).
517
518 fixturedef = self._get_active_fixturedef(argname)
519 assert fixturedef.cached_result is not None, (
520 f'The fixture value for "{argname}" is not available. '
521 "This can happen when the fixture has already been torn down."
522 )
523 return fixturedef.cached_result[0]
524
525 def _iter_chain(self) -> Iterator["SubRequest"]:
526 """Yield all SubRequests in the chain, from self up.
527
528 Note: does *not* yield the TopRequest.
529 """
530 current = self
531 while isinstance(current, SubRequest):
532 yield current
533 current = current._parent_request
534
535 def _get_active_fixturedef(
536 self, argname: str
537 ) -> Union["FixtureDef[object]", PseudoFixtureDef[object]]:
538 if argname == "request":
539 cached_result = (self, [0], None)
540 return PseudoFixtureDef(cached_result, Scope.Function)
541
542 # If we already finished computing a fixture by this name in this item,
543 # return it.
544 fixturedef = self._fixture_defs.get(argname)
545 if fixturedef is not None:
546 self._check_scope(fixturedef, fixturedef._scope)
547 return fixturedef
548
549 # Find the appropriate fixturedef.
550 fixturedefs = self._arg2fixturedefs.get(argname, None)
551 if fixturedefs is None:
552 # We arrive here because of a dynamic call to
553 # getfixturevalue(argname) which was naturally
554 # not known at parsing/collection time.
555 fixturedefs = self._fixturemanager.getfixturedefs(argname, self._pyfuncitem)
556 if fixturedefs is not None:
557 self._arg2fixturedefs[argname] = fixturedefs
558 # No fixtures defined with this name.
559 if fixturedefs is None:
560 raise FixtureLookupError(argname, self)
561 # The are no fixtures with this name applicable for the function.
562 if not fixturedefs:
563 raise FixtureLookupError(argname, self)
564 # A fixture may override another fixture with the same name, e.g. a
565 # fixture in a module can override a fixture in a conftest, a fixture in
566 # a class can override a fixture in the module, and so on.
567 # An overriding fixture can request its own name (possibly indirectly);
568 # in this case it gets the value of the fixture it overrides, one level
569 # up.
570 # Check how many `argname`s deep we are, and take the next one.
571 # `fixturedefs` is sorted from furthest to closest, so use negative
572 # indexing to go in reverse.
573 index = -1
574 for request in self._iter_chain():
575 if request.fixturename == argname:
576 index -= 1
577 # If already consumed all of the available levels, fail.
578 if -index > len(fixturedefs):
579 raise FixtureLookupError(argname, self)
580 fixturedef = fixturedefs[index]
581
582 # Prepare a SubRequest object for calling the fixture.
583 try:
584 callspec = self._pyfuncitem.callspec
585 except AttributeError:
586 callspec = None
587 if callspec is not None and argname in callspec.params:
588 param = callspec.params[argname]
589 param_index = callspec.indices[argname]
590 # The parametrize invocation scope overrides the fixture's scope.
591 scope = callspec._arg2scope[argname]
592 else:
593 param = NOTSET
594 param_index = 0
595 scope = fixturedef._scope
596 self._check_fixturedef_without_param(fixturedef)
597 self._check_scope(fixturedef, scope)
598 subrequest = SubRequest(
599 self, scope, param, param_index, fixturedef, _ispytest=True
600 )
601
602 # Make sure the fixture value is cached, running it if it isn't
603 fixturedef.execute(request=subrequest)
604
605 self._fixture_defs[argname] = fixturedef
606 return fixturedef
607
608 def _check_fixturedef_without_param(self, fixturedef: "FixtureDef[object]") -> None:
609 """Check that this request is allowed to execute this fixturedef without
610 a param."""
611 funcitem = self._pyfuncitem
612 has_params = fixturedef.params is not None
613 fixtures_not_supported = getattr(funcitem, "nofuncargs", False)
614 if has_params and fixtures_not_supported:
615 msg = (
616 f"{funcitem.name} does not support fixtures, maybe unittest.TestCase subclass?\n"
617 f"Node id: {funcitem.nodeid}\n"
618 f"Function type: {type(funcitem).__name__}"
619 )
620 fail(msg, pytrace=False)
621 if has_params:
622 frame = inspect.stack()[3]
623 frameinfo = inspect.getframeinfo(frame[0])
624 source_path = absolutepath(frameinfo.filename)
625 source_lineno = frameinfo.lineno
626 try:
627 source_path_str = str(source_path.relative_to(funcitem.config.rootpath))
628 except ValueError:
629 source_path_str = str(source_path)
630 location = getlocation(fixturedef.func, funcitem.config.rootpath)
631 msg = (
632 "The requested fixture has no parameter defined for test:\n"
633 f" {funcitem.nodeid}\n\n"
634 f"Requested fixture '{fixturedef.argname}' defined in:\n"
635 f"{location}\n\n"
636 f"Requested here:\n"
637 f"{source_path_str}:{source_lineno}"
638 )
639 fail(msg, pytrace=False)
640
641 def _get_fixturestack(self) -> List["FixtureDef[Any]"]:
642 values = [request._fixturedef for request in self._iter_chain()]
643 values.reverse()
644 return values
645
646
647 @final
648 class TopRequest(FixtureRequest):
649 """The type of the ``request`` fixture in a test function."""
650
651 def __init__(self, pyfuncitem: "Function", *, _ispytest: bool = False) -> None:
652 super().__init__(
653 fixturename=None,
654 pyfuncitem=pyfuncitem,
655 arg2fixturedefs=pyfuncitem._fixtureinfo.name2fixturedefs.copy(),
656 fixture_defs={},
657 _ispytest=_ispytest,
658 )
659
660 @property
661 def _scope(self) -> Scope:
662 return Scope.Function
663
664 def _check_scope(
665 self,
666 requested_fixturedef: Union["FixtureDef[object]", PseudoFixtureDef[object]],
667 requested_scope: Scope,
668 ) -> None:
669 # TopRequest always has function scope so always valid.
670 pass
671
672 @property
673 def node(self):
674 return self._pyfuncitem
675
676 def __repr__(self) -> str:
677 return "<FixtureRequest for %r>" % (self.node)
678
679 def _fillfixtures(self) -> None:
680 item = self._pyfuncitem
681 for argname in item.fixturenames:
682 if argname not in item.funcargs:
683 item.funcargs[argname] = self.getfixturevalue(argname)
684
685 def addfinalizer(self, finalizer: Callable[[], object]) -> None:
686 self.node.addfinalizer(finalizer)
687
688
689 @final
690 class SubRequest(FixtureRequest):
691 """The type of the ``request`` fixture in a fixture function requested
692 (transitively) by a test function."""
693
694 def __init__(
695 self,
696 request: FixtureRequest,
697 scope: Scope,
698 param: Any,
699 param_index: int,
700 fixturedef: "FixtureDef[object]",
701 *,
702 _ispytest: bool = False,
703 ) -> None:
704 super().__init__(
705 pyfuncitem=request._pyfuncitem,
706 fixturename=fixturedef.argname,
707 fixture_defs=request._fixture_defs,
708 arg2fixturedefs=request._arg2fixturedefs,
709 _ispytest=_ispytest,
710 )
711 self._parent_request: Final[FixtureRequest] = request
712 self._scope_field: Final = scope
713 self._fixturedef: Final[FixtureDef[object]] = fixturedef
714 if param is not NOTSET:
715 self.param = param
716 self.param_index: Final = param_index
717
718 def __repr__(self) -> str:
719 return f"<SubRequest {self.fixturename!r} for {self._pyfuncitem!r}>"
720
721 @property
722 def _scope(self) -> Scope:
723 return self._scope_field
724
725 @property
726 def node(self):
727 scope = self._scope
728 if scope is Scope.Function:
729 # This might also be a non-function Item despite its attribute name.
730 node: Optional[nodes.Node] = self._pyfuncitem
731 elif scope is Scope.Package:
732 node = get_scope_package(self._pyfuncitem, self._fixturedef)
733 else:
734 node = get_scope_node(self._pyfuncitem, scope)
735 if node is None and scope is Scope.Class:
736 # Fallback to function item itself.
737 node = self._pyfuncitem
738 assert node, f'Could not obtain a node for scope "{scope}" for function {self._pyfuncitem!r}'
739 return node
740
741 def _check_scope(
742 self,
743 requested_fixturedef: Union["FixtureDef[object]", PseudoFixtureDef[object]],
744 requested_scope: Scope,
745 ) -> None:
746 if isinstance(requested_fixturedef, PseudoFixtureDef):
747 return
748 if self._scope > requested_scope:
749 # Try to report something helpful.
750 argname = requested_fixturedef.argname
751 fixture_stack = "\n".join(
752 self._format_fixturedef_line(fixturedef)
753 for fixturedef in self._get_fixturestack()
754 )
755 requested_fixture = self._format_fixturedef_line(requested_fixturedef)
756 fail(
757 f"ScopeMismatch: You tried to access the {requested_scope.value} scoped "
758 f"fixture {argname} with a {self._scope.value} scoped request object. "
759 f"Requesting fixture stack:\n{fixture_stack}\n"
760 f"Requested fixture:\n{requested_fixture}",
761 pytrace=False,
762 )
763
764 def _format_fixturedef_line(self, fixturedef: "FixtureDef[object]") -> str:
765 factory = fixturedef.func
766 path, lineno = getfslineno(factory)
767 if isinstance(path, Path):
768 path = bestrelpath(self._pyfuncitem.session.path, path)
769 signature = inspect.signature(factory)
770 return f"{path}:{lineno + 1}: def {factory.__name__}{signature}"
771
772 def addfinalizer(self, finalizer: Callable[[], object]) -> None:
773 self._fixturedef.addfinalizer(finalizer)
774
775
776 @final
777 class FixtureLookupError(LookupError):
778 """Could not return a requested fixture (missing or invalid)."""
779
780 def __init__(
781 self, argname: Optional[str], request: FixtureRequest, msg: Optional[str] = None
782 ) -> None:
783 self.argname = argname
784 self.request = request
785 self.fixturestack = request._get_fixturestack()
786 self.msg = msg
787
788 def formatrepr(self) -> "FixtureLookupErrorRepr":
789 tblines: List[str] = []
790 addline = tblines.append
791 stack = [self.request._pyfuncitem.obj]
792 stack.extend(map(lambda x: x.func, self.fixturestack))
793 msg = self.msg
794 if msg is not None:
795 # The last fixture raise an error, let's present
796 # it at the requesting side.
797 stack = stack[:-1]
798 for function in stack:
799 fspath, lineno = getfslineno(function)
800 try:
801 lines, _ = inspect.getsourcelines(get_real_func(function))
802 except (OSError, IndexError, TypeError):
803 error_msg = "file %s, line %s: source code not available"
804 addline(error_msg % (fspath, lineno + 1))
805 else:
806 addline(f"file {fspath}, line {lineno + 1}")
807 for i, line in enumerate(lines):
808 line = line.rstrip()
809 addline(" " + line)
810 if line.lstrip().startswith("def"):
811 break
812
813 if msg is None:
814 fm = self.request._fixturemanager
815 available = set()
816 parent = self.request._pyfuncitem.parent
817 assert parent is not None
818 for name, fixturedefs in fm._arg2fixturedefs.items():
819 faclist = list(fm._matchfactories(fixturedefs, parent))
820 if faclist:
821 available.add(name)
822 if self.argname in available:
823 msg = (
824 f" recursive dependency involving fixture '{self.argname}' detected"
825 )
826 else:
827 msg = f"fixture '{self.argname}' not found"
828 msg += "\n available fixtures: {}".format(", ".join(sorted(available)))
829 msg += "\n use 'pytest --fixtures [testpath]' for help on them."
830
831 return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname)
832
833
834 class FixtureLookupErrorRepr(TerminalRepr):
835 def __init__(
836 self,
837 filename: Union[str, "os.PathLike[str]"],
838 firstlineno: int,
839 tblines: Sequence[str],
840 errorstring: str,
841 argname: Optional[str],
842 ) -> None:
843 self.tblines = tblines
844 self.errorstring = errorstring
845 self.filename = filename
846 self.firstlineno = firstlineno
847 self.argname = argname
848
849 def toterminal(self, tw: TerminalWriter) -> None:
850 # tw.line("FixtureLookupError: %s" %(self.argname), red=True)
851 for tbline in self.tblines:
852 tw.line(tbline.rstrip())
853 lines = self.errorstring.split("\n")
854 if lines:
855 tw.line(
856 f"{FormattedExcinfo.fail_marker} {lines[0].strip()}",
857 red=True,
858 )
859 for line in lines[1:]:
860 tw.line(
861 f"{FormattedExcinfo.flow_marker} {line.strip()}",
862 red=True,
863 )
864 tw.line()
865 tw.line("%s:%d" % (os.fspath(self.filename), self.firstlineno + 1))
866
867
868 def call_fixture_func(
869 fixturefunc: "_FixtureFunc[FixtureValue]", request: FixtureRequest, kwargs
870 ) -> FixtureValue:
871 if is_generator(fixturefunc):
872 fixturefunc = cast(
873 Callable[..., Generator[FixtureValue, None, None]], fixturefunc
874 )
875 generator = fixturefunc(**kwargs)
876 try:
877 fixture_result = next(generator)
878 except StopIteration:
879 raise ValueError(f"{request.fixturename} did not yield a value") from None
880 finalizer = functools.partial(_teardown_yield_fixture, fixturefunc, generator)
881 request.addfinalizer(finalizer)
882 else:
883 fixturefunc = cast(Callable[..., FixtureValue], fixturefunc)
884 fixture_result = fixturefunc(**kwargs)
885 return fixture_result
886
887
888 def _teardown_yield_fixture(fixturefunc, it) -> None:
889 """Execute the teardown of a fixture function by advancing the iterator
890 after the yield and ensure the iteration ends (if not it means there is
891 more than one yield in the function)."""
892 try:
893 next(it)
894 except StopIteration:
895 pass
896 else:
897 fs, lineno = getfslineno(fixturefunc)
898 fail(
899 f"fixture function has more than one 'yield':\n\n"
900 f"{Source(fixturefunc).indent()}\n"
901 f"{fs}:{lineno + 1}",
902 pytrace=False,
903 )
904
905
906 def _eval_scope_callable(
907 scope_callable: Callable[[str, Config], _ScopeName],
908 fixture_name: str,
909 config: Config,
910 ) -> _ScopeName:
911 try:
912 # Type ignored because there is no typing mechanism to specify
913 # keyword arguments, currently.
914 result = scope_callable(fixture_name=fixture_name, config=config) # type: ignore[call-arg]
915 except Exception as e:
916 raise TypeError(
917 f"Error evaluating {scope_callable} while defining fixture '{fixture_name}'.\n"
918 "Expected a function with the signature (*, fixture_name, config)"
919 ) from e
920 if not isinstance(result, str):
921 fail(
922 f"Expected {scope_callable} to return a 'str' while defining fixture '{fixture_name}', but it returned:\n"
923 f"{result!r}",
924 pytrace=False,
925 )
926 return result
927
928
929 @final
930 class FixtureDef(Generic[FixtureValue]):
931 """A container for a fixture definition.
932
933 Note: At this time, only explicitly documented fields and methods are
934 considered public stable API.
935 """
936
937 def __init__(
938 self,
939 config: Config,
940 baseid: Optional[str],
941 argname: str,
942 func: "_FixtureFunc[FixtureValue]",
943 scope: Union[Scope, _ScopeName, Callable[[str, Config], _ScopeName], None],
944 params: Optional[Sequence[object]],
945 ids: Optional[
946 Union[Tuple[Optional[object], ...], Callable[[Any], Optional[object]]]
947 ] = None,
948 *,
949 _ispytest: bool = False,
950 ) -> None:
951 check_ispytest(_ispytest)
952 # The "base" node ID for the fixture.
953 #
954 # This is a node ID prefix. A fixture is only available to a node (e.g.
955 # a `Function` item) if the fixture's baseid is a nodeid of a parent of
956 # node.
957 #
958 # For a fixture found in a Collector's object (e.g. a `Module`s module,
959 # a `Class`'s class), the baseid is the Collector's nodeid.
960 #
961 # For a fixture found in a conftest plugin, the baseid is the conftest's
962 # directory path relative to the rootdir.
963 #
964 # For other plugins, the baseid is the empty string (always matches).
965 self.baseid: Final = baseid or ""
966 # Whether the fixture was found from a node or a conftest in the
967 # collection tree. Will be false for fixtures defined in non-conftest
968 # plugins.
969 self.has_location: Final = baseid is not None
970 # The fixture factory function.
971 self.func: Final = func
972 # The name by which the fixture may be requested.
973 self.argname: Final = argname
974 if scope is None:
975 scope = Scope.Function
976 elif callable(scope):
977 scope = _eval_scope_callable(scope, argname, config)
978 if isinstance(scope, str):
979 scope = Scope.from_user(
980 scope, descr=f"Fixture '{func.__name__}'", where=baseid
981 )
982 self._scope: Final = scope
983 # If the fixture is directly parametrized, the parameter values.
984 self.params: Final = params
985 # If the fixture is directly parametrized, a tuple of explicit IDs to
986 # assign to the parameter values, or a callable to generate an ID given
987 # a parameter value.
988 self.ids: Final = ids
989 # The names requested by the fixtures.
990 self.argnames: Final = getfuncargnames(func, name=argname)
991 # If the fixture was executed, the current value of the fixture.
992 # Can change if the fixture is executed with different parameters.
993 self.cached_result: Optional[_FixtureCachedResult[FixtureValue]] = None
994 self._finalizers: Final[List[Callable[[], object]]] = []
995
996 @property
997 def scope(self) -> _ScopeName:
998 """Scope string, one of "function", "class", "module", "package", "session"."""
999 return self._scope.value
1000
1001 def addfinalizer(self, finalizer: Callable[[], object]) -> None:
1002 self._finalizers.append(finalizer)
1003
1004 def finish(self, request: SubRequest) -> None:
1005 exceptions: List[BaseException] = []
1006 while self._finalizers:
1007 fin = self._finalizers.pop()
1008 try:
1009 fin()
1010 except BaseException as e:
1011 exceptions.append(e)
1012 node = request.node
1013 node.ihook.pytest_fixture_post_finalizer(fixturedef=self, request=request)
1014 # Even if finalization fails, we invalidate the cached fixture
1015 # value and remove all finalizers because they may be bound methods
1016 # which will keep instances alive.
1017 self.cached_result = None
1018 self._finalizers.clear()
1019 if len(exceptions) == 1:
1020 raise exceptions[0]
1021 elif len(exceptions) > 1:
1022 msg = f'errors while tearing down fixture "{self.argname}" of {node}'
1023 raise BaseExceptionGroup(msg, exceptions[::-1])
1024
1025 def execute(self, request: SubRequest) -> FixtureValue:
1026 """Return the value of this fixture, executing it if not cached."""
1027 # Ensure that the dependent fixtures requested by this fixture are loaded.
1028 # This needs to be done before checking if we have a cached value, since
1029 # if a dependent fixture has their cache invalidated, e.g. due to
1030 # parametrization, they finalize themselves and fixtures depending on it
1031 # (which will likely include this fixture) setting `self.cached_result = None`.
1032 # See #4871
1033 requested_fixtures_that_should_finalize_us = []
1034 for argname in self.argnames:
1035 fixturedef = request._get_active_fixturedef(argname)
1036 # Saves requested fixtures in a list so we later can add our finalizer
1037 # to them, ensuring that if a requested fixture gets torn down we get torn
1038 # down first. This is generally handled by SetupState, but still currently
1039 # needed when this fixture is not parametrized but depends on a parametrized
1040 # fixture.
1041 if not isinstance(fixturedef, PseudoFixtureDef):
1042 requested_fixtures_that_should_finalize_us.append(fixturedef)
1043
1044 # Check for (and return) cached value/exception.
1045 my_cache_key = self.cache_key(request)
1046 if self.cached_result is not None:
1047 cache_key = self.cached_result[1]
1048 # note: comparison with `==` can fail (or be expensive) for e.g.
1049 # numpy arrays (#6497).
1050 if my_cache_key is cache_key:
1051 if self.cached_result[2] is not None:
1052 exc = self.cached_result[2]
1053 raise exc
1054 else:
1055 result = self.cached_result[0]
1056 return result
1057 # We have a previous but differently parametrized fixture instance
1058 # so we need to tear it down before creating a new one.
1059 self.finish(request)
1060 assert self.cached_result is None
1061
1062 # Add finalizer to requested fixtures we saved previously.
1063 # We make sure to do this after checking for cached value to avoid
1064 # adding our finalizer multiple times. (#12135)
1065 finalizer = functools.partial(self.finish, request=request)
1066 for parent_fixture in requested_fixtures_that_should_finalize_us:
1067 parent_fixture.addfinalizer(finalizer)
1068
1069 ihook = request.node.ihook
1070 try:
1071 # Setup the fixture, run the code in it, and cache the value
1072 # in self.cached_result
1073 result = ihook.pytest_fixture_setup(fixturedef=self, request=request)
1074 finally:
1075 # schedule our finalizer, even if the setup failed
1076 request.node.addfinalizer(finalizer)
1077
1078 return result
1079
1080 def cache_key(self, request: SubRequest) -> object:
1081 return getattr(request, "param", None)
1082
1083 def __repr__(self) -> str:
1084 return f"<FixtureDef argname={self.argname!r} scope={self.scope!r} baseid={self.baseid!r}>"
1085
1086
1087 def resolve_fixture_function(
1088 fixturedef: FixtureDef[FixtureValue], request: FixtureRequest
1089 ) -> "_FixtureFunc[FixtureValue]":
1090 """Get the actual callable that can be called to obtain the fixture
1091 value."""
1092 fixturefunc = fixturedef.func
1093 # The fixture function needs to be bound to the actual
1094 # request.instance so that code working with "fixturedef" behaves
1095 # as expected.
1096 instance = request.instance
1097 if instance is not None:
1098 # Handle the case where fixture is defined not in a test class, but some other class
1099 # (for example a plugin class with a fixture), see #2270.
1100 if hasattr(fixturefunc, "__self__") and not isinstance(
1101 instance,
1102 fixturefunc.__self__.__class__,
1103 ):
1104 return fixturefunc
1105 fixturefunc = getimfunc(fixturedef.func)
1106 if fixturefunc != fixturedef.func:
1107 fixturefunc = fixturefunc.__get__(instance)
1108 return fixturefunc
1109
1110
1111 def pytest_fixture_setup(
1112 fixturedef: FixtureDef[FixtureValue], request: SubRequest
1113 ) -> FixtureValue:
1114 """Execution of fixture setup."""
1115 kwargs = {}
1116 for argname in fixturedef.argnames:
1117 kwargs[argname] = request.getfixturevalue(argname)
1118
1119 fixturefunc = resolve_fixture_function(fixturedef, request)
1120 my_cache_key = fixturedef.cache_key(request)
1121 try:
1122 result = call_fixture_func(fixturefunc, request, kwargs)
1123 except TEST_OUTCOME as e:
1124 if isinstance(e, skip.Exception):
1125 # The test requested a fixture which caused a skip.
1126 # Don't show the fixture as the skip location, as then the user
1127 # wouldn't know which test skipped.
1128 e._use_item_location = True
1129 fixturedef.cached_result = (None, my_cache_key, e)
1130 raise
1131 fixturedef.cached_result = (result, my_cache_key, None)
1132 return result
1133
1134
1135 def wrap_function_to_error_out_if_called_directly(
1136 function: FixtureFunction,
1137 fixture_marker: "FixtureFunctionMarker",
1138 ) -> FixtureFunction:
1139 """Wrap the given fixture function so we can raise an error about it being called directly,
1140 instead of used as an argument in a test function."""
1141 name = fixture_marker.name or function.__name__
1142 message = (
1143 f'Fixture "{name}" called directly. Fixtures are not meant to be called directly,\n'
1144 "but are created automatically when test functions request them as parameters.\n"
1145 "See https://docs.pytest.org/en/stable/explanation/fixtures.html for more information about fixtures, and\n"
1146 "https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly about how to update your code."
1147 )
1148
1149 @functools.wraps(function)
1150 def result(*args, **kwargs):
1151 fail(message, pytrace=False)
1152
1153 # Keep reference to the original function in our own custom attribute so we don't unwrap
1154 # further than this point and lose useful wrappings like @mock.patch (#3774).
1155 result.__pytest_wrapped__ = _PytestWrapper(function) # type: ignore[attr-defined]
1156
1157 return cast(FixtureFunction, result)
1158
1159
1160 @final
1161 @dataclasses.dataclass(frozen=True)
1162 class FixtureFunctionMarker:
1163 scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]"
1164 params: Optional[Tuple[object, ...]]
1165 autouse: bool = False
1166 ids: Optional[
1167 Union[Tuple[Optional[object], ...], Callable[[Any], Optional[object]]]
1168 ] = None
1169 name: Optional[str] = None
1170
1171 _ispytest: dataclasses.InitVar[bool] = False
1172
1173 def __post_init__(self, _ispytest: bool) -> None:
1174 check_ispytest(_ispytest)
1175
1176 def __call__(self, function: FixtureFunction) -> FixtureFunction:
1177 if inspect.isclass(function):
1178 raise ValueError("class fixtures not supported (maybe in the future)")
1179
1180 if getattr(function, "_pytestfixturefunction", False):
1181 raise ValueError(
1182 f"@pytest.fixture is being applied more than once to the same function {function.__name__!r}"
1183 )
1184
1185 if hasattr(function, "pytestmark"):
1186 warnings.warn(MARKED_FIXTURE, stacklevel=2)
1187
1188 function = wrap_function_to_error_out_if_called_directly(function, self)
1189
1190 name = self.name or function.__name__
1191 if name == "request":
1192 location = getlocation(function)
1193 fail(
1194 f"'request' is a reserved word for fixtures, use another name:\n {location}",
1195 pytrace=False,
1196 )
1197
1198 # Type ignored because https://github.com/python/mypy/issues/2087.
1199 function._pytestfixturefunction = self # type: ignore[attr-defined]
1200 return function
1201
1202
1203 @overload
1204 def fixture(
1205 fixture_function: FixtureFunction,
1206 *,
1207 scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = ...,
1208 params: Optional[Iterable[object]] = ...,
1209 autouse: bool = ...,
1210 ids: Optional[
1211 Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]]
1212 ] = ...,
1213 name: Optional[str] = ...,
1214 ) -> FixtureFunction: ...
1215
1216
1217 @overload
1218 def fixture(
1219 fixture_function: None = ...,
1220 *,
1221 scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = ...,
1222 params: Optional[Iterable[object]] = ...,
1223 autouse: bool = ...,
1224 ids: Optional[
1225 Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]]
1226 ] = ...,
1227 name: Optional[str] = None,
1228 ) -> FixtureFunctionMarker: ...
1229
1230
1231 def fixture(
1232 fixture_function: Optional[FixtureFunction] = None,
1233 *,
1234 scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = "function",
1235 params: Optional[Iterable[object]] = None,
1236 autouse: bool = False,
1237 ids: Optional[
1238 Union[Sequence[Optional[object]], Callable[[Any], Optional[object]]]
1239 ] = None,
1240 name: Optional[str] = None,
1241 ) -> Union[FixtureFunctionMarker, FixtureFunction]:
1242 """Decorator to mark a fixture factory function.
1243
1244 This decorator can be used, with or without parameters, to define a
1245 fixture function.
1246
1247 The name of the fixture function can later be referenced to cause its
1248 invocation ahead of running tests: test modules or classes can use the
1249 ``pytest.mark.usefixtures(fixturename)`` marker.
1250
1251 Test functions can directly use fixture names as input arguments in which
1252 case the fixture instance returned from the fixture function will be
1253 injected.
1254
1255 Fixtures can provide their values to test functions using ``return`` or
1256 ``yield`` statements. When using ``yield`` the code block after the
1257 ``yield`` statement is executed as teardown code regardless of the test
1258 outcome, and must yield exactly once.
1259
1260 :param scope:
1261 The scope for which this fixture is shared; one of ``"function"``
1262 (default), ``"class"``, ``"module"``, ``"package"`` or ``"session"``.
1263
1264 This parameter may also be a callable which receives ``(fixture_name, config)``
1265 as parameters, and must return a ``str`` with one of the values mentioned above.
1266
1267 See :ref:`dynamic scope` in the docs for more information.
1268
1269 :param params:
1270 An optional list of parameters which will cause multiple invocations
1271 of the fixture function and all of the tests using it. The current
1272 parameter is available in ``request.param``.
1273
1274 :param autouse:
1275 If True, the fixture func is activated for all tests that can see it.
1276 If False (the default), an explicit reference is needed to activate
1277 the fixture.
1278
1279 :param ids:
1280 Sequence of ids each corresponding to the params so that they are
1281 part of the test id. If no ids are provided they will be generated
1282 automatically from the params.
1283
1284 :param name:
1285 The name of the fixture. This defaults to the name of the decorated
1286 function. If a fixture is used in the same module in which it is
1287 defined, the function name of the fixture will be shadowed by the
1288 function arg that requests the fixture; one way to resolve this is to
1289 name the decorated function ``fixture_<fixturename>`` and then use
1290 ``@pytest.fixture(name='<fixturename>')``.
1291 """
1292 fixture_marker = FixtureFunctionMarker(
1293 scope=scope,
1294 params=tuple(params) if params is not None else None,
1295 autouse=autouse,
1296 ids=None if ids is None else ids if callable(ids) else tuple(ids),
1297 name=name,
1298 _ispytest=True,
1299 )
1300
1301 # Direct decoration.
1302 if fixture_function:
1303 return fixture_marker(fixture_function)
1304
1305 return fixture_marker
1306
1307
1308 def yield_fixture(
1309 fixture_function=None,
1310 *args,
1311 scope="function",
1312 params=None,
1313 autouse=False,
1314 ids=None,
1315 name=None,
1316 ):
1317 """(Return a) decorator to mark a yield-fixture factory function.
1318
1319 .. deprecated:: 3.0
1320 Use :py:func:`pytest.fixture` directly instead.
1321 """
1322 warnings.warn(YIELD_FIXTURE, stacklevel=2)
1323 return fixture(
1324 fixture_function,
1325 *args,
1326 scope=scope,
1327 params=params,
1328 autouse=autouse,
1329 ids=ids,
1330 name=name,
1331 )
1332
1333
1334 @fixture(scope="session")
1335 def pytestconfig(request: FixtureRequest) -> Config:
1336 """Session-scoped fixture that returns the session's :class:`pytest.Config`
1337 object.
1338
1339 Example::
1340
1341 def test_foo(pytestconfig):
1342 if pytestconfig.getoption("verbose") > 0:
1343 ...
1344
1345 """
1346 return request.config
1347
1348
1349 def pytest_addoption(parser: Parser) -> None:
1350 parser.addini(
1351 "usefixtures",
1352 type="args",
1353 default=[],
1354 help="List of default fixtures to be used with this project",
1355 )
1356 group = parser.getgroup("general")
1357 group.addoption(
1358 "--fixtures",
1359 "--funcargs",
1360 action="store_true",
1361 dest="showfixtures",
1362 default=False,
1363 help="Show available fixtures, sorted by plugin appearance "
1364 "(fixtures with leading '_' are only shown with '-v')",
1365 )
1366 group.addoption(
1367 "--fixtures-per-test",
1368 action="store_true",
1369 dest="show_fixtures_per_test",
1370 default=False,
1371 help="Show fixtures per test",
1372 )
1373
1374
1375 def pytest_cmdline_main(config: Config) -> Optional[Union[int, ExitCode]]:
1376 if config.option.showfixtures:
1377 showfixtures(config)
1378 return 0
1379 if config.option.show_fixtures_per_test:
1380 show_fixtures_per_test(config)
1381 return 0
1382 return None
1383
1384
1385 def _get_direct_parametrize_args(node: nodes.Node) -> Set[str]:
1386 """Return all direct parametrization arguments of a node, so we don't
1387 mistake them for fixtures.
1388
1389 Check https://github.com/pytest-dev/pytest/issues/5036.
1390
1391 These things are done later as well when dealing with parametrization
1392 so this could be improved.
1393 """
1394 parametrize_argnames: Set[str] = set()
1395 for marker in node.iter_markers(name="parametrize"):
1396 if not marker.kwargs.get("indirect", False):
1397 p_argnames, _ = ParameterSet._parse_parametrize_args(
1398 *marker.args, **marker.kwargs
1399 )
1400 parametrize_argnames.update(p_argnames)
1401 return parametrize_argnames
1402
1403
1404 def deduplicate_names(*seqs: Iterable[str]) -> Tuple[str, ...]:
1405 """De-duplicate the sequence of names while keeping the original order."""
1406 # Ideally we would use a set, but it does not preserve insertion order.
1407 return tuple(dict.fromkeys(name for seq in seqs for name in seq))
1408
1409
1410 class FixtureManager:
1411 """pytest fixture definitions and information is stored and managed
1412 from this class.
1413
1414 During collection fm.parsefactories() is called multiple times to parse
1415 fixture function definitions into FixtureDef objects and internal
1416 data structures.
1417
1418 During collection of test functions, metafunc-mechanics instantiate
1419 a FuncFixtureInfo object which is cached per node/func-name.
1420 This FuncFixtureInfo object is later retrieved by Function nodes
1421 which themselves offer a fixturenames attribute.
1422
1423 The FuncFixtureInfo object holds information about fixtures and FixtureDefs
1424 relevant for a particular function. An initial list of fixtures is
1425 assembled like this:
1426
1427 - ini-defined usefixtures
1428 - autouse-marked fixtures along the collection chain up from the function
1429 - usefixtures markers at module/class/function level
1430 - test function funcargs
1431
1432 Subsequently the funcfixtureinfo.fixturenames attribute is computed
1433 as the closure of the fixtures needed to setup the initial fixtures,
1434 i.e. fixtures needed by fixture functions themselves are appended
1435 to the fixturenames list.
1436
1437 Upon the test-setup phases all fixturenames are instantiated, retrieved
1438 by a lookup of their FuncFixtureInfo.
1439 """
1440
1441 def __init__(self, session: "Session") -> None:
1442 self.session = session
1443 self.config: Config = session.config
1444 # Maps a fixture name (argname) to all of the FixtureDefs in the test
1445 # suite/plugins defined with this name. Populated by parsefactories().
1446 # TODO: The order of the FixtureDefs list of each arg is significant,
1447 # explain.
1448 self._arg2fixturedefs: Final[Dict[str, List[FixtureDef[Any]]]] = {}
1449 self._holderobjseen: Final[Set[object]] = set()
1450 # A mapping from a nodeid to a list of autouse fixtures it defines.
1451 self._nodeid_autousenames: Final[Dict[str, List[str]]] = {
1452 "": self.config.getini("usefixtures"),
1453 }
1454 session.config.pluginmanager.register(self, "funcmanage")
1455
1456 def getfixtureinfo(
1457 self,
1458 node: nodes.Item,
1459 func: Optional[Callable[..., object]],
1460 cls: Optional[type],
1461 ) -> FuncFixtureInfo:
1462 """Calculate the :class:`FuncFixtureInfo` for an item.
1463
1464 If ``func`` is None, or if the item sets an attribute
1465 ``nofuncargs = True``, then ``func`` is not examined at all.
1466
1467 :param node:
1468 The item requesting the fixtures.
1469 :param func:
1470 The item's function.
1471 :param cls:
1472 If the function is a method, the method's class.
1473 """
1474 if func is not None and not getattr(node, "nofuncargs", False):
1475 argnames = getfuncargnames(func, name=node.name, cls=cls)
1476 else:
1477 argnames = ()
1478 usefixturesnames = self._getusefixturesnames(node)
1479 autousenames = self._getautousenames(node)
1480 initialnames = deduplicate_names(autousenames, usefixturesnames, argnames)
1481
1482 direct_parametrize_args = _get_direct_parametrize_args(node)
1483
1484 names_closure, arg2fixturedefs = self.getfixtureclosure(
1485 parentnode=node,
1486 initialnames=initialnames,
1487 ignore_args=direct_parametrize_args,
1488 )
1489
1490 return FuncFixtureInfo(argnames, initialnames, names_closure, arg2fixturedefs)
1491
1492 def pytest_plugin_registered(self, plugin: _PluggyPlugin, plugin_name: str) -> None:
1493 # Fixtures defined in conftest plugins are only visible to within the
1494 # conftest's directory. This is unlike fixtures in non-conftest plugins
1495 # which have global visibility. So for conftests, construct the base
1496 # nodeid from the plugin name (which is the conftest path).
1497 if plugin_name and plugin_name.endswith("conftest.py"):
1498 # Note: we explicitly do *not* use `plugin.__file__` here -- The
1499 # difference is that plugin_name has the correct capitalization on
1500 # case-insensitive systems (Windows) and other normalization issues
1501 # (issue #11816).
1502 conftestpath = absolutepath(plugin_name)
1503 try:
1504 nodeid = str(conftestpath.parent.relative_to(self.config.rootpath))
1505 except ValueError:
1506 nodeid = ""
1507 if nodeid == ".":
1508 nodeid = ""
1509 if os.sep != nodes.SEP:
1510 nodeid = nodeid.replace(os.sep, nodes.SEP)
1511 else:
1512 nodeid = None
1513
1514 self.parsefactories(plugin, nodeid)
1515
1516 def _getautousenames(self, node: nodes.Node) -> Iterator[str]:
1517 """Return the names of autouse fixtures applicable to node."""
1518 for parentnode in node.listchain():
1519 basenames = self._nodeid_autousenames.get(parentnode.nodeid)
1520 if basenames:
1521 yield from basenames
1522
1523 def _getusefixturesnames(self, node: nodes.Item) -> Iterator[str]:
1524 """Return the names of usefixtures fixtures applicable to node."""
1525 for mark in node.iter_markers(name="usefixtures"):
1526 yield from mark.args
1527
1528 def getfixtureclosure(
1529 self,
1530 parentnode: nodes.Node,
1531 initialnames: Tuple[str, ...],
1532 ignore_args: AbstractSet[str],
1533 ) -> Tuple[List[str], Dict[str, Sequence[FixtureDef[Any]]]]:
1534 # Collect the closure of all fixtures, starting with the given
1535 # fixturenames as the initial set. As we have to visit all
1536 # factory definitions anyway, we also return an arg2fixturedefs
1537 # mapping so that the caller can reuse it and does not have
1538 # to re-discover fixturedefs again for each fixturename
1539 # (discovering matching fixtures for a given name/node is expensive).
1540
1541 fixturenames_closure = list(initialnames)
1542
1543 arg2fixturedefs: Dict[str, Sequence[FixtureDef[Any]]] = {}
1544 lastlen = -1
1545 while lastlen != len(fixturenames_closure):
1546 lastlen = len(fixturenames_closure)
1547 for argname in fixturenames_closure:
1548 if argname in ignore_args:
1549 continue
1550 if argname in arg2fixturedefs:
1551 continue
1552 fixturedefs = self.getfixturedefs(argname, parentnode)
1553 if fixturedefs:
1554 arg2fixturedefs[argname] = fixturedefs
1555 for arg in fixturedefs[-1].argnames:
1556 if arg not in fixturenames_closure:
1557 fixturenames_closure.append(arg)
1558
1559 def sort_by_scope(arg_name: str) -> Scope:
1560 try:
1561 fixturedefs = arg2fixturedefs[arg_name]
1562 except KeyError:
1563 return Scope.Function
1564 else:
1565 return fixturedefs[-1]._scope
1566
1567 fixturenames_closure.sort(key=sort_by_scope, reverse=True)
1568 return fixturenames_closure, arg2fixturedefs
1569
1570 def pytest_generate_tests(self, metafunc: "Metafunc") -> None:
1571 """Generate new tests based on parametrized fixtures used by the given metafunc"""
1572
1573 def get_parametrize_mark_argnames(mark: Mark) -> Sequence[str]:
1574 args, _ = ParameterSet._parse_parametrize_args(*mark.args, **mark.kwargs)
1575 return args
1576
1577 for argname in metafunc.fixturenames:
1578 # Get the FixtureDefs for the argname.
1579 fixture_defs = metafunc._arg2fixturedefs.get(argname)
1580 if not fixture_defs:
1581 # Will raise FixtureLookupError at setup time if not parametrized somewhere
1582 # else (e.g @pytest.mark.parametrize)
1583 continue
1584
1585 # If the test itself parametrizes using this argname, give it
1586 # precedence.
1587 if any(
1588 argname in get_parametrize_mark_argnames(mark)
1589 for mark in metafunc.definition.iter_markers("parametrize")
1590 ):
1591 continue
1592
1593 # In the common case we only look at the fixture def with the
1594 # closest scope (last in the list). But if the fixture overrides
1595 # another fixture, while requesting the super fixture, keep going
1596 # in case the super fixture is parametrized (#1953).
1597 for fixturedef in reversed(fixture_defs):
1598 # Fixture is parametrized, apply it and stop.
1599 if fixturedef.params is not None:
1600 metafunc.parametrize(
1601 argname,
1602 fixturedef.params,
1603 indirect=True,
1604 scope=fixturedef.scope,
1605 ids=fixturedef.ids,
1606 )
1607 break
1608
1609 # Not requesting the overridden super fixture, stop.
1610 if argname not in fixturedef.argnames:
1611 break
1612
1613 # Try next super fixture, if any.
1614
1615 def pytest_collection_modifyitems(self, items: List[nodes.Item]) -> None:
1616 # Separate parametrized setups.
1617 items[:] = reorder_items(items)
1618
1619 def _register_fixture(
1620 self,
1621 *,
1622 name: str,
1623 func: "_FixtureFunc[object]",
1624 nodeid: Optional[str],
1625 scope: Union[
1626 Scope, _ScopeName, Callable[[str, Config], _ScopeName], None
1627 ] = "function",
1628 params: Optional[Sequence[object]] = None,
1629 ids: Optional[
1630 Union[Tuple[Optional[object], ...], Callable[[Any], Optional[object]]]
1631 ] = None,
1632 autouse: bool = False,
1633 ) -> None:
1634 """Register a fixture
1635
1636 :param name:
1637 The fixture's name.
1638 :param func:
1639 The fixture's implementation function.
1640 :param nodeid:
1641 The visibility of the fixture. The fixture will be available to the
1642 node with this nodeid and its children in the collection tree.
1643 None means that the fixture is visible to the entire collection tree,
1644 e.g. a fixture defined for general use in a plugin.
1645 :param scope:
1646 The fixture's scope.
1647 :param params:
1648 The fixture's parametrization params.
1649 :param ids:
1650 The fixture's IDs.
1651 :param autouse:
1652 Whether this is an autouse fixture.
1653 """
1654 fixture_def = FixtureDef(
1655 config=self.config,
1656 baseid=nodeid,
1657 argname=name,
1658 func=func,
1659 scope=scope,
1660 params=params,
1661 ids=ids,
1662 _ispytest=True,
1663 )
1664
1665 faclist = self._arg2fixturedefs.setdefault(name, [])
1666 if fixture_def.has_location:
1667 faclist.append(fixture_def)
1668 else:
1669 # fixturedefs with no location are at the front
1670 # so this inserts the current fixturedef after the
1671 # existing fixturedefs from external plugins but
1672 # before the fixturedefs provided in conftests.
1673 i = len([f for f in faclist if not f.has_location])
1674 faclist.insert(i, fixture_def)
1675 if autouse:
1676 self._nodeid_autousenames.setdefault(nodeid or "", []).append(name)
1677
1678 @overload
1679 def parsefactories(
1680 self,
1681 node_or_obj: nodes.Node,
1682 ) -> None:
1683 raise NotImplementedError()
1684
1685 @overload
1686 def parsefactories(
1687 self,
1688 node_or_obj: object,
1689 nodeid: Optional[str],
1690 ) -> None:
1691 raise NotImplementedError()
1692
1693 def parsefactories(
1694 self,
1695 node_or_obj: Union[nodes.Node, object],
1696 nodeid: Union[str, NotSetType, None] = NOTSET,
1697 ) -> None:
1698 """Collect fixtures from a collection node or object.
1699
1700 Found fixtures are parsed into `FixtureDef`s and saved.
1701
1702 If `node_or_object` is a collection node (with an underlying Python
1703 object), the node's object is traversed and the node's nodeid is used to
1704 determine the fixtures' visibility. `nodeid` must not be specified in
1705 this case.
1706
1707 If `node_or_object` is an object (e.g. a plugin), the object is
1708 traversed and the given `nodeid` is used to determine the fixtures'
1709 visibility. `nodeid` must be specified in this case; None and "" mean
1710 total visibility.
1711 """
1712 if nodeid is not NOTSET:
1713 holderobj = node_or_obj
1714 else:
1715 assert isinstance(node_or_obj, nodes.Node)
1716 holderobj = cast(object, node_or_obj.obj) # type: ignore[attr-defined]
1717 assert isinstance(node_or_obj.nodeid, str)
1718 nodeid = node_or_obj.nodeid
1719 if holderobj in self._holderobjseen:
1720 return
1721
1722 self._holderobjseen.add(holderobj)
1723 for name in dir(holderobj):
1724 # The attribute can be an arbitrary descriptor, so the attribute
1725 # access below can raise. safe_getatt() ignores such exceptions.
1726 obj = safe_getattr(holderobj, name, None)
1727 marker = getfixturemarker(obj)
1728 if not isinstance(marker, FixtureFunctionMarker):
1729 # Magic globals with __getattr__ might have got us a wrong
1730 # fixture attribute.
1731 continue
1732
1733 if marker.name:
1734 name = marker.name
1735
1736 # During fixture definition we wrap the original fixture function
1737 # to issue a warning if called directly, so here we unwrap it in
1738 # order to not emit the warning when pytest itself calls the
1739 # fixture function.
1740 func = get_real_method(obj, holderobj)
1741
1742 self._register_fixture(
1743 name=name,
1744 nodeid=nodeid,
1745 func=func,
1746 scope=marker.scope,
1747 params=marker.params,
1748 ids=marker.ids,
1749 autouse=marker.autouse,
1750 )
1751
1752 def getfixturedefs(
1753 self, argname: str, node: nodes.Node
1754 ) -> Optional[Sequence[FixtureDef[Any]]]:
1755 """Get FixtureDefs for a fixture name which are applicable
1756 to a given node.
1757
1758 Returns None if there are no fixtures at all defined with the given
1759 name. (This is different from the case in which there are fixtures
1760 with the given name, but none applicable to the node. In this case,
1761 an empty result is returned).
1762
1763 :param argname: Name of the fixture to search for.
1764 :param node: The requesting Node.
1765 """
1766 try:
1767 fixturedefs = self._arg2fixturedefs[argname]
1768 except KeyError:
1769 return None
1770 return tuple(self._matchfactories(fixturedefs, node))
1771
1772 def _matchfactories(
1773 self, fixturedefs: Iterable[FixtureDef[Any]], node: nodes.Node
1774 ) -> Iterator[FixtureDef[Any]]:
1775 parentnodeids = {n.nodeid for n in node.iter_parents()}
1776 for fixturedef in fixturedefs:
1777 if fixturedef.baseid in parentnodeids:
1778 yield fixturedef
1779
1780
1781 def show_fixtures_per_test(config: Config) -> Union[int, ExitCode]:
1782 from _pytest.main import wrap_session
1783
1784 return wrap_session(config, _show_fixtures_per_test)
1785
1786
1787 _PYTEST_DIR = Path(_pytest.__file__).parent
1788
1789
1790 def _pretty_fixture_path(invocation_dir: Path, func) -> str:
1791 loc = Path(getlocation(func, invocation_dir))
1792 prefix = Path("...", "_pytest")
1793 try:
1794 return str(prefix / loc.relative_to(_PYTEST_DIR))
1795 except ValueError:
1796 return bestrelpath(invocation_dir, loc)
1797
1798
1799 def _show_fixtures_per_test(config: Config, session: "Session") -> None:
1800 import _pytest.config
1801
1802 session.perform_collect()
1803 invocation_dir = config.invocation_params.dir
1804 tw = _pytest.config.create_terminal_writer(config)
1805 verbose = config.getvalue("verbose")
1806
1807 def get_best_relpath(func) -> str:
1808 loc = getlocation(func, invocation_dir)
1809 return bestrelpath(invocation_dir, Path(loc))
1810
1811 def write_fixture(fixture_def: FixtureDef[object]) -> None:
1812 argname = fixture_def.argname
1813 if verbose <= 0 and argname.startswith("_"):
1814 return
1815 prettypath = _pretty_fixture_path(invocation_dir, fixture_def.func)
1816 tw.write(f"{argname}", green=True)
1817 tw.write(f" -- {prettypath}", yellow=True)
1818 tw.write("\n")
1819 fixture_doc = inspect.getdoc(fixture_def.func)
1820 if fixture_doc:
1821 write_docstring(
1822 tw, fixture_doc.split("\n\n")[0] if verbose <= 0 else fixture_doc
1823 )
1824 else:
1825 tw.line(" no docstring available", red=True)
1826
1827 def write_item(item: nodes.Item) -> None:
1828 # Not all items have _fixtureinfo attribute.
1829 info: Optional[FuncFixtureInfo] = getattr(item, "_fixtureinfo", None)
1830 if info is None or not info.name2fixturedefs:
1831 # This test item does not use any fixtures.
1832 return
1833 tw.line()
1834 tw.sep("-", f"fixtures used by {item.name}")
1835 # TODO: Fix this type ignore.
1836 tw.sep("-", f"({get_best_relpath(item.function)})") # type: ignore[attr-defined]
1837 # dict key not used in loop but needed for sorting.
1838 for _, fixturedefs in sorted(info.name2fixturedefs.items()):
1839 assert fixturedefs is not None
1840 if not fixturedefs:
1841 continue
1842 # Last item is expected to be the one used by the test item.
1843 write_fixture(fixturedefs[-1])
1844
1845 for session_item in session.items:
1846 write_item(session_item)
1847
1848
1849 def showfixtures(config: Config) -> Union[int, ExitCode]:
1850 from _pytest.main import wrap_session
1851
1852 return wrap_session(config, _showfixtures_main)
1853
1854
1855 def _showfixtures_main(config: Config, session: "Session") -> None:
1856 import _pytest.config
1857
1858 session.perform_collect()
1859 invocation_dir = config.invocation_params.dir
1860 tw = _pytest.config.create_terminal_writer(config)
1861 verbose = config.getvalue("verbose")
1862
1863 fm = session._fixturemanager
1864
1865 available = []
1866 seen: Set[Tuple[str, str]] = set()
1867
1868 for argname, fixturedefs in fm._arg2fixturedefs.items():
1869 assert fixturedefs is not None
1870 if not fixturedefs:
1871 continue
1872 for fixturedef in fixturedefs:
1873 loc = getlocation(fixturedef.func, invocation_dir)
1874 if (fixturedef.argname, loc) in seen:
1875 continue
1876 seen.add((fixturedef.argname, loc))
1877 available.append(
1878 (
1879 len(fixturedef.baseid),
1880 fixturedef.func.__module__,
1881 _pretty_fixture_path(invocation_dir, fixturedef.func),
1882 fixturedef.argname,
1883 fixturedef,
1884 )
1885 )
1886
1887 available.sort()
1888 currentmodule = None
1889 for baseid, module, prettypath, argname, fixturedef in available:
1890 if currentmodule != module:
1891 if not module.startswith("_pytest."):
1892 tw.line()
1893 tw.sep("-", f"fixtures defined from {module}")
1894 currentmodule = module
1895 if verbose <= 0 and argname.startswith("_"):
1896 continue
1897 tw.write(f"{argname}", green=True)
1898 if fixturedef.scope != "function":
1899 tw.write(" [%s scope]" % fixturedef.scope, cyan=True)
1900 tw.write(f" -- {prettypath}", yellow=True)
1901 tw.write("\n")
1902 doc = inspect.getdoc(fixturedef.func)
1903 if doc:
1904 write_docstring(tw, doc.split("\n\n")[0] if verbose <= 0 else doc)
1905 else:
1906 tw.line(" no docstring available", red=True)
1907 tw.line()
1908
1909
1910 def write_docstring(tw: TerminalWriter, doc: str, indent: str = " ") -> None:
1911 for line in doc.split("\n"):
1912 tw.line(indent + line)