-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathtest_pytest_rerunfailures.py
More file actions
1428 lines (1188 loc) · 41.6 KB
/
test_pytest_rerunfailures.py
File metadata and controls
1428 lines (1188 loc) · 41.6 KB
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
import random
import socket
import time
from unittest import mock
import pytest
from pytest_rerunfailures import HAS_PYTEST_HANDLECRASHITEM, SocketDB
pytest_plugins = "pytester"
has_xdist = HAS_PYTEST_HANDLECRASHITEM
def temporary_failure(count=1):
return f"""
import py
path = py.path.local(__file__).dirpath().ensure('test.res')
count = path.read() or 1
if int(count) <= {count}:
path.write(int(count) + 1)
raise Exception('Failure: {{0}}'.format(count))"""
def temporary_crash(count=1):
return f"""
import py
import os
path = py.path.local(__file__).dirpath().ensure('test.res')
count = path.read() or 1
if int(count) <= {count}:
path.write(int(count) + 1)
os._exit(1)"""
def check_outcome_field(outcomes, field_name, expected_value):
field_value = outcomes.get(field_name, 0)
assert field_value == expected_value, (
f"outcomes.{field_name} has unexpected value. "
f"Expected '{expected_value}' but got '{field_value}'"
)
def assert_outcomes(
result,
passed=1,
skipped=0,
failed=0,
error=0,
xfailed=0,
xpassed=0,
rerun=0,
):
outcomes = result.parseoutcomes()
check_outcome_field(outcomes, "passed", passed)
check_outcome_field(outcomes, "skipped", skipped)
check_outcome_field(outcomes, "failed", failed)
field = "errors"
check_outcome_field(outcomes, field, error)
check_outcome_field(outcomes, "xfailed", xfailed)
check_outcome_field(outcomes, "xpassed", xpassed)
check_outcome_field(outcomes, "rerun", rerun)
def test_error_when_run_with_pdb(testdir):
testdir.makepyfile("def test_pass(): pass")
result = testdir.runpytest("--reruns", "1", "--pdb")
result.stderr.fnmatch_lines_random("ERROR: --reruns incompatible with --pdb")
def test_no_rerun_on_pass(testdir):
testdir.makepyfile("def test_pass(): pass")
result = testdir.runpytest("--reruns", "1")
assert_outcomes(result)
def test_no_rerun_on_skipif_mark(testdir):
reason = str(random.random())
testdir.makepyfile(
f"""
import pytest
@pytest.mark.skipif(reason='{reason}')
def test_skip():
pass
"""
)
result = testdir.runpytest("--reruns", "1")
assert_outcomes(result, passed=0, skipped=1)
def test_no_rerun_on_skip_call(testdir):
reason = str(random.random())
testdir.makepyfile(
f"""
import pytest
def test_skip():
pytest.skip('{reason}')
"""
)
result = testdir.runpytest("--reruns", "1")
assert_outcomes(result, passed=0, skipped=1)
def test_no_rerun_on_xfail_mark(testdir):
testdir.makepyfile(
"""
import pytest
@pytest.mark.xfail()
def test_xfail():
assert False
"""
)
result = testdir.runpytest("--reruns", "1")
assert_outcomes(result, passed=0, xfailed=1)
def test_no_rerun_on_xfail_call(testdir):
reason = str(random.random())
testdir.makepyfile(
f"""
import pytest
def test_xfail():
pytest.xfail('{reason}')
"""
)
result = testdir.runpytest("--reruns", "1")
assert_outcomes(result, passed=0, xfailed=1)
def test_no_rerun_on_xpass(testdir):
testdir.makepyfile(
"""
import pytest
@pytest.mark.xfail()
def test_xpass():
pass
"""
)
result = testdir.runpytest("--reruns", "1")
assert_outcomes(result, passed=0, xpassed=1)
def test_rerun_fails_after_consistent_setup_failure(testdir):
testdir.makepyfile("def test_pass(): pass")
testdir.makeconftest(
"""
def pytest_runtest_setup(item):
raise Exception('Setup failure')"""
)
result = testdir.runpytest("--reruns", "1")
assert_outcomes(result, passed=0, error=1, rerun=1)
def test_rerun_passes_after_temporary_setup_failure(testdir):
testdir.makepyfile("def test_pass(): pass")
testdir.makeconftest(
f"""
def pytest_runtest_setup(item):
{temporary_failure()}"""
)
result = testdir.runpytest("--reruns", "1", "-r", "R")
assert_outcomes(result, passed=1, rerun=1)
def test_rerun_fails_after_consistent_test_failure(testdir):
testdir.makepyfile("def test_fail(): assert False")
result = testdir.runpytest("--reruns", "1")
assert_outcomes(result, passed=0, failed=1, rerun=1)
def test_rerun_passes_after_temporary_test_failure(testdir):
testdir.makepyfile(
f"""
def test_pass():
{temporary_failure()}"""
)
result = testdir.runpytest("--reruns", "1", "-r", "R")
assert_outcomes(result, passed=1, rerun=1)
def test_run_with_fail_on_flaky_fails_with_custom_error_code_after_pass_on_rerun(
testdir,
):
testdir.makepyfile(
f"""
def test_pass():
{temporary_failure()}"""
)
result = testdir.runpytest("--reruns", "1", "--fail-on-flaky")
assert_outcomes(result, passed=1, rerun=1)
assert result.ret == 7
def test_run_fails_with_code_1_after_consistent_test_failure_even_with_fail_on_flaky(
testdir,
):
testdir.makepyfile("def test_fail(): assert False")
result = testdir.runpytest("--reruns", "1", "--fail-on-flaky")
assert_outcomes(result, passed=0, failed=1, rerun=1)
assert result.ret == 1
def test_run_mark_and_fail_on_flaky_fails_with_custom_error_code_after_pass_on_rerun(
testdir,
):
testdir.makepyfile(f"""
import pytest
@pytest.mark.flaky(reruns=1)
def test_fail():
{temporary_failure()}
""")
result = testdir.runpytest("--fail-on-flaky")
assert_outcomes(result, passed=1, rerun=1)
assert result.ret == 7
def test_run_fails_with_code_1_after_test_failure_with_fail_on_flaky_and_mark(
testdir,
):
testdir.makepyfile("""
import pytest
@pytest.mark.flaky(reruns=2)
def test_fail():
assert False
""")
result = testdir.runpytest("--fail-on-flaky")
assert_outcomes(result, passed=0, failed=1, rerun=2)
assert result.ret == 1
def test_run_with_mark_and_fail_on_flaky_succeeds_if_all_tests_pass_without_reruns(
testdir,
):
testdir.makepyfile("""
import pytest
@pytest.mark.flaky(reruns=2)
def test_marked_pass():
assert True
def test_unmarked_pass():
assert True
""")
result = testdir.runpytest("--fail-on-flaky")
assert_outcomes(result, passed=2, rerun=0)
assert result.ret == pytest.ExitCode.OK
def test_run_with_fail_on_flaky_succeeds_if_all_tests_pass_without_reruns(
testdir,
):
testdir.makepyfile("def test_pass(): assert True")
result = testdir.runpytest("--reruns", "1", "--fail-on-flaky")
assert_outcomes(result, passed=1, rerun=0)
assert result.ret == pytest.ExitCode.OK
@pytest.mark.skipif(not has_xdist, reason="requires xdist with crashitem")
def test_rerun_passes_after_temporary_test_crash(testdir):
# note: we need two tests because there is a bug where xdist
# cannot rerun the last test if it crashes. the bug exists only
# in xdist is there is no error that causes the bug in this plugin.
testdir.makepyfile(
f"""
def test_crash():
{temporary_crash()}
def test_pass():
pass"""
)
result = testdir.runpytest("-p", "xdist", "-n", "1", "--reruns", "1", "-r", "R")
assert_outcomes(result, passed=2, rerun=1)
def test_rerun_passes_after_temporary_test_failure_with_flaky_mark(testdir):
testdir.makepyfile(
f"""
import pytest
@pytest.mark.flaky(reruns=2)
def test_pass():
{temporary_failure(2)}"""
)
result = testdir.runpytest("-r", "R")
assert_outcomes(result, passed=1, rerun=2)
def test_reruns_if_flaky_mark_is_called_without_options(testdir):
testdir.makepyfile(
f"""
import pytest
@pytest.mark.flaky()
def test_pass():
{temporary_failure(1)}"""
)
result = testdir.runpytest("-r", "R")
assert_outcomes(result, passed=1, rerun=1)
def test_reruns_if_flaky_mark_is_called_with_positional_argument(testdir):
testdir.makepyfile(
f"""
import pytest
@pytest.mark.flaky(2)
def test_pass():
{temporary_failure(2)}"""
)
result = testdir.runpytest("-r", "R")
assert_outcomes(result, passed=1, rerun=2)
def test_no_extra_test_summary_for_reruns_by_default(testdir):
testdir.makepyfile(
f"""
def test_pass():
{temporary_failure()}"""
)
result = testdir.runpytest("--reruns", "1")
assert "RERUN" not in result.stdout.str()
assert "1 rerun" in result.stdout.str()
def test_extra_test_summary_for_reruns(testdir):
testdir.makepyfile(
f"""
def test_pass():
{temporary_failure()}"""
)
result = testdir.runpytest("--reruns", "1", "-r", "R")
result.stdout.fnmatch_lines_random(["RERUN test_*:*"])
assert "1 rerun" in result.stdout.str()
def test_verbose(testdir):
testdir.makepyfile(
f"""
def test_pass():
{temporary_failure()}"""
)
result = testdir.runpytest("--reruns", "1", "-v")
result.stdout.fnmatch_lines_random(["test_*:* RERUN*"])
assert "1 rerun" in result.stdout.str()
def test_no_rerun_on_class_setup_error_without_reruns(testdir):
testdir.makepyfile(
"""
class TestFoo(object):
@classmethod
def setup_class(cls):
assert False
def test_pass():
pass"""
)
result = testdir.runpytest("--reruns", "0")
assert_outcomes(result, passed=0, error=1, rerun=0)
def test_rerun_on_class_setup_error_with_reruns(testdir):
testdir.makepyfile(
"""
class TestFoo(object):
@classmethod
def setup_class(cls):
assert False
def test_pass():
pass"""
)
result = testdir.runpytest("--reruns", "1")
assert_outcomes(result, passed=0, error=1, rerun=1)
@pytest.mark.parametrize("delay_time", [-1, 0, 0.0, 1, 2.5])
def test_reruns_with_delay(testdir, delay_time):
testdir.makepyfile(
"""
def test_fail():
assert False"""
)
time.sleep = mock.MagicMock()
result = testdir.runpytest("--reruns", "3", "--reruns-delay", str(delay_time))
if delay_time < 0:
result.stdout.fnmatch_lines(
"*UserWarning: Delay time between re-runs cannot be < 0. "
"Using default value: 0"
)
delay_time = 0
time.sleep.assert_called_with(delay_time)
assert_outcomes(result, passed=0, failed=1, rerun=3)
@pytest.mark.parametrize("delay_time", [-1, 0, 0.0, 1, 2.5])
def test_reruns_with_delay_marker(testdir, delay_time):
testdir.makepyfile(
f"""
import pytest
@pytest.mark.flaky(reruns=2, reruns_delay={delay_time})
def test_fail_two():
assert False"""
)
time.sleep = mock.MagicMock()
result = testdir.runpytest()
if delay_time < 0:
result.stdout.fnmatch_lines(
"*UserWarning: Delay time between re-runs cannot be < 0. "
"Using default value: 0"
)
delay_time = 0
time.sleep.assert_called_with(delay_time)
assert_outcomes(result, passed=0, failed=1, rerun=2)
def test_rerun_on_setup_class_with_error_with_reruns(testdir):
"""
Case: setup_class throwing error on the first execution for parametrized test
"""
testdir.makepyfile(
"""
import pytest
pass_fixture = False
class TestFoo(object):
@classmethod
def setup_class(cls):
global pass_fixture
if not pass_fixture:
pass_fixture = True
assert False
assert True
@pytest.mark.parametrize('param', [1, 2, 3])
def test_pass(self, param):
assert param"""
)
result = testdir.runpytest("--reruns", "1")
assert_outcomes(result, passed=3, rerun=1)
def test_rerun_on_class_scope_fixture_with_error_with_reruns(testdir):
"""
Case: Class scope fixture throwing error on the first execution
for parametrized test
"""
testdir.makepyfile(
"""
import pytest
pass_fixture = False
class TestFoo(object):
@pytest.fixture(scope="class")
def setup_fixture(self):
global pass_fixture
if not pass_fixture:
pass_fixture = True
assert False
assert True
@pytest.mark.parametrize('param', [1, 2, 3])
def test_pass(self, setup_fixture, param):
assert param"""
)
result = testdir.runpytest("--reruns", "1")
assert_outcomes(result, passed=3, rerun=1)
def test_rerun_on_module_fixture_with_reruns(testdir):
"""
Case: Module scope fixture is not re-executed when class scope fixture throwing
error on the first execution for parametrized test
"""
testdir.makepyfile(
"""
import pytest
pass_fixture = False
@pytest.fixture(scope='module')
def module_fixture():
assert not pass_fixture
class TestFoo(object):
@pytest.fixture(scope="class")
def setup_fixture(self):
global pass_fixture
if not pass_fixture:
pass_fixture = True
assert False
assert True
def test_pass_1(self, module_fixture, setup_fixture):
assert True
def test_pass_2(self, module_fixture, setup_fixture):
assert True"""
)
result = testdir.runpytest("--reruns", "1")
assert_outcomes(result, passed=2, rerun=1)
def test_rerun_on_session_fixture_with_reruns(testdir):
"""
Case: Module scope fixture is not re-executed when class scope fixture
throwing error on the first execution for parametrized test
"""
testdir.makepyfile(
"""
import pytest
pass_fixture = False
@pytest.fixture(scope='session')
def session_fixture():
assert not pass_fixture
class TestFoo(object):
@pytest.fixture(scope="class")
def setup_fixture(self):
global pass_fixture
if not pass_fixture:
pass_fixture = True
assert False
assert True
def test_pass_1(self, session_fixture, setup_fixture):
assert True
def test_pass_2(self, session_fixture, setup_fixture):
assert True"""
)
result = testdir.runpytest("--reruns", "1")
assert_outcomes(result, passed=2, rerun=1)
def test_execution_count_exposed(testdir):
testdir.makepyfile("def test_pass(): assert True")
testdir.makeconftest(
"""
def pytest_runtest_teardown(item):
assert item.execution_count == 3"""
)
result = testdir.runpytest("--reruns", "2")
assert_outcomes(result, passed=3, rerun=2)
def test_rerun_report(testdir):
testdir.makepyfile("def test_pass(): assert False")
testdir.makeconftest(
"""
def pytest_runtest_logreport(report):
assert hasattr(report, 'rerun')
assert isinstance(report.rerun, int)
assert report.rerun <= 2
"""
)
result = testdir.runpytest("--reruns", "2")
assert_outcomes(result, failed=1, rerun=2, passed=0)
def test_pytest_runtest_logfinish_is_called(testdir):
hook_message = "Message from pytest_runtest_logfinish hook"
testdir.makepyfile("def test_pass(): pass")
testdir.makeconftest(
rf"""
def pytest_runtest_logfinish(nodeid, location):
print("\n{hook_message}\n")
"""
)
result = testdir.runpytest("--reruns", "1", "-s")
result.stdout.fnmatch_lines(hook_message)
@pytest.mark.parametrize(
"only_rerun_texts, should_rerun",
[
(["AssertionError"], True),
(["Assertion*"], True),
(["Assertion"], True),
(["ValueError"], False),
([""], True),
(["AssertionError: "], True),
(["AssertionError: ERR"], True),
(["ERR"], True),
(["AssertionError,ValueError"], False),
(["AssertionError ValueError"], False),
(["AssertionError", "ValueError"], True),
],
)
def test_only_rerun_flag(testdir, only_rerun_texts, should_rerun):
testdir.makepyfile("""
def test_only_rerun1():
raise AssertionError("ERR")
def test_only_rerun2():
assert False, "ERR"
""")
num_failed = 2
num_passed = 0
num_reruns = 2
num_reruns_actual = num_reruns * 2 if should_rerun else 0
pytest_args = ["--reruns", str(num_reruns)]
for only_rerun_text in only_rerun_texts:
pytest_args.extend(["--only-rerun", only_rerun_text])
result = testdir.runpytest(*pytest_args)
assert_outcomes(
result, passed=num_passed, failed=num_failed, rerun=num_reruns_actual
)
def test_no_rerun_on_strict_xfail_with_only_rerun_flag(testdir):
testdir.makepyfile(
"""
import pytest
@pytest.mark.xfail(strict=True)
def test_xfail():
assert True
"""
)
result = testdir.runpytest("--reruns", "1", "--only-rerun", "RuntimeError")
assert_outcomes(result, passed=0, failed=1, rerun=0)
@pytest.mark.parametrize(
"rerun_except_texts, should_rerun",
[
(["AssertionError"], True),
(["Assertion*"], True),
(["Assertion"], True),
(["ValueError"], False),
(["AssertionError: "], True),
(["ERR"], False),
(["AssertionError", "OSError"], True),
(["ValueError", "OSError"], False),
],
)
def test_rerun_except_flag(testdir, rerun_except_texts, should_rerun):
testdir.makepyfile('def test_rerun_except(): raise ValueError("ERR")')
num_failed = 1
num_passed = 0
num_reruns = 1
num_reruns_actual = num_reruns if should_rerun else 0
pytest_args = ["--reruns", str(num_reruns)]
for rerun_except_text in rerun_except_texts:
pytest_args.extend(["--rerun-except", rerun_except_text])
result = testdir.runpytest(*pytest_args)
assert_outcomes(
result, passed=num_passed, failed=num_failed, rerun=num_reruns_actual
)
@pytest.mark.parametrize(
"only_rerun_texts, rerun_except_texts, should_rerun",
[
# Matches --only-rerun, but not --rerun-except (rerun)
(["ValueError"], ["Not a Match"], True),
(["ValueError", "AssertionError"], ["Not a match", "OSError"], True),
# Matches --only-rerun AND --rerun-except (no rerun)
(["ValueError"], ["ERR"], False),
(["OSError", "ValueError"], ["Not a match", "ERR"], False),
# Matches --rerun-except, but not --only-rerun (no rerun)
(["OSError", "AssertionError"], ["TypeError", "ValueError"], False),
# Matches neither --only-rerun nor --rerun-except (no rerun)
(["AssertionError"], ["OSError"], False),
# --rerun-except overrides --only-rerun for same arg (no rerun)
(["ValueError"], ["ValueError"], False),
],
)
def test_rerun_except_and_only_rerun(
testdir, rerun_except_texts, only_rerun_texts, should_rerun
):
testdir.makepyfile('def test_only_rerun_except(): raise ValueError("ERR")')
num_failed = 1
num_passed = 0
num_reruns = 1
num_reruns_actual = num_reruns if should_rerun else 0
pytest_args = ["--reruns", str(num_reruns)]
for only_rerun_text in only_rerun_texts:
pytest_args.extend(["--only-rerun", only_rerun_text])
for rerun_except_text in rerun_except_texts:
pytest_args.extend(["--rerun-except", rerun_except_text])
result = testdir.runpytest(*pytest_args)
assert_outcomes(
result, passed=num_passed, failed=num_failed, rerun=num_reruns_actual
)
def test_rerun_except_passes_setup_errors(testdir):
testdir.makepyfile(
"""
import pytest
@pytest.fixture()
def fixture_setup_fails(non_existent_fixture):
return 1
def test_will_not_run(fixture_setup_fails):
assert fixture_setup_fails == 1"""
)
num_reruns = 1
pytest_args = ["--reruns", str(num_reruns), "--rerun-except", "ValueError"]
result = testdir.runpytest(*pytest_args)
assert result.ret != pytest.ExitCode.INTERNAL_ERROR
assert_outcomes(result, passed=0, error=1, rerun=num_reruns)
@pytest.mark.parametrize(
"condition, expected_reruns",
[
(1 == 1, 2),
(1 == 2, 0),
(True, 2),
(False, 0),
(1, 2),
(0, 0),
(["list"], 2),
([], 0),
({"dict": 1}, 2),
({}, 0),
(None, 0),
],
)
def test_reruns_with_condition_marker(testdir, condition, expected_reruns):
testdir.makepyfile(
f"""
import pytest
@pytest.mark.flaky(reruns=2, condition={condition})
def test_fail_two():
assert False"""
)
result = testdir.runpytest()
assert_outcomes(result, passed=0, failed=1, rerun=expected_reruns)
@pytest.mark.parametrize(
"condition, expected_reruns",
[('sys.platform.startswith("non-exists") == False', 2), ("os.getpid() != -1", 2)],
)
# before evaluating the condition expression, sys&os&platform package has been imported
def test_reruns_with_string_condition(testdir, condition, expected_reruns):
testdir.makepyfile(
f"""
import pytest
@pytest.mark.flaky(reruns=2, condition='{condition}')
def test_fail_two():
assert False"""
)
result = testdir.runpytest()
assert_outcomes(result, passed=0, failed=1, rerun=2)
def test_reruns_with_string_condition_with_global_var(testdir):
testdir.makepyfile(
"""
import pytest
rerunBool = False
@pytest.mark.flaky(reruns=2, condition='rerunBool')
def test_fail_two():
global rerunBool
rerunBool = True
assert False"""
)
result = testdir.runpytest()
assert_outcomes(result, passed=0, failed=1, rerun=2)
@pytest.mark.parametrize(
"marker_only_rerun,cli_only_rerun,should_rerun",
[
("AssertionError", None, True),
("AssertionError: ERR", None, True),
(["AssertionError"], None, True),
(["AssertionError: ABC"], None, False),
("ValueError", None, False),
(["ValueError"], None, False),
(["AssertionError", "ValueError"], None, True),
# CLI override behavior
("AssertionError", "ValueError", True),
("ValueError", "AssertionError", False),
],
)
def test_only_rerun_flag_in_flaky_marker(
testdir, marker_only_rerun, cli_only_rerun, should_rerun
):
testdir.makepyfile(
f"""
import pytest
@pytest.mark.flaky(reruns=1, only_rerun={marker_only_rerun!r})
def test_fail():
raise AssertionError("ERR")
"""
)
args = []
if cli_only_rerun:
args.extend(["--only-rerun", cli_only_rerun])
result = testdir.runpytest()
num_reruns = 1 if should_rerun else 0
assert_outcomes(result, passed=0, failed=1, rerun=num_reruns)
@pytest.mark.parametrize(
"marker_rerun_except,cli_rerun_except,raised_error,should_rerun",
[
("AssertionError", None, "AssertionError", False),
("AssertionError: ERR", None, "AssertionError", False),
(["AssertionError"], None, "AssertionError", False),
(["AssertionError: ABC"], None, "AssertionError", True),
("ValueError", None, "AssertionError", True),
(["ValueError"], None, "AssertionError", True),
(["OSError", "ValueError"], None, "AssertionError", True),
(["OSError", "AssertionError"], None, "AssertionError", False),
# CLI override behavior
("AssertionError", "ValueError", "AssertionError", False),
("ValueError", "AssertionError", "AssertionError", True),
("CustomFailure", None, "CustomFailure", False),
("CustomFailure", None, "AssertionError", True),
],
)
def test_rerun_except_flag_in_flaky_marker(
testdir, marker_rerun_except, cli_rerun_except, raised_error, should_rerun
):
testdir.makepyfile(
f"""
import pytest
class CustomFailure(Exception):
pass
@pytest.mark.flaky(reruns=1, rerun_except={marker_rerun_except!r})
def test_fail():
raise {raised_error}("ERR")
"""
)
args = []
if cli_rerun_except:
args.extend(["--rerun-except", cli_rerun_except])
result = testdir.runpytest(*args)
num_reruns = 1 if should_rerun else 0
assert_outcomes(result, passed=0, failed=1, rerun=num_reruns)
def test_ini_file_parameters(testdir):
testdir.makepyfile(
"""
import time
def test_foo():
assert False
"""
)
testdir.makeini(
"""
[pytest]
reruns = 2
reruns_delay = 3
"""
)
time.sleep = mock.MagicMock()
result = testdir.runpytest()
time.sleep.assert_called_with(3)
assert_outcomes(result, passed=0, failed=1, rerun=2)
def test_ini_file_parameters_override(testdir):
testdir.makepyfile(
"""
import time
def test_foo():
assert False
"""
)
testdir.makeini(
"""
[pytest]
reruns = 2
reruns_delay = 3
"""
)
time.sleep = mock.MagicMock()
result = testdir.runpytest("--reruns", "4", "--reruns-delay", "5")
time.sleep.assert_called_with(5)
assert_outcomes(result, passed=0, failed=1, rerun=4)
def test_run_session_teardown_once_after_reruns(testdir):
testdir.makepyfile(
"""
import logging
import pytest
from unittest import TestCase
@pytest.fixture(scope='session', autouse=True)
def session_fixture():
logging.info('session setup')
yield
logging.info('session teardown')
@pytest.fixture(scope='class', autouse=True)
def class_fixture():
logging.info('class setup')
yield
logging.info('class teardown')
@pytest.fixture(scope='function', autouse=True)
def function_fixture():
logging.info('function setup')
yield
logging.info('function teardown')
@pytest.fixture(scope='function')
def function_skip_fixture():
logging.info('skip fixture setup')
pytest.skip('some reason')
yield
logging.info('skip fixture teardown')
@pytest.fixture(scope='function')
def function_setup_fail_fixture():
logging.info('fail fixture setup')
assert False
yield
logging.info('fail fixture teardown')
class TestFirstPassLastFail:
@staticmethod
def test_1():
logging.info("TestFirstPassLastFail 1")
@staticmethod
def test_2():
logging.info("TestFirstPassLastFail 2")
assert False
class TestFirstFailLastPass:
@staticmethod
def test_1():
logging.info("TestFirstFailLastPass 1")
assert False
@staticmethod
def test_2():
logging.info("TestFirstFailLastPass 2")
class TestSkipFirst:
@staticmethod
@pytest.mark.skipif(True, reason='Some reason')
def test_1():
logging.info("TestSkipFirst 1")
assert False
@staticmethod
def test_2():
logging.info("TestSkipFirst 2")
assert False
class TestSkipLast:
@staticmethod
def test_1():
logging.info("TestSkipLast 1")
assert False
@staticmethod
@pytest.mark.skipif(True, reason='Some reason')
def test_2():
logging.info("TestSkipLast 2")
assert False
class TestSkipFixture:
@staticmethod
def test_1(function_skip_fixture):
logging.info("TestSkipFixture 1")
class TestSetupFailed: