forked from pytest-dev/pytest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_cacheprovider.py
1362 lines (1213 loc) · 45.5 KB
/
test_cacheprovider.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
from enum import auto
from enum import Enum
import os
from pathlib import Path
import shutil
from typing import Any
from typing import Generator
from typing import Sequence
from _pytest.compat import assert_never
from _pytest.config import ExitCode
from _pytest.monkeypatch import MonkeyPatch
from _pytest.pytester import Pytester
from _pytest.tmpdir import TempPathFactory
import pytest
pytest_plugins = ("pytester",)
class TestNewAPI:
def test_config_cache_mkdir(self, pytester: Pytester) -> None:
pytester.makeini("[pytest]")
config = pytester.parseconfigure()
assert config.cache is not None
with pytest.raises(ValueError):
config.cache.mkdir("key/name")
p = config.cache.mkdir("name")
assert p.is_dir()
def test_cache_dir_permissions(self, pytester: Pytester) -> None:
"""The .pytest_cache directory should have world-readable permissions
(depending on umask).
Regression test for #12308.
"""
pytester.makeini("[pytest]")
config = pytester.parseconfigure()
assert config.cache is not None
p = config.cache.mkdir("name")
assert p.is_dir()
# Instead of messing with umask, make sure .pytest_cache has the same
# permissions as the default that `mkdir` gives `p`.
assert (p.parent.stat().st_mode & 0o777) == (p.stat().st_mode & 0o777)
def test_config_cache_dataerror(self, pytester: Pytester) -> None:
pytester.makeini("[pytest]")
config = pytester.parseconfigure()
assert config.cache is not None
cache = config.cache
pytest.raises(TypeError, lambda: cache.set("key/name", cache))
config.cache.set("key/name", 0)
config.cache._getvaluepath("key/name").write_bytes(b"123invalid")
val = config.cache.get("key/name", -2)
assert val == -2
@pytest.mark.filterwarnings("ignore:could not create cache path")
def test_cache_writefail_cachefile_silent(self, pytester: Pytester) -> None:
pytester.makeini("[pytest]")
pytester.path.joinpath(".pytest_cache").write_text(
"gone wrong", encoding="utf-8"
)
config = pytester.parseconfigure()
cache = config.cache
assert cache is not None
cache.set("test/broken", [])
@pytest.fixture
def unwritable_cache_dir(self, pytester: Pytester) -> Generator[Path]:
cache_dir = pytester.path.joinpath(".pytest_cache")
cache_dir.mkdir()
mode = cache_dir.stat().st_mode
cache_dir.chmod(0)
if os.access(cache_dir, os.W_OK):
pytest.skip("Failed to make cache dir unwritable")
yield cache_dir
cache_dir.chmod(mode)
@pytest.mark.filterwarnings(
"ignore:could not create cache path:pytest.PytestWarning"
)
def test_cache_writefail_permissions(
self, unwritable_cache_dir: Path, pytester: Pytester
) -> None:
pytester.makeini("[pytest]")
config = pytester.parseconfigure()
cache = config.cache
assert cache is not None
cache.set("test/broken", [])
@pytest.mark.filterwarnings("default")
def test_cache_failure_warns(
self,
pytester: Pytester,
monkeypatch: MonkeyPatch,
unwritable_cache_dir: Path,
) -> None:
monkeypatch.setenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "1")
pytester.makepyfile("def test_error(): raise Exception")
result = pytester.runpytest()
assert result.ret == 1
# warnings from nodeids, lastfailed, and stepwise
result.stdout.fnmatch_lines(
[
# Validate location/stacklevel of warning from cacheprovider.
"*= warnings summary =*",
"*/cacheprovider.py:*",
" */cacheprovider.py:*: PytestCacheWarning: could not create cache path "
f"{unwritable_cache_dir}/v/cache/nodeids: *",
' config.cache.set("cache/nodeids", sorted(self.cached_nodeids))',
"*1 failed, 3 warnings in*",
]
)
def test_config_cache(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_configure(config):
# see that we get cache information early on
assert hasattr(config, "cache")
"""
)
pytester.makepyfile(
"""
def test_session(pytestconfig):
assert hasattr(pytestconfig, "cache")
"""
)
result = pytester.runpytest()
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 passed*"])
def test_cachefuncarg(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
def test_cachefuncarg(cache):
val = cache.get("some/thing", None)
assert val is None
cache.set("some/thing", [1])
pytest.raises(TypeError, lambda: cache.get("some/thing"))
val = cache.get("some/thing", [])
assert val == [1]
"""
)
result = pytester.runpytest()
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 passed*"])
def test_custom_rel_cache_dir(self, pytester: Pytester) -> None:
rel_cache_dir = os.path.join("custom_cache_dir", "subdir")
pytester.makeini(
f"""
[pytest]
cache_dir = {rel_cache_dir}
"""
)
pytester.makepyfile(test_errored="def test_error():\n assert False")
pytester.runpytest()
assert pytester.path.joinpath(rel_cache_dir).is_dir()
def test_custom_abs_cache_dir(
self, pytester: Pytester, tmp_path_factory: TempPathFactory
) -> None:
tmp = tmp_path_factory.mktemp("tmp")
abs_cache_dir = tmp / "custom_cache_dir"
pytester.makeini(
f"""
[pytest]
cache_dir = {abs_cache_dir}
"""
)
pytester.makepyfile(test_errored="def test_error():\n assert False")
pytester.runpytest()
assert abs_cache_dir.is_dir()
def test_custom_cache_dir_with_env_var(
self, pytester: Pytester, monkeypatch: MonkeyPatch
) -> None:
monkeypatch.setenv("env_var", "custom_cache_dir")
pytester.makeini(
"""
[pytest]
cache_dir = {cache_dir}
""".format(cache_dir="$env_var")
)
pytester.makepyfile(test_errored="def test_error():\n assert False")
pytester.runpytest()
assert pytester.path.joinpath("custom_cache_dir").is_dir()
@pytest.mark.parametrize("env", ((), ("TOX_ENV_DIR", "mydir/tox-env")))
def test_cache_reportheader(
env: Sequence[str], pytester: Pytester, monkeypatch: MonkeyPatch
) -> None:
pytester.makepyfile("""def test_foo(): pass""")
if env:
monkeypatch.setenv(*env)
expected = os.path.join(env[1], ".pytest_cache")
else:
monkeypatch.delenv("TOX_ENV_DIR", raising=False)
expected = ".pytest_cache"
result = pytester.runpytest("-v")
result.stdout.fnmatch_lines([f"cachedir: {expected}"])
def test_cache_reportheader_external_abspath(
pytester: Pytester, tmp_path_factory: TempPathFactory
) -> None:
external_cache = tmp_path_factory.mktemp(
"test_cache_reportheader_external_abspath_abs"
)
pytester.makepyfile("def test_hello(): pass")
pytester.makeini(
f"""
[pytest]
cache_dir = {external_cache}
"""
)
result = pytester.runpytest("-v")
result.stdout.fnmatch_lines([f"cachedir: {external_cache}"])
def test_cache_show(pytester: Pytester) -> None:
result = pytester.runpytest("--cache-show")
assert result.ret == 0
result.stdout.fnmatch_lines(["*cache is empty*"])
pytester.makeconftest(
"""
def pytest_configure(config):
config.cache.set("my/name", [1,2,3])
config.cache.set("my/hello", "world")
config.cache.set("other/some", {1:2})
dp = config.cache.mkdir("mydb")
dp.joinpath("hello").touch()
dp.joinpath("world").touch()
"""
)
result = pytester.runpytest()
assert result.ret == 5 # no tests executed
result = pytester.runpytest("--cache-show")
result.stdout.fnmatch_lines(
[
"*cachedir:*",
"*- cache values for '[*]' -*",
"cache/nodeids contains:",
"my/name contains:",
" [1, 2, 3]",
"other/some contains:",
" {*'1': 2}",
"*- cache directories for '[*]' -*",
"*mydb/hello*length 0*",
"*mydb/world*length 0*",
]
)
assert result.ret == 0
result = pytester.runpytest("--cache-show", "*/hello")
result.stdout.fnmatch_lines(
[
"*cachedir:*",
"*- cache values for '[*]/hello' -*",
"my/hello contains:",
" *'world'",
"*- cache directories for '[*]/hello' -*",
"d/mydb/hello*length 0*",
]
)
stdout = result.stdout.str()
assert "other/some" not in stdout
assert "d/mydb/world" not in stdout
assert result.ret == 0
class TestLastFailed:
def test_lastfailed_usecase(
self, pytester: Pytester, monkeypatch: MonkeyPatch
) -> None:
monkeypatch.setattr("sys.dont_write_bytecode", True)
p = pytester.makepyfile(
"""
def test_1(): assert 0
def test_2(): assert 0
def test_3(): assert 1
"""
)
result = pytester.runpytest(str(p))
result.stdout.fnmatch_lines(["*2 failed*"])
p = pytester.makepyfile(
"""
def test_1(): assert 1
def test_2(): assert 1
def test_3(): assert 0
"""
)
result = pytester.runpytest(str(p), "--lf")
result.stdout.fnmatch_lines(
[
"collected 3 items / 1 deselected / 2 selected",
"run-last-failure: rerun previous 2 failures",
"*= 2 passed, 1 deselected in *",
]
)
result = pytester.runpytest(str(p), "--lf")
result.stdout.fnmatch_lines(
[
"collected 3 items",
"run-last-failure: no previously failed tests, not deselecting items.",
"*1 failed*2 passed*",
]
)
pytester.path.joinpath(".pytest_cache", ".git").mkdir(parents=True)
result = pytester.runpytest(str(p), "--lf", "--cache-clear")
result.stdout.fnmatch_lines(["*1 failed*2 passed*"])
assert pytester.path.joinpath(".pytest_cache", "README.md").is_file()
assert pytester.path.joinpath(".pytest_cache", ".git").is_dir()
# Run this again to make sure clear-cache is robust
if os.path.isdir(".pytest_cache"):
shutil.rmtree(".pytest_cache")
result = pytester.runpytest("--lf", "--cache-clear")
result.stdout.fnmatch_lines(["*1 failed*2 passed*"])
def test_failedfirst_order(self, pytester: Pytester) -> None:
pytester.makepyfile(
test_a="def test_always_passes(): pass",
test_b="def test_always_fails(): assert 0",
)
result = pytester.runpytest()
# Test order will be collection order; alphabetical
result.stdout.fnmatch_lines(["test_a.py*", "test_b.py*"])
result = pytester.runpytest("--ff")
# Test order will be failing tests first
result.stdout.fnmatch_lines(
[
"collected 2 items",
"run-last-failure: rerun previous 1 failure first",
"test_b.py*",
"test_a.py*",
]
)
def test_lastfailed_failedfirst_order(self, pytester: Pytester) -> None:
pytester.makepyfile(
test_a="def test_always_passes(): assert 1",
test_b="def test_always_fails(): assert 0",
)
result = pytester.runpytest()
# Test order will be collection order; alphabetical
result.stdout.fnmatch_lines(["test_a.py*", "test_b.py*"])
result = pytester.runpytest("--lf", "--ff")
# Test order will be failing tests first
result.stdout.fnmatch_lines(["test_b.py*"])
result.stdout.no_fnmatch_line("*test_a.py*")
def test_lastfailed_difference_invocations(
self, pytester: Pytester, monkeypatch: MonkeyPatch
) -> None:
monkeypatch.setattr("sys.dont_write_bytecode", True)
pytester.makepyfile(
test_a="""
def test_a1(): assert 0
def test_a2(): assert 1
""",
test_b="def test_b1(): assert 0",
)
p = pytester.path.joinpath("test_a.py")
p2 = pytester.path.joinpath("test_b.py")
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*2 failed*"])
result = pytester.runpytest("--lf", p2)
result.stdout.fnmatch_lines(["*1 failed*"])
pytester.makepyfile(test_b="def test_b1(): assert 1")
result = pytester.runpytest("--lf", p2)
result.stdout.fnmatch_lines(["*1 passed*"])
result = pytester.runpytest("--lf", p)
result.stdout.fnmatch_lines(
[
"collected 2 items / 1 deselected / 1 selected",
"run-last-failure: rerun previous 1 failure",
"*= 1 failed, 1 deselected in *",
]
)
def test_lastfailed_usecase_splice(
self, pytester: Pytester, monkeypatch: MonkeyPatch
) -> None:
monkeypatch.setattr("sys.dont_write_bytecode", True)
pytester.makepyfile(
"def test_1(): assert 0", test_something="def test_2(): assert 0"
)
p2 = pytester.path.joinpath("test_something.py")
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*2 failed*"])
result = pytester.runpytest("--lf", p2)
result.stdout.fnmatch_lines(["*1 failed*"])
result = pytester.runpytest("--lf")
result.stdout.fnmatch_lines(["*2 failed*"])
def test_lastfailed_xpass(self, pytester: Pytester) -> None:
pytester.inline_runsource(
"""
import pytest
@pytest.mark.xfail
def test_hello():
assert 1
"""
)
config = pytester.parseconfigure()
assert config.cache is not None
lastfailed = config.cache.get("cache/lastfailed", -1)
assert lastfailed == -1
def test_non_serializable_parametrize(self, pytester: Pytester) -> None:
"""Test that failed parametrized tests with unmarshable parameters
don't break pytest-cache.
"""
pytester.makepyfile(
r"""
import pytest
@pytest.mark.parametrize('val', [
b'\xac\x10\x02G',
])
def test_fail(val):
assert False
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*1 failed in*"])
@pytest.mark.parametrize("parent", ("directory", "package"))
def test_terminal_report_lastfailed(self, pytester: Pytester, parent: str) -> None:
if parent == "package":
pytester.makepyfile(
__init__="",
)
test_a = pytester.makepyfile(
test_a="""
def test_a1(): pass
def test_a2(): pass
"""
)
test_b = pytester.makepyfile(
test_b="""
def test_b1(): assert 0
def test_b2(): assert 0
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["collected 4 items", "*2 failed, 2 passed in*"])
result = pytester.runpytest("--lf")
result.stdout.fnmatch_lines(
[
"collected 2 items",
"run-last-failure: rerun previous 2 failures (skipped 1 file)",
"*2 failed in*",
]
)
result = pytester.runpytest(test_a, "--lf")
result.stdout.fnmatch_lines(
[
"collected 2 items",
"run-last-failure: 2 known failures not in selected tests",
"*2 passed in*",
]
)
result = pytester.runpytest(test_b, "--lf")
result.stdout.fnmatch_lines(
[
"collected 2 items",
"run-last-failure: rerun previous 2 failures",
"*2 failed in*",
]
)
result = pytester.runpytest("test_b.py::test_b1", "--lf")
result.stdout.fnmatch_lines(
[
"collected 1 item",
"run-last-failure: rerun previous 1 failure",
"*1 failed in*",
]
)
def test_terminal_report_failedfirst(self, pytester: Pytester) -> None:
pytester.makepyfile(
test_a="""
def test_a1(): assert 0
def test_a2(): pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["collected 2 items", "*1 failed, 1 passed in*"])
result = pytester.runpytest("--ff")
result.stdout.fnmatch_lines(
[
"collected 2 items",
"run-last-failure: rerun previous 1 failure first",
"*1 failed, 1 passed in*",
]
)
def test_lastfailed_collectfailure(
self, pytester: Pytester, monkeypatch: MonkeyPatch
) -> None:
pytester.makepyfile(
test_maybe="""
import os
env = os.environ
if '1' == env['FAILIMPORT']:
raise ImportError('fail')
def test_hello():
assert '0' == env['FAILTEST']
"""
)
def rlf(fail_import: int, fail_run: int) -> Any:
monkeypatch.setenv("FAILIMPORT", str(fail_import))
monkeypatch.setenv("FAILTEST", str(fail_run))
pytester.runpytest("-q")
config = pytester.parseconfigure()
assert config.cache is not None
lastfailed = config.cache.get("cache/lastfailed", -1)
return lastfailed
lastfailed = rlf(fail_import=0, fail_run=0)
assert lastfailed == -1
lastfailed = rlf(fail_import=1, fail_run=0)
assert list(lastfailed) == ["test_maybe.py"]
lastfailed = rlf(fail_import=0, fail_run=1)
assert list(lastfailed) == ["test_maybe.py::test_hello"]
def test_lastfailed_failure_subset(
self, pytester: Pytester, monkeypatch: MonkeyPatch
) -> None:
pytester.makepyfile(
test_maybe="""
import os
env = os.environ
if '1' == env['FAILIMPORT']:
raise ImportError('fail')
def test_hello():
assert '0' == env['FAILTEST']
"""
)
pytester.makepyfile(
test_maybe2="""
import os
env = os.environ
if '1' == env['FAILIMPORT']:
raise ImportError('fail')
def test_hello():
assert '0' == env['FAILTEST']
def test_pass():
pass
"""
)
def rlf(
fail_import: int, fail_run: int, args: Sequence[str] = ()
) -> tuple[Any, Any]:
monkeypatch.setenv("FAILIMPORT", str(fail_import))
monkeypatch.setenv("FAILTEST", str(fail_run))
result = pytester.runpytest("-q", "--lf", *args)
config = pytester.parseconfigure()
assert config.cache is not None
lastfailed = config.cache.get("cache/lastfailed", -1)
return result, lastfailed
result, lastfailed = rlf(fail_import=0, fail_run=0)
assert lastfailed == -1
result.stdout.fnmatch_lines(["*3 passed*"])
result, lastfailed = rlf(fail_import=1, fail_run=0)
assert sorted(list(lastfailed)) == ["test_maybe.py", "test_maybe2.py"]
result, lastfailed = rlf(fail_import=0, fail_run=0, args=("test_maybe2.py",))
assert list(lastfailed) == ["test_maybe.py"]
# edge case of test selection - even if we remember failures
# from other tests we still need to run all tests if no test
# matches the failures
result, lastfailed = rlf(fail_import=0, fail_run=0, args=("test_maybe2.py",))
assert list(lastfailed) == ["test_maybe.py"]
result.stdout.fnmatch_lines(["*2 passed*"])
def test_lastfailed_creates_cache_when_needed(self, pytester: Pytester) -> None:
# Issue #1342
pytester.makepyfile(test_empty="")
pytester.runpytest("-q", "--lf")
assert not os.path.exists(".pytest_cache/v/cache/lastfailed")
pytester.makepyfile(test_successful="def test_success():\n assert True")
pytester.runpytest("-q", "--lf")
assert not os.path.exists(".pytest_cache/v/cache/lastfailed")
pytester.makepyfile(test_errored="def test_error():\n assert False")
pytester.runpytest("-q", "--lf")
assert os.path.exists(".pytest_cache/v/cache/lastfailed")
def test_xfail_not_considered_failure(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.xfail
def test(): assert 0
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*1 xfailed*"])
assert self.get_cached_last_failed(pytester) == []
def test_xfail_strict_considered_failure(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.xfail(strict=True)
def test(): pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*1 failed*"])
assert self.get_cached_last_failed(pytester) == [
"test_xfail_strict_considered_failure.py::test"
]
@pytest.mark.parametrize("mark", ["mark.xfail", "mark.skip"])
def test_failed_changed_to_xfail_or_skip(
self, pytester: Pytester, mark: str
) -> None:
pytester.makepyfile(
"""
import pytest
def test(): assert 0
"""
)
result = pytester.runpytest()
assert self.get_cached_last_failed(pytester) == [
"test_failed_changed_to_xfail_or_skip.py::test"
]
assert result.ret == 1
pytester.makepyfile(
f"""
import pytest
@pytest.{mark}
def test(): assert 0
"""
)
result = pytester.runpytest()
assert result.ret == 0
assert self.get_cached_last_failed(pytester) == []
assert result.ret == 0
@pytest.mark.parametrize("quiet", [True, False])
@pytest.mark.parametrize("opt", ["--ff", "--lf"])
def test_lf_and_ff_prints_no_needless_message(
self, quiet: bool, opt: str, pytester: Pytester
) -> None:
# Issue 3853
pytester.makepyfile("def test(): assert 0")
args = [opt]
if quiet:
args.append("-q")
result = pytester.runpytest(*args)
result.stdout.no_fnmatch_line("*run all*")
result = pytester.runpytest(*args)
if quiet:
result.stdout.no_fnmatch_line("*run all*")
else:
assert "rerun previous" in result.stdout.str()
def get_cached_last_failed(self, pytester: Pytester) -> list[str]:
config = pytester.parseconfigure()
assert config.cache is not None
return sorted(config.cache.get("cache/lastfailed", {}))
def test_cache_cumulative(self, pytester: Pytester) -> None:
"""Test workflow where user fixes errors gradually file by file using --lf."""
# 1. initial run
test_bar = pytester.makepyfile(
test_bar="""
def test_bar_1(): pass
def test_bar_2(): assert 0
"""
)
test_foo = pytester.makepyfile(
test_foo="""
def test_foo_3(): pass
def test_foo_4(): assert 0
"""
)
pytester.runpytest()
assert self.get_cached_last_failed(pytester) == [
"test_bar.py::test_bar_2",
"test_foo.py::test_foo_4",
]
# 2. fix test_bar_2, run only test_bar.py
pytester.makepyfile(
test_bar="""
def test_bar_1(): pass
def test_bar_2(): pass
"""
)
result = pytester.runpytest(test_bar)
result.stdout.fnmatch_lines(["*2 passed*"])
# ensure cache does not forget that test_foo_4 failed once before
assert self.get_cached_last_failed(pytester) == ["test_foo.py::test_foo_4"]
result = pytester.runpytest("--last-failed")
result.stdout.fnmatch_lines(
[
"collected 1 item",
"run-last-failure: rerun previous 1 failure (skipped 1 file)",
"*= 1 failed in *",
]
)
assert self.get_cached_last_failed(pytester) == ["test_foo.py::test_foo_4"]
# 3. fix test_foo_4, run only test_foo.py
test_foo = pytester.makepyfile(
test_foo="""
def test_foo_3(): pass
def test_foo_4(): pass
"""
)
result = pytester.runpytest(test_foo, "--last-failed")
result.stdout.fnmatch_lines(
[
"collected 2 items / 1 deselected / 1 selected",
"run-last-failure: rerun previous 1 failure",
"*= 1 passed, 1 deselected in *",
]
)
assert self.get_cached_last_failed(pytester) == []
result = pytester.runpytest("--last-failed")
result.stdout.fnmatch_lines(["*4 passed*"])
assert self.get_cached_last_failed(pytester) == []
def test_lastfailed_no_failures_behavior_all_passed(
self, pytester: Pytester
) -> None:
pytester.makepyfile(
"""
def test_1(): pass
def test_2(): pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*2 passed*"])
result = pytester.runpytest("--lf")
result.stdout.fnmatch_lines(["*2 passed*"])
result = pytester.runpytest("--lf", "--lfnf", "all")
result.stdout.fnmatch_lines(["*2 passed*"])
# Ensure the list passed to pytest_deselected is a copy,
# and not a reference which is cleared right after.
pytester.makeconftest(
"""
deselected = []
def pytest_deselected(items):
global deselected
deselected = items
def pytest_sessionfinish():
print("\\ndeselected={}".format(len(deselected)))
"""
)
result = pytester.runpytest("--lf", "--lfnf", "none")
result.stdout.fnmatch_lines(
[
"collected 2 items / 2 deselected / 0 selected",
"run-last-failure: no previously failed tests, deselecting all items.",
"deselected=2",
"* 2 deselected in *",
]
)
assert result.ret == ExitCode.NO_TESTS_COLLECTED
def test_lastfailed_no_failures_behavior_empty_cache(
self, pytester: Pytester
) -> None:
pytester.makepyfile(
"""
def test_1(): pass
def test_2(): assert 0
"""
)
result = pytester.runpytest("--lf", "--cache-clear")
result.stdout.fnmatch_lines(["*1 failed*1 passed*"])
result = pytester.runpytest("--lf", "--cache-clear", "--lfnf", "all")
result.stdout.fnmatch_lines(["*1 failed*1 passed*"])
result = pytester.runpytest("--lf", "--cache-clear", "--lfnf", "none")
result.stdout.fnmatch_lines(["*2 desel*"])
def test_lastfailed_skip_collection(self, pytester: Pytester) -> None:
"""
Test --lf behavior regarding skipping collection of files that are not marked as
failed in the cache (#5172).
"""
pytester.makepyfile(
**{
"pkg1/test_1.py": """
import pytest
@pytest.mark.parametrize('i', range(3))
def test_1(i): pass
""",
"pkg2/test_2.py": """
import pytest
@pytest.mark.parametrize('i', range(5))
def test_1(i):
assert i not in (1, 3)
""",
}
)
# first run: collects 8 items (test_1: 3, test_2: 5)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["collected 8 items", "*2 failed*6 passed*"])
# second run: collects only 5 items from test_2, because all tests from test_1 have passed
result = pytester.runpytest("--lf")
result.stdout.fnmatch_lines(
[
"collected 2 items",
"run-last-failure: rerun previous 2 failures (skipped 1 file)",
"*= 2 failed in *",
]
)
# add another file and check if message is correct when skipping more than 1 file
pytester.makepyfile(
**{
"pkg1/test_3.py": """
def test_3(): pass
"""
}
)
result = pytester.runpytest("--lf")
result.stdout.fnmatch_lines(
[
"collected 2 items",
"run-last-failure: rerun previous 2 failures (skipped 2 files)",
"*= 2 failed in *",
]
)
def test_lastfailed_skip_collection_with_nesting(self, pytester: Pytester) -> None:
"""Check that file skipping works even when the file with failures is
nested at a different level of the collection tree."""
pytester.makepyfile(
**{
"test_1.py": """
def test_1(): pass
""",
"pkg/__init__.py": "",
"pkg/test_2.py": """
def test_2(): assert False
""",
}
)
# first run
result = pytester.runpytest()
result.stdout.fnmatch_lines(["collected 2 items", "*1 failed*1 passed*"])
# second run - test_1.py is skipped.
result = pytester.runpytest("--lf")
result.stdout.fnmatch_lines(
[
"collected 1 item",
"run-last-failure: rerun previous 1 failure (skipped 1 file)",
"*= 1 failed in *",
]
)
def test_lastfailed_with_known_failures_not_being_selected(
self, pytester: Pytester
) -> None:
pytester.makepyfile(
**{
"pkg1/test_1.py": """def test_1(): assert 0""",
"pkg1/test_2.py": """def test_2(): pass""",
}
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["collected 2 items", "* 1 failed, 1 passed in *"])
Path("pkg1/test_1.py").unlink()
result = pytester.runpytest("--lf")
result.stdout.fnmatch_lines(
[
"collected 1 item",
"run-last-failure: 1 known failures not in selected tests",
"* 1 passed in *",
]
)
# Recreate file with known failure.
pytester.makepyfile(**{"pkg1/test_1.py": """def test_1(): assert 0"""})
result = pytester.runpytest("--lf")
result.stdout.fnmatch_lines(
[
"collected 1 item",
"run-last-failure: rerun previous 1 failure (skipped 1 file)",
"* 1 failed in *",
]
)
# Remove/rename test: collects the file again.
pytester.makepyfile(**{"pkg1/test_1.py": """def test_renamed(): assert 0"""})
result = pytester.runpytest("--lf", "-rf")
result.stdout.fnmatch_lines(
[
"collected 2 items",
"run-last-failure: 1 known failures not in selected tests",
"pkg1/test_1.py F *",
"pkg1/test_2.py . *",
"FAILED pkg1/test_1.py::test_renamed - assert 0",
"* 1 failed, 1 passed in *",
]
)
result = pytester.runpytest("--lf", "--co")
result.stdout.fnmatch_lines(
[
"collected 1 item",
"run-last-failure: rerun previous 1 failure (skipped 1 file)",
"",
"<Dir *>",
" <Dir pkg1>",
" <Module test_1.py>",
" <Function test_renamed>",
]
)
def test_lastfailed_args_with_deselected(self, pytester: Pytester) -> None:
"""Test regression with --lf running into NoMatch error.
This was caused by it not collecting (non-failed) nodes given as
arguments.
"""
pytester.makepyfile(
**{
"pkg1/test_1.py": """
def test_pass(): pass
def test_fail(): assert 0
""",
}
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["collected 2 items", "* 1 failed, 1 passed in *"])
assert result.ret == 1
result = pytester.runpytest("pkg1/test_1.py::test_pass", "--lf", "--co")
assert result.ret == 0
result.stdout.fnmatch_lines(
[
"*collected 1 item",
"run-last-failure: 1 known failures not in selected tests",
"",
"<Dir *>",
" <Dir pkg1>",
" <Module test_1.py>",
" <Function test_pass>",
],
consecutive=True,
)
result = pytester.runpytest(
"pkg1/test_1.py::test_pass", "pkg1/test_1.py::test_fail", "--lf", "--co"
)
assert result.ret == 0
result.stdout.fnmatch_lines(
[