Debian Codegraph @

doc/en/how-to/cache.rst

raw
1 .. _`cache_provider`:
2 .. _cache:
3
4
5 How to re-run failed tests and maintain state between test runs
6 ===============================================================
7
8
9
10 Usage
11 ---------
12
13 The plugin provides two command line options to rerun failures from the
14 last ``pytest`` invocation:
15
16 * :option:`--lf, --last-failed <--lf>` - to only re-run the failures.
17 * :option:`--ff, --failed-first <--ff>` - to run the failures first and then the rest of
18 the tests.
19
20 For cleanup (usually not needed), a :option:`--cache-clear` option allows to remove
21 all cross-session cache contents ahead of a test run.
22
23 Other plugins may access the `config.cache`_ object to set/get
24 **json encodable** values between ``pytest`` invocations.
25
26 .. note::
27
28 This plugin is enabled by default, but can be disabled if needed: see
29 :ref:`cmdunregister` (the internal name for this plugin is
30 ``cacheprovider``).
31
32
33 Rerunning only failures or failures first
34 -----------------------------------------------
35
36 First, let's create 50 test invocations of which only 2 fail:
37
38 .. code-block:: python
39
40 # content of test_50.py
41 import pytest
42
43
44 @pytest.mark.parametrize("i", range(50))
45 def test_num(i):
46 if i in (17, 25):
47 pytest.fail("bad luck")
48
49 If you run this for the first time you will see two failures:
50
51 .. code-block:: pytest
52
53 $ pytest -q
54 .................F.......F........................ [100%]
55 ================================= FAILURES =================================
56 _______________________________ test_num[17] _______________________________
57
58 i = 17
59
60 @pytest.mark.parametrize("i", range(50))
61 def test_num(i):
62 if i in (17, 25):
63 > pytest.fail("bad luck")
64 E Failed: bad luck
65
66 test_50.py:7: Failed
67 _______________________________ test_num[25] _______________________________
68
69 i = 25
70
71 @pytest.mark.parametrize("i", range(50))
72 def test_num(i):
73 if i in (17, 25):
74 > pytest.fail("bad luck")
75 E Failed: bad luck
76
77 test_50.py:7: Failed
78 ========================= short test summary info ==========================
79 FAILED test_50.py::test_num[17] - Failed: bad luck
80 FAILED test_50.py::test_num[25] - Failed: bad luck
81 2 failed, 48 passed in 0.12s
82
83 If you then run it with :option:`--lf`:
84
85 .. code-block:: pytest
86
87 $ pytest --lf
88 =========================== test session starts ============================
89 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
90 rootdir: /home/sweet/project
91 collected 2 items
92 run-last-failure: rerun previous 2 failures
93
94 test_50.py FF [100%]
95
96 ================================= FAILURES =================================
97 _______________________________ test_num[17] _______________________________
98
99 i = 17
100
101 @pytest.mark.parametrize("i", range(50))
102 def test_num(i):
103 if i in (17, 25):
104 > pytest.fail("bad luck")
105 E Failed: bad luck
106
107 test_50.py:7: Failed
108 _______________________________ test_num[25] _______________________________
109
110 i = 25
111
112 @pytest.mark.parametrize("i", range(50))
113 def test_num(i):
114 if i in (17, 25):
115 > pytest.fail("bad luck")
116 E Failed: bad luck
117
118 test_50.py:7: Failed
119 ========================= short test summary info ==========================
120 FAILED test_50.py::test_num[17] - Failed: bad luck
121 FAILED test_50.py::test_num[25] - Failed: bad luck
122 ============================ 2 failed in 0.12s =============================
123
124 You have run only the two failing tests from the last run, while the 48 passing
125 tests have not been run ("deselected").
126
127 Now, if you run with the :option:`--ff` option, all tests will be run but the first
128 previous failures will be executed first (as can be seen from the series
129 of ``FF`` and dots):
130
131 .. code-block:: pytest
132
133 $ pytest --ff
134 =========================== test session starts ============================
135 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
136 rootdir: /home/sweet/project
137 collected 50 items
138 run-last-failure: rerun previous 2 failures first
139
140 test_50.py FF................................................ [100%]
141
142 ================================= FAILURES =================================
143 _______________________________ test_num[17] _______________________________
144
145 i = 17
146
147 @pytest.mark.parametrize("i", range(50))
148 def test_num(i):
149 if i in (17, 25):
150 > pytest.fail("bad luck")
151 E Failed: bad luck
152
153 test_50.py:7: Failed
154 _______________________________ test_num[25] _______________________________
155
156 i = 25
157
158 @pytest.mark.parametrize("i", range(50))
159 def test_num(i):
160 if i in (17, 25):
161 > pytest.fail("bad luck")
162 E Failed: bad luck
163
164 test_50.py:7: Failed
165 ========================= short test summary info ==========================
166 FAILED test_50.py::test_num[17] - Failed: bad luck
167 FAILED test_50.py::test_num[25] - Failed: bad luck
168 ======================= 2 failed, 48 passed in 0.12s =======================
169
170 .. _`config.cache`:
171
172 New :option:`--nf, --new-first <--nf>` option: run new tests first followed by the rest
173 of the tests, in both cases tests are also sorted by the file modified time,
174 with more recent files coming first.
175
176 Behavior when no tests failed in the last run
177 ---------------------------------------------
178
179 The :option:`--lfnf, --last-failed-no-failures <--lfnf>` option governs the behavior of :option:`--last-failed`.
180 Determines whether to execute tests when there are no previously (known)
181 failures or when no cached ``lastfailed`` data was found.
182
183 There are two options:
184
185 * ``all``: when there are no known test failures, runs all tests (the full test suite). This is the default.
186 * ``none``: when there are no known test failures, just emits a message stating this and exit successfully.
187
188 Example:
189
190 .. code-block:: bash
191
192 pytest --last-failed --last-failed-no-failures all # runs the full test suite (default behavior)
193 pytest --last-failed --last-failed-no-failures none # runs no tests and exits successfully
194
195 The new config.cache object
196 --------------------------------
197
198 .. regendoc:wipe
199
200 Plugins or conftest.py support code can get a cached value using the
201 pytest ``config`` object. Here is a basic example plugin which
202 implements a :ref:`fixture <fixture>` which reuses previously created state
203 across pytest invocations:
204
205 .. code-block:: python
206
207 # content of test_caching.py
208 import pytest
209
210
211 def expensive_computation():
212 print("running expensive computation...")
213
214
215 @pytest.fixture
216 def mydata(pytestconfig):
217 cache = getattr(pytestconfig, "cache", None)
218 if cache is None:
219 # pytestconfig not having the cache attribute means the
220 # cache plugin is disabled.
221 expensive_computation()
222 return 42
223
224 val = cache.get("example/value", None)
225 if val is None:
226 expensive_computation()
227 val = 42
228 cache.set("example/value", val)
229 return val
230
231
232 def test_function(mydata):
233 assert mydata == 23
234
235 If you run this command for the first time, you can see the print statement:
236
237 .. code-block:: pytest
238
239 $ pytest -q
240 F [100%]
241 ================================= FAILURES =================================
242 ______________________________ test_function _______________________________
243
244 mydata = 42
245
246 def test_function(mydata):
247 > assert mydata == 23
248 E assert 42 == 23
249
250 test_caching.py:26: AssertionError
251 -------------------------- Captured stdout setup ---------------------------
252 running expensive computation...
253 ========================= short test summary info ==========================
254 FAILED test_caching.py::test_function - assert 42 == 23
255 1 failed in 0.12s
256
257 If you run it a second time, the value will be retrieved from
258 the cache and nothing will be printed:
259
260 .. code-block:: pytest
261
262 $ pytest -q
263 F [100%]
264 ================================= FAILURES =================================
265 ______________________________ test_function _______________________________
266
267 mydata = 42
268
269 def test_function(mydata):
270 > assert mydata == 23
271 E assert 42 == 23
272
273 test_caching.py:26: AssertionError
274 ========================= short test summary info ==========================
275 FAILED test_caching.py::test_function - assert 42 == 23
276 1 failed in 0.12s
277
278 See the :fixture:`config.cache fixture <cache>` for more details.
279
280
281 Inspecting Cache content
282 ------------------------
283
284 You can always peek at the content of the cache using the
285 :option:`--cache-show` command line option:
286
287 .. code-block:: pytest
288
289 $ pytest --cache-show
290 =========================== test session starts ============================
291 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
292 rootdir: /home/sweet/project
293 cachedir: /home/sweet/project/.pytest_cache
294 --------------------------- cache values for '*' ---------------------------
295 cache/lastfailed contains:
296 {'test_caching.py::test_function': True}
297 cache/nodeids contains:
298 ['test_caching.py::test_function']
299 example/value contains:
300 42
301
302 ========================== no tests ran in 0.12s ===========================
303
304 :option:`--cache-show` takes an optional argument to specify a glob pattern for
305 filtering:
306
307 .. code-block:: pytest
308
309 $ pytest --cache-show example/*
310 =========================== test session starts ============================
311 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
312 rootdir: /home/sweet/project
313 cachedir: /home/sweet/project/.pytest_cache
314 ----------------------- cache values for 'example/*' -----------------------
315 example/value contains:
316 42
317
318 ========================== no tests ran in 0.12s ===========================
319
320 Clearing Cache content
321 ----------------------
322
323 You can instruct pytest to clear all cache files and values
324 by adding the :option:`--cache-clear` option like this:
325
326 .. code-block:: bash
327
328 pytest --cache-clear
329
330 This is recommended for invocations from Continuous Integration
331 servers where isolation and correctness is more important
332 than speed.
333
334
335 .. _cache stepwise:
336
337 Stepwise
338 --------
339
340 As an alternative to :option:`--lf` :option:`-x`, especially for cases where you expect a large part of the test suite will fail, :option:`--sw, --stepwise <--sw>` allows you to fix them one at a time. The test suite will run until the first failure and then stop. At the next invocation, tests will continue from the last failing test and then run until the next failing test. You may use the :option:`--stepwise-skip` option to ignore one failing test and stop the test execution on the second failing test instead. This is useful if you get stuck on a failing test and just want to ignore it until later. Providing ``--stepwise-skip`` will also enable ``--stepwise`` implicitly.