Debian Codegraph @

testing/test_stepwise.py

raw
1 # mypy: disallow-untyped-defs
2 from __future__ import annotations
3
4 from collections.abc import Sequence
5 import json
6 from pathlib import Path
7
8 from _pytest.cacheprovider import Cache
9 from _pytest.monkeypatch import MonkeyPatch
10 from _pytest.pytester import Pytester
11 from _pytest.stepwise import STEPWISE_CACHE_DIR
12 import pytest
13
14
15 @pytest.fixture
16 def stepwise_pytester(pytester: Pytester) -> Pytester:
17 # Rather than having to modify our testfile between tests, we introduce
18 # a flag for whether or not the second test should fail.
19 pytester.makeconftest(
20 """
21 def pytest_addoption(parser):
22 group = parser.getgroup('general')
23 group.addoption('--fail', action='store_true', dest='fail')
24 group.addoption('--fail-last', action='store_true', dest='fail_last')
25 """
26 )
27
28 # Create a simple test suite.
29 pytester.makepyfile(
30 test_a="""
31 def test_success_before_fail():
32 assert 1
33
34 def test_fail_on_flag(request):
35 assert not request.config.getvalue('fail')
36
37 def test_success_after_fail():
38 assert 1
39
40 def test_fail_last_on_flag(request):
41 assert not request.config.getvalue('fail_last')
42
43 def test_success_after_last_fail():
44 assert 1
45 """
46 )
47
48 pytester.makepyfile(
49 test_b="""
50 def test_success():
51 assert 1
52 """
53 )
54
55 # customize cache directory so we don't use the tox's cache directory, which makes tests in this module flaky
56 pytester.makeini(
57 """
58 [pytest]
59 cache_dir = .cache
60 """
61 )
62
63 return pytester
64
65
66 @pytest.fixture
67 def error_pytester(pytester: Pytester) -> Pytester:
68 pytester.makepyfile(
69 test_a="""
70 def test_error(nonexisting_fixture):
71 assert 1
72
73 def test_success_after_fail():
74 assert 1
75 """
76 )
77
78 return pytester
79
80
81 @pytest.fixture
82 def broken_pytester(pytester: Pytester) -> Pytester:
83 pytester.makepyfile(
84 working_testfile="def test_proper(): assert 1", broken_testfile="foobar"
85 )
86 return pytester
87
88
89 def _strip_resource_warnings(lines: Sequence[str]) -> Sequence[str]:
90 # Strip unreliable ResourceWarnings, so no-output assertions on stderr can work.
91 # (https://github.com/pytest-dev/pytest/issues/5088)
92 return [
93 x
94 for x in lines
95 if not x.startswith(("Exception ignored in:", "ResourceWarning"))
96 ]
97
98
99 def test_run_without_stepwise(stepwise_pytester: Pytester) -> None:
100 result = stepwise_pytester.runpytest("-v", "--strict-markers", "--fail")
101 result.stdout.fnmatch_lines(["*test_success_before_fail PASSED*"])
102 result.stdout.fnmatch_lines(["*test_fail_on_flag FAILED*"])
103 result.stdout.fnmatch_lines(["*test_success_after_fail PASSED*"])
104
105
106 def test_stepwise_output_summary(pytester: Pytester) -> None:
107 pytester.makepyfile(
108 """
109 import pytest
110 @pytest.mark.parametrize("expected", [True, True, True, True, False])
111 def test_data(expected):
112 assert expected
113 """
114 )
115 result = pytester.runpytest("-v", "--stepwise")
116 result.stdout.fnmatch_lines(["stepwise: no previously failed tests, not skipping."])
117 result = pytester.runpytest("-v", "--stepwise")
118 result.stdout.fnmatch_lines(
119 [
120 "stepwise: skipping 4 already passed items (cache from * ago, use --sw-reset to discard).",
121 "*1 failed, 4 deselected*",
122 ]
123 )
124
125
126 def test_fail_and_continue_with_stepwise(stepwise_pytester: Pytester) -> None:
127 # Run the tests with a failing second test.
128 result = stepwise_pytester.runpytest(
129 "-v", "--strict-markers", "--stepwise", "--fail"
130 )
131 assert _strip_resource_warnings(result.stderr.lines) == []
132
133 stdout = result.stdout.str()
134 # Make sure we stop after first failing test.
135 assert "test_success_before_fail PASSED" in stdout
136 assert "test_fail_on_flag FAILED" in stdout
137 assert "test_success_after_fail" not in stdout
138
139 # "Fix" the test that failed in the last run and run it again.
140 result = stepwise_pytester.runpytest("-v", "--strict-markers", "--stepwise")
141 assert _strip_resource_warnings(result.stderr.lines) == []
142
143 stdout = result.stdout.str()
144 # Make sure the latest failing test runs and then continues.
145 assert "test_success_before_fail" not in stdout
146 assert "test_fail_on_flag PASSED" in stdout
147 assert "test_success_after_fail PASSED" in stdout
148
149
150 @pytest.mark.parametrize("stepwise_skip", ["--stepwise-skip", "--sw-skip"])
151 def test_run_with_skip_option(stepwise_pytester: Pytester, stepwise_skip: str) -> None:
152 result = stepwise_pytester.runpytest(
153 "-v",
154 "--strict-markers",
155 "--stepwise",
156 stepwise_skip,
157 "--fail",
158 "--fail-last",
159 )
160 assert _strip_resource_warnings(result.stderr.lines) == []
161
162 stdout = result.stdout.str()
163 # Make sure first fail is ignore and second fail stops the test run.
164 assert "test_fail_on_flag FAILED" in stdout
165 assert "test_success_after_fail PASSED" in stdout
166 assert "test_fail_last_on_flag FAILED" in stdout
167 assert "test_success_after_last_fail" not in stdout
168
169
170 def test_fail_on_errors(error_pytester: Pytester) -> None:
171 result = error_pytester.runpytest("-v", "--strict-markers", "--stepwise")
172
173 assert _strip_resource_warnings(result.stderr.lines) == []
174 stdout = result.stdout.str()
175
176 assert "test_error ERROR" in stdout
177 assert "test_success_after_fail" not in stdout
178
179
180 def test_change_testfile(stepwise_pytester: Pytester) -> None:
181 result = stepwise_pytester.runpytest(
182 "-v", "--strict-markers", "--stepwise", "--fail", "test_a.py"
183 )
184 assert _strip_resource_warnings(result.stderr.lines) == []
185
186 stdout = result.stdout.str()
187 assert "test_fail_on_flag FAILED" in stdout
188
189 # Make sure the second test run starts from the beginning, since the
190 # test to continue from does not exist in testfile_b.
191 result = stepwise_pytester.runpytest(
192 "-v", "--strict-markers", "--stepwise", "test_b.py"
193 )
194 assert _strip_resource_warnings(result.stderr.lines) == []
195
196 stdout = result.stdout.str()
197 assert "test_success PASSED" in stdout
198
199
200 @pytest.mark.parametrize("broken_first", [True, False])
201 def test_stop_on_collection_errors(
202 broken_pytester: Pytester, broken_first: bool
203 ) -> None:
204 """Stop during collection errors. Broken test first or broken test last
205 actually surfaced a bug (#5444), so we test both situations."""
206 files = ["working_testfile.py", "broken_testfile.py"]
207 if broken_first:
208 files.reverse()
209 result = broken_pytester.runpytest("-v", "--strict-markers", "--stepwise", *files)
210 result.stdout.fnmatch_lines("*error during collection*")
211
212
213 def test_xfail_handling(pytester: Pytester, monkeypatch: MonkeyPatch) -> None:
214 """Ensure normal xfail is ignored, and strict xfail interrupts the session in sw mode
215
216 (#5547)
217 """
218 monkeypatch.setattr("sys.dont_write_bytecode", True)
219
220 contents = """
221 import pytest
222 def test_a(): pass
223
224 @pytest.mark.xfail(strict={strict})
225 def test_b(): assert {assert_value}
226
227 def test_c(): pass
228 def test_d(): pass
229 """
230 pytester.makepyfile(contents.format(assert_value="0", strict="False"))
231 result = pytester.runpytest("--sw", "-v")
232 result.stdout.fnmatch_lines(
233 [
234 "*::test_a PASSED *",
235 "*::test_b XFAIL *",
236 "*::test_c PASSED *",
237 "*::test_d PASSED *",
238 "* 3 passed, 1 xfailed in *",
239 ]
240 )
241
242 pytester.makepyfile(contents.format(assert_value="1", strict="True"))
243 result = pytester.runpytest("--sw", "-v")
244 result.stdout.fnmatch_lines(
245 [
246 "*::test_a PASSED *",
247 "*::test_b FAILED *",
248 "* Interrupted*",
249 "* 1 failed, 1 passed in *",
250 ]
251 )
252
253 pytester.makepyfile(contents.format(assert_value="0", strict="True"))
254 result = pytester.runpytest("--sw", "-v")
255 result.stdout.fnmatch_lines(
256 [
257 "*::test_b XFAIL *",
258 "*::test_c PASSED *",
259 "*::test_d PASSED *",
260 "* 2 passed, 1 deselected, 1 xfailed in *",
261 ]
262 )
263
264
265 def test_stepwise_skip_is_independent(pytester: Pytester) -> None:
266 pytester.makepyfile(
267 """
268 def test_one():
269 assert False
270
271 def test_two():
272 assert False
273
274 def test_three():
275 assert False
276
277 """
278 )
279 result = pytester.runpytest("--tb", "no", "--stepwise-skip")
280 result.assert_outcomes(failed=2)
281 result.stdout.fnmatch_lines(
282 [
283 "FAILED test_stepwise_skip_is_independent.py::test_one - assert False",
284 "FAILED test_stepwise_skip_is_independent.py::test_two - assert False",
285 "*Interrupted: Test failed, continuing from this test next run.*",
286 ]
287 )
288
289
290 def test_sw_skip_help(pytester: Pytester) -> None:
291 result = pytester.runpytest("-h")
292 result.stdout.fnmatch_lines("*Implicitly enables --stepwise.")
293
294
295 def test_stepwise_xdist_dont_store_lastfailed(pytester: Pytester) -> None:
296 pytester.makefile(
297 ext=".ini",
298 pytest=f"[pytest]\ncache_dir = {pytester.path}\n",
299 )
300
301 pytester.makepyfile(
302 conftest="""
303 import pytest
304
305 @pytest.hookimpl(tryfirst=True)
306 def pytest_configure(config) -> None:
307 config.workerinput = True
308 """
309 )
310 pytester.makepyfile(
311 test_one="""
312 def test_one():
313 assert False
314 """
315 )
316 result = pytester.runpytest("--stepwise")
317 assert result.ret == pytest.ExitCode.INTERRUPTED
318
319 stepwise_cache_file = (
320 pytester.path / Cache._CACHE_PREFIX_VALUES / STEPWISE_CACHE_DIR
321 )
322 assert not Path(stepwise_cache_file).exists()
323
324
325 def test_disabled_stepwise_xdist_dont_clear_cache(pytester: Pytester) -> None:
326 pytester.makefile(
327 ext=".ini",
328 pytest=f"[pytest]\ncache_dir = {pytester.path}\n",
329 )
330
331 stepwise_cache_file = (
332 pytester.path / Cache._CACHE_PREFIX_VALUES / STEPWISE_CACHE_DIR
333 )
334 stepwise_cache_dir = stepwise_cache_file.parent
335 stepwise_cache_dir.mkdir(exist_ok=True, parents=True)
336
337 stepwise_cache_file_relative = f"{Cache._CACHE_PREFIX_VALUES}/{STEPWISE_CACHE_DIR}"
338
339 expected_value = '"test_one.py::test_one"'
340 content = {f"{stepwise_cache_file_relative}": expected_value}
341
342 pytester.makefile(ext="", **content)
343
344 pytester.makepyfile(
345 conftest="""
346 import pytest
347
348 @pytest.hookimpl(tryfirst=True)
349 def pytest_configure(config) -> None:
350 config.workerinput = True
351 """
352 )
353 pytester.makepyfile(
354 test_one="""
355 def test_one():
356 assert True
357 """
358 )
359 result = pytester.runpytest()
360 assert result.ret == 0
361
362 assert Path(stepwise_cache_file).exists()
363 with stepwise_cache_file.open(encoding="utf-8") as file_handle:
364 observed_value = file_handle.readlines()
365 assert [expected_value] == observed_value
366
367
368 def test_do_not_reset_cache_if_disabled(pytester: Pytester) -> None:
369 """
370 If pytest is run without --stepwise, do not clear the stepwise cache.
371
372 Keeping the cache around is important for this workflow:
373
374 1. Run tests with --stepwise
375 2. Stop at the failing test, and iterate over it changing the code and running it in isolation
376 (in the IDE for example).
377 3. Run tests with --stepwise again - at this point we expect to start from the failing test, which should now pass,
378 and continue with the next tests.
379 """
380 pytester.makepyfile(
381 """
382 def test_1(): pass
383 def test_2(): assert False
384 def test_3(): pass
385 """
386 )
387 result = pytester.runpytest("--stepwise")
388 result.stdout.fnmatch_lines(
389 [
390 "*::test_2 - assert False*",
391 "*failed, continuing from this test next run*",
392 "=* 1 failed, 1 passed in *",
393 ]
394 )
395
396 # Run a specific test without passing `--stepwise`.
397 result = pytester.runpytest("-k", "test_1")
398 result.stdout.fnmatch_lines(["*1 passed*"])
399
400 # Running with `--stepwise` should continue from the last failing test.
401 result = pytester.runpytest("--stepwise")
402 result.stdout.fnmatch_lines(
403 [
404 "stepwise: skipping 1 already passed items (cache from *, use --sw-reset to discard).",
405 "*::test_2 - assert False*",
406 "*failed, continuing from this test next run*",
407 "=* 1 failed, 1 deselected in *",
408 ]
409 )
410
411
412 def test_reset(pytester: Pytester) -> None:
413 pytester.makepyfile(
414 """
415 def test_1(): pass
416 def test_2(): assert False
417 def test_3(): pass
418 """
419 )
420 result = pytester.runpytest("--stepwise", "-v")
421 result.stdout.fnmatch_lines(
422 [
423 "stepwise: no previously failed tests, not skipping.",
424 "*::test_1 *PASSED*",
425 "*::test_2 *FAILED*",
426 "*failed, continuing from this test next run*",
427 "* 1 failed, 1 passed in *",
428 ]
429 )
430
431 result = pytester.runpytest("--stepwise", "-v")
432 result.stdout.fnmatch_lines(
433 [
434 "stepwise: skipping 1 already passed items (cache from *, use --sw-reset to discard).",
435 "*::test_2 *FAILED*",
436 "*failed, continuing from this test next run*",
437 "* 1 failed, 1 deselected in *",
438 ]
439 )
440
441 # Running with --stepwise-reset restarts the stepwise workflow.
442 result = pytester.runpytest("-v", "--stepwise-reset")
443 result.stdout.fnmatch_lines(
444 [
445 "stepwise: resetting state, not skipping.",
446 "*::test_1 *PASSED*",
447 "*::test_2 *FAILED*",
448 "*failed, continuing from this test next run*",
449 "* 1 failed, 1 passed in *",
450 ]
451 )
452
453
454 def test_change_test_count(pytester: Pytester) -> None:
455 # Run initially with 3 tests.
456 pytester.makepyfile(
457 """
458 def test_1(): pass
459 def test_2(): assert False
460 def test_3(): pass
461 """
462 )
463 result = pytester.runpytest("--stepwise", "-v")
464 result.stdout.fnmatch_lines(
465 [
466 "stepwise: no previously failed tests, not skipping.",
467 "*::test_1 *PASSED*",
468 "*::test_2 *FAILED*",
469 "*failed, continuing from this test next run*",
470 "* 1 failed, 1 passed in *",
471 ]
472 )
473
474 # Change the number of tests, which invalidates the test cache.
475 pytester.makepyfile(
476 """
477 def test_1(): pass
478 def test_2(): assert False
479 def test_3(): pass
480 def test_4(): pass
481 """
482 )
483 result = pytester.runpytest("--stepwise", "-v")
484 result.stdout.fnmatch_lines(
485 [
486 "stepwise: test count changed, not skipping (now 4 tests, previously 3).",
487 "*::test_1 *PASSED*",
488 "*::test_2 *FAILED*",
489 "*failed, continuing from this test next run*",
490 "* 1 failed, 1 passed in *",
491 ]
492 )
493
494 # Fix the failing test and run again.
495 pytester.makepyfile(
496 """
497 def test_1(): pass
498 def test_2(): pass
499 def test_3(): pass
500 def test_4(): pass
501 """
502 )
503 result = pytester.runpytest("--stepwise", "-v")
504 result.stdout.fnmatch_lines(
505 [
506 "stepwise: skipping 1 already passed items (cache from *, use --sw-reset to discard).",
507 "*::test_2 *PASSED*",
508 "*::test_3 *PASSED*",
509 "*::test_4 *PASSED*",
510 "* 3 passed, 1 deselected in *",
511 ]
512 )
513
514
515 def test_cache_error(pytester: Pytester) -> None:
516 pytester.makepyfile(
517 """
518 def test_1(): pass
519 """
520 )
521 # Run stepwise normally to generate the cache information.
522 result = pytester.runpytest("--stepwise", "-v")
523 result.stdout.fnmatch_lines(
524 [
525 "stepwise: no previously failed tests, not skipping.",
526 "*::test_1 *PASSED*",
527 "* 1 passed in *",
528 ]
529 )
530
531 # Corrupt the cache.
532 cache_file = pytester.path / f".pytest_cache/v/{STEPWISE_CACHE_DIR}"
533 assert cache_file.is_file()
534 cache_file.write_text(json.dumps({"invalid": True}), encoding="UTF-8")
535
536 # Check we run as if the cache did not exist, but also show an error message.
537 result = pytester.runpytest("--stepwise", "-v")
538 result.stdout.fnmatch_lines(
539 [
540 "stepwise: error reading cache, discarding (KeyError: *",
541 "stepwise: no previously failed tests, not skipping.",
542 "*::test_1 *PASSED*",
543 "* 1 passed in *",
544 ]
545 )