Debian Codegraph @

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