Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/doc/en/reference/fixtures.rst

raw
1 .. _reference-fixtures:
2 .. _fixture:
3 .. _fixtures:
4 .. _`@pytest.fixture`:
5 .. _`pytest.fixture`:
6
7
8 Fixtures reference
9 ========================================================
10
11 .. seealso:: :ref:`about-fixtures`
12 .. seealso:: :ref:`how-to-fixtures`
13
14 .. _`Dependency injection`: https://en.wikipedia.org/wiki/Dependency_injection
15
16
17 Built-in fixtures
18 -----------------
19
20 :ref:`Fixtures <fixtures-api>` are defined using the :ref:`@pytest.fixture
21 <pytest.fixture-api>` decorator. Pytest has several useful built-in fixtures:
22
23 :fixture:`capfd`
24 Capture, as text, output to file descriptors ``1`` and ``2``.
25
26 :fixture:`capfdbinary`
27 Capture, as bytes, output to file descriptors ``1`` and ``2``.
28
29 :fixture:`caplog`
30 Control logging and access log entries.
31
32 :fixture:`capsys`
33 Capture, as text, output to ``sys.stdout`` and ``sys.stderr``.
34
35 :fixture:`capsysbinary`
36 Capture, as bytes, output to ``sys.stdout`` and ``sys.stderr``.
37
38 :fixture:`cache`
39 Store and retrieve values across pytest runs.
40
41 :fixture:`doctest_namespace`
42 Provide a dict injected into the doctests namespace.
43
44 :fixture:`monkeypatch`
45 Temporarily modify classes, functions, dictionaries,
46 ``os.environ``, and other objects.
47
48 :fixture:`pytestconfig`
49 Access to configuration values, pluginmanager and plugin hooks.
50
51 :fixture:`record_property`
52 Add extra properties to the test.
53
54 :fixture:`record_testsuite_property`
55 Add extra properties to the test suite.
56
57 :fixture:`recwarn`
58 Record warnings emitted by test functions.
59
60 :fixture:`request`
61 Provide information on the executing test function.
62
63 :fixture:`testdir`
64 Provide a temporary test directory to aid in running, and
65 testing, pytest plugins.
66
67 :fixture:`tmp_path`
68 Provide a :class:`pathlib.Path` object to a temporary directory
69 which is unique to each test function.
70
71 :fixture:`tmp_path_factory`
72 Make session-scoped temporary directories and return
73 :class:`pathlib.Path` objects.
74
75 :fixture:`tmpdir`
76 Provide a `py.path.local <https://py.readthedocs.io/en/latest/path.html>`_ object to a temporary
77 directory which is unique to each test function;
78 replaced by :fixture:`tmp_path`.
79
80 :fixture:`tmpdir_factory`
81 Make session-scoped temporary directories and return
82 ``py.path.local`` objects;
83 replaced by :fixture:`tmp_path_factory`.
84
85
86 .. _`conftest.py`:
87 .. _`conftest`:
88
89 Fixture availability
90 ---------------------
91
92 Fixture availability is determined from the perspective of the test. A fixture
93 is only available for tests to request if they are in the scope that fixture is
94 defined in. If a fixture is defined inside a class, it can only be requested by
95 tests inside that class. But if a fixture is defined inside the global scope of
96 the module, then every test in that module, even if it's defined inside a class,
97 can request it.
98
99 Similarly, a test can also only be affected by an autouse fixture if that test
100 is in the same scope that autouse fixture is defined in (see
101 :ref:`autouse order`).
102
103 A fixture can also request any other fixture, no matter where it's defined, so
104 long as the test requesting them can see all fixtures involved.
105
106 For example, here's a test file with a fixture (``outer``) that requests a
107 fixture (``inner``) from a scope it wasn't defined in:
108
109 .. literalinclude:: /example/fixtures/test_fixtures_request_different_scope.py
110
111 From the tests' perspectives, they have no problem seeing each of the fixtures
112 they're dependent on:
113
114 .. image:: /example/fixtures/test_fixtures_request_different_scope.*
115 :align: center
116
117 So when they run, ``outer`` will have no problem finding ``inner``, because
118 pytest searched from the tests' perspectives.
119
120 .. note::
121 The scope a fixture is defined in has no bearing on the order it will be
122 instantiated in: the order is mandated by the logic described
123 :ref:`here <fixture order>`.
124
125 ``conftest.py``: sharing fixtures across multiple files
126 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
127
128 The ``conftest.py`` file serves as a means of providing fixtures for an entire
129 directory. Fixtures defined in a ``conftest.py`` can be used by any test
130 in that package without needing to import them (pytest will automatically
131 discover them).
132
133 You can have multiple nested directories/packages containing your tests, and
134 each directory can have its own ``conftest.py`` with its own fixtures, adding on
135 to the ones provided by the ``conftest.py`` files in parent directories.
136
137 For example, given a test file structure like this:
138
139 ::
140
141 tests/
142 __init__.py
143
144 conftest.py
145 # content of tests/conftest.py
146 import pytest
147
148 @pytest.fixture
149 def order():
150 return []
151
152 @pytest.fixture
153 def top(order, innermost):
154 order.append("top")
155
156 test_top.py
157 # content of tests/test_top.py
158 import pytest
159
160 @pytest.fixture
161 def innermost(order):
162 order.append("innermost top")
163
164 def test_order(order, top):
165 assert order == ["innermost top", "top"]
166
167 subpackage/
168 __init__.py
169
170 conftest.py
171 # content of tests/subpackage/conftest.py
172 import pytest
173
174 @pytest.fixture
175 def mid(order):
176 order.append("mid subpackage")
177
178 test_subpackage.py
179 # content of tests/subpackage/test_subpackage.py
180 import pytest
181
182 @pytest.fixture
183 def innermost(order, mid):
184 order.append("innermost subpackage")
185
186 def test_order(order, top):
187 assert order == ["mid subpackage", "innermost subpackage", "top"]
188
189 The boundaries of the scopes can be visualized like this:
190
191 .. image:: /example/fixtures/fixture_availability.*
192 :align: center
193
194 The directories become their own sort of scope where fixtures that are defined
195 in a ``conftest.py`` file in that directory become available for that whole
196 scope.
197
198 Tests are allowed to search upward (stepping outside a circle) for fixtures, but
199 can never go down (stepping inside a circle) to continue their search. So
200 ``tests/subpackage/test_subpackage.py::test_order`` would be able to find the
201 ``innermost`` fixture defined in ``tests/subpackage/test_subpackage.py``, but
202 the one defined in ``tests/test_top.py`` would be unavailable to it because it
203 would have to step down a level (step inside a circle) to find it.
204
205 The first fixture the test finds is the one that will be used, so
206 :ref:`fixtures can be overridden <override fixtures>` if you need to change or
207 extend what one does for a particular scope.
208
209 You can also use the ``conftest.py`` file to implement
210 :ref:`local per-directory plugins <conftest.py plugins>`.
211
212 Fixtures from third-party plugins
213 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
214
215 Fixtures don't have to be defined in this structure to be available for tests,
216 though. They can also be provided by third-party plugins that are installed, and
217 this is how many pytest plugins operate. As long as those plugins are installed,
218 the fixtures they provide can be requested from anywhere in your test suite.
219
220 Because they're provided from outside the structure of your test suite,
221 third-party plugins don't really provide a scope like `conftest.py` files and
222 the directories in your test suite do. As a result, pytest will search for
223 fixtures stepping out through scopes as explained previously, only reaching
224 fixtures defined in plugins *last*.
225
226 For example, given the following file structure:
227
228 ::
229
230 tests/
231 __init__.py
232
233 conftest.py
234 # content of tests/conftest.py
235 import pytest
236
237 @pytest.fixture
238 def order():
239 return []
240
241 subpackage/
242 __init__.py
243
244 conftest.py
245 # content of tests/subpackage/conftest.py
246 import pytest
247
248 @pytest.fixture(autouse=True)
249 def mid(order, b_fix):
250 order.append("mid subpackage")
251
252 test_subpackage.py
253 # content of tests/subpackage/test_subpackage.py
254 import pytest
255
256 @pytest.fixture
257 def inner(order, mid, a_fix):
258 order.append("inner subpackage")
259
260 def test_order(order, inner):
261 assert order == ["b_fix", "mid subpackage", "a_fix", "inner subpackage"]
262
263 If ``plugin_a`` is installed and provides the fixture ``a_fix``, and
264 ``plugin_b`` is installed and provides the fixture ``b_fix``, then this is what
265 the test's search for fixtures would look like:
266
267 .. image:: /example/fixtures/fixture_availability_plugins.svg
268 :align: center
269
270 pytest will only search for ``a_fix`` and ``b_fix`` in the plugins after
271 searching for them first in the scopes inside ``tests/``.
272
273 .. note:
274
275 pytest can tell you what fixtures are available for a given test if you call
276 ``pytests`` along with the test's name (or the scope it's in), and provide
277 the ``--fixtures`` flag, e.g. ``pytest --fixtures test_something.py``
278 (fixtures with names that start with ``_`` will only be shown if you also
279 provide the ``-v`` flag).
280
281
282 .. _`fixture order`:
283
284 Fixture instantiation order
285 ---------------------------
286
287 When pytest wants to execute a test, once it knows what fixtures will be
288 executed, it has to figure out the order they'll be executed in. To do this, it
289 considers 3 factors:
290
291 1. scope
292 2. dependencies
293 3. autouse
294
295 Names of fixtures or tests, where they're defined, the order they're defined in,
296 and the order fixtures are requested in have no bearing on execution order
297 beyond coincidence. While pytest will try to make sure coincidences like these
298 stay consistent from run to run, it's not something that should be depended on.
299 If you want to control the order, it's safest to rely on these 3 things and make
300 sure dependencies are clearly established.
301
302 Higher-scoped fixtures are executed first
303 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
304
305 Within a function request for fixtures, those of higher-scopes (such as
306 ``session``) are executed before lower-scoped fixtures (such as ``function`` or
307 ``class``).
308
309 Here's an example:
310
311 .. literalinclude:: /example/fixtures/test_fixtures_order_scope.py
312
313 The test will pass because the larger scoped fixtures are executing first.
314
315 The order breaks down to this:
316
317 .. image:: /example/fixtures/test_fixtures_order_scope.*
318 :align: center
319
320 Fixtures of the same order execute based on dependencies
321 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
322
323 When a fixture requests another fixture, the other fixture is executed first.
324 So if fixture ``a`` requests fixture ``b``, fixture ``b`` will execute first,
325 because ``a`` depends on ``b`` and can't operate without it. Even if ``a``
326 doesn't need the result of ``b``, it can still request ``b`` if it needs to make
327 sure it is executed after ``b``.
328
329 For example:
330
331 .. literalinclude:: /example/fixtures/test_fixtures_order_dependencies.py
332
333 If we map out what depends on what, we get something that looks like this:
334
335 .. image:: /example/fixtures/test_fixtures_order_dependencies.*
336 :align: center
337
338 The rules provided by each fixture (as to what fixture(s) each one has to come
339 after) are comprehensive enough that it can be flattened to this:
340
341 .. image:: /example/fixtures/test_fixtures_order_dependencies_flat.*
342 :align: center
343
344 Enough information has to be provided through these requests in order for pytest
345 to be able to figure out a clear, linear chain of dependencies, and as a result,
346 an order of operations for a given test. If there's any ambiguity, and the order
347 of operations can be interpreted more than one way, you should assume pytest
348 could go with any one of those interpretations at any point.
349
350 For example, if ``d`` didn't request ``c``, i.e.the graph would look like this:
351
352 .. image:: /example/fixtures/test_fixtures_order_dependencies_unclear.*
353 :align: center
354
355 Because nothing requested ``c`` other than ``g``, and ``g`` also requests ``f``,
356 it's now unclear if ``c`` should go before/after ``f``, ``e``, or ``d``. The
357 only rules that were set for ``c`` is that it must execute after ``b`` and
358 before ``g``.
359
360 pytest doesn't know where ``c`` should go in the case, so it should be assumed
361 that it could go anywhere between ``g`` and ``b``.
362
363 This isn't necessarily bad, but it's something to keep in mind. If the order
364 they execute in could affect the behavior a test is targeting, or could
365 otherwise influence the result of a test, then the order should be defined
366 explicitly in a way that allows pytest to linearize/"flatten" that order.
367
368 .. _`autouse order`:
369
370 Autouse fixtures are executed first within their scope
371 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
372
373 Autouse fixtures are assumed to apply to every test that could reference them,
374 so they are executed before other fixtures in that scope. Fixtures that are
375 requested by autouse fixtures effectively become autouse fixtures themselves for
376 the tests that the real autouse fixture applies to.
377
378 So if fixture ``a`` is autouse and fixture ``b`` is not, but fixture ``a``
379 requests fixture ``b``, then fixture ``b`` will effectively be an autouse
380 fixture as well, but only for the tests that ``a`` applies to.
381
382 In the last example, the graph became unclear if ``d`` didn't request ``c``. But
383 if ``c`` was autouse, then ``b`` and ``a`` would effectively also be autouse
384 because ``c`` depends on them. As a result, they would all be shifted above
385 non-autouse fixtures within that scope.
386
387 So if the test file looked like this:
388
389 .. literalinclude:: /example/fixtures/test_fixtures_order_autouse.py
390
391 the graph would look like this:
392
393 .. image:: /example/fixtures/test_fixtures_order_autouse.*
394 :align: center
395
396 Because ``c`` can now be put above ``d`` in the graph, pytest can once again
397 linearize the graph to this:
398
399 .. image:: /example/fixtures/test_fixtures_order_autouse_flat.*
400 :align: center
401
402 In this example, ``c`` makes ``b`` and ``a`` effectively autouse fixtures as
403 well.
404
405 Be careful with autouse, though, as an autouse fixture will automatically
406 execute for every test that can reach it, even if they don't request it. For
407 example, consider this file:
408
409 .. literalinclude:: /example/fixtures/test_fixtures_order_autouse_multiple_scopes.py
410
411 Even though nothing in ``TestClassWithoutC1Request`` is requesting ``c1``, it still
412 is executed for the tests inside it anyway:
413
414 .. image:: /example/fixtures/test_fixtures_order_autouse_multiple_scopes.*
415 :align: center
416
417 But just because one autouse fixture requested a non-autouse fixture, that
418 doesn't mean the non-autouse fixture becomes an autouse fixture for all contexts
419 that it can apply to. It only effectively becomes an autouse fixture for the
420 contexts the real autouse fixture (the one that requested the non-autouse
421 fixture) can apply to.
422
423 For example, take a look at this test file:
424
425 .. literalinclude:: /example/fixtures/test_fixtures_order_autouse_temp_effects.py
426
427 It would break down to something like this:
428
429 .. image:: /example/fixtures/test_fixtures_order_autouse_temp_effects.*
430 :align: center
431
432 For ``test_req`` and ``test_no_req`` inside ``TestClassWithAutouse``, ``c3``
433 effectively makes ``c2`` an autouse fixture, which is why ``c2`` and ``c3`` are
434 executed for both tests, despite not being requested, and why ``c2`` and ``c3``
435 are executed before ``c1`` for ``test_req``.
436
437 If this made ``c2`` an *actual* autouse fixture, then ``c2`` would also execute
438 for the tests inside ``TestClassWithoutAutouse``, since they can reference
439 ``c2`` if they wanted to. But it doesn't, because from the perspective of the
440 ``TestClassWithoutAutouse`` tests, ``c2`` isn't an autouse fixture, since they
441 can't see ``c3``.
442
443
444 .. note:
445
446 pytest can tell you what order the fixtures will execute in for a given test
447 if you call ``pytests`` along with the test's name (or the scope it's in),
448 and provide the ``--setup-plan`` flag, e.g.
449 ``pytest --setup-plan test_something.py`` (fixtures with names that start
450 with ``_`` will only be shown if you also provide the ``-v`` flag).