-
Notifications
You must be signed in to change notification settings - Fork 234
/
Copy pathacceptance_test.py
1706 lines (1528 loc) · 55.1 KB
/
acceptance_test.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
import os
import re
import shutil
from typing import cast
import pytest
import xdist
class TestSingleCollectScheduling:
def test_singlecollect_mode(self, pytester: pytest.Pytester) -> None:
"""Test that the singlecollect distribution mode works."""
# Create a simple test file
p1 = pytester.makepyfile(
"""
def test_ok():
pass
"""
)
result = pytester.runpytest(p1, "-n2", "--dist=singlecollect", "-v")
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 passed*"])
# Make sure the tests are correctly distributed
result.stdout.fnmatch_lines(["*scheduling tests via SingleCollectScheduling*"])
def test_singlecollect_many_tests(self, pytester: pytest.Pytester) -> None:
"""Test that the singlecollect mode correctly distributes many tests."""
# Create test file with multiple tests
p1 = pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize("x", range(10))
def test_ok(x):
assert True
"""
)
result = pytester.runpytest(p1, "-n2", "--dist=singlecollect", "-v")
assert result.ret == 0
result.stdout.fnmatch_lines(["*passed*"])
# Make sure the tests are correctly distributed
result.stdout.fnmatch_lines(["*scheduling tests via SingleCollectScheduling*"])
def test_singlecollect_failure(self, pytester: pytest.Pytester) -> None:
"""Test that failures are correctly reported with singlecollect mode."""
p1 = pytester.makepyfile(
"""
def test_fail():
assert 0
"""
)
result = pytester.runpytest(p1, "-n2", "--dist=singlecollect", "-v")
assert result.ret == 1
result.stdout.fnmatch_lines(["*1 failed*"])
def test_singlecollect_handles_fixtures(self, pytester: pytest.Pytester) -> None:
"""Test that fixtures work correctly with singlecollect mode."""
pytester.makepyfile(
"""
import pytest
@pytest.fixture
def my_fixture():
return 42
def test_with_fixture(my_fixture):
assert my_fixture == 42
"""
)
result = pytester.runpytest("-n2", "--dist=singlecollect", "-v")
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 passed*"])
class TestDistribution:
def test_n1_pass(self, pytester: pytest.Pytester) -> None:
p1 = pytester.makepyfile(
"""
def test_ok():
pass
"""
)
result = pytester.runpytest(p1, "-n1")
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 passed*"])
def test_n1_fail(self, pytester: pytest.Pytester) -> None:
p1 = pytester.makepyfile(
"""
def test_fail():
assert 0
"""
)
result = pytester.runpytest(p1, "-n1")
assert result.ret == 1
result.stdout.fnmatch_lines(["*1 failed*"])
def test_n1_import_error(self, pytester: pytest.Pytester) -> None:
p1 = pytester.makepyfile(
"""
import __import_of_missing_module
def test_import():
pass
"""
)
result = pytester.runpytest(p1, "-n1")
assert result.ret == 1
result.stdout.fnmatch_lines(
["E *Error: No module named *__import_of_missing_module*"]
)
def test_n2_import_error(self, pytester: pytest.Pytester) -> None:
"""Check that we don't report the same import error multiple times
in distributed mode."""
p1 = pytester.makepyfile(
"""
import __import_of_missing_module
def test_import():
pass
"""
)
result1 = pytester.runpytest(p1, "-n2")
result2 = pytester.runpytest(p1, "-n1")
assert len(result1.stdout.lines) == len(result2.stdout.lines)
def test_n1_skip(self, pytester: pytest.Pytester) -> None:
p1 = pytester.makepyfile(
"""
def test_skip():
import pytest
pytest.skip("myreason")
"""
)
result = pytester.runpytest(p1, "-n1")
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 skipped*"])
def test_manytests_to_one_import_error(self, pytester: pytest.Pytester) -> None:
p1 = pytester.makepyfile(
"""
import __import_of_missing_module
def test_import():
pass
"""
)
result = pytester.runpytest(p1, "--tx=popen", "--tx=popen")
assert result.ret in (1, 2)
result.stdout.fnmatch_lines(
["E *Error: No module named *__import_of_missing_module*"]
)
def test_manytests_to_one_popen(self, pytester: pytest.Pytester) -> None:
p1 = pytester.makepyfile(
"""
import pytest
def test_fail0():
assert 0
def test_fail1():
raise ValueError()
def test_ok():
pass
def test_skip():
pytest.skip("hello")
"""
)
result = pytester.runpytest(p1, "-v", "-d", "--tx=popen", "--tx=popen")
result.stdout.fnmatch_lines(
[
"created: 2/2 workers",
"*2 failed, 1 passed, 1 skipped*",
]
)
assert result.ret == 1
def test_exitfirst_waits_for_workers_to_finish(
self, pytester: pytest.Pytester
) -> None:
"""The DSession waits for workers before exiting early on failure.
When -x/--exitfirst is set, the DSession wait for all workers to finish
before raising an Interrupt exception. This prevents reports from the
faiing test and other tests from being discarded.
"""
p1 = pytester.makepyfile(
"""
import time
def test_fail1():
time.sleep(0.1)
assert 0
def test_fail2():
time.sleep(0.2)
def test_fail3():
time.sleep(0.3)
assert 0
def test_fail4():
time.sleep(0.3)
def test_fail5():
time.sleep(0.3)
def test_fail6():
time.sleep(0.3)
"""
)
# Two workers are used
result = pytester.runpytest(p1, "-x", "-rA", "-v", "-n2")
assert result.ret == 2
# DSession should stop when the first failure is reached. Two failures
# may actually occur, due to timing.
outcomes = result.parseoutcomes()
assert "failed" in outcomes, "Expected at least one failure"
assert 1 <= outcomes["failed"] <= 2, "Expected no more than 2 failures"
def test_basetemp_in_subprocesses(self, pytester: pytest.Pytester) -> None:
p1 = pytester.makepyfile(
"""
def test_send(tmp_path):
from pathlib import Path
assert tmp_path.relative_to(Path(%r)), tmp_path
"""
% str(pytester.path)
)
result = pytester.runpytest_subprocess(p1, "-n1")
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 passed*"])
def test_dist_ini_specified(self, pytester: pytest.Pytester) -> None:
p1 = pytester.makepyfile(
"""
import pytest
def test_fail0():
assert 0
def test_fail1():
raise ValueError()
def test_ok():
pass
def test_skip():
pytest.skip("hello")
"""
)
pytester.makeini(
"""
[pytest]
addopts = --tx=3*popen
"""
)
result = pytester.runpytest(p1, "-d", "-v")
result.stdout.fnmatch_lines(
[
"created: 3/3 workers",
"*2 failed, 1 passed, 1 skipped*",
]
)
assert result.ret == 1
def test_dist_tests_with_crash(self, pytester: pytest.Pytester) -> None:
if not hasattr(os, "kill"):
pytest.skip("no os.kill")
p1 = pytester.makepyfile(
"""
import pytest
def test_fail0():
assert 0
def test_fail1():
raise ValueError()
def test_ok():
pass
def test_skip():
pytest.skip("hello")
def test_crash():
import time
import os
time.sleep(0.5)
os.kill(os.getpid(), 15)
"""
)
result = pytester.runpytest(p1, "-v", "-d", "-n1")
result.stdout.fnmatch_lines(
[
"*Python*",
"*PASS**test_ok*",
"*node*down*",
"*3 failed, 1 passed, 1 skipped*",
]
)
assert result.ret == 1
def test_distribution_rsyncdirs_example(
self, pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch
) -> None:
# use a custom plugin that has a custom command-line option to ensure
# this is propagated to workers (see #491)
pytester.makepyfile(
**{
"myplugin/src/foobarplugin.py": """
from __future__ import print_function
import os
import sys
import pytest
def pytest_addoption(parser):
parser.addoption("--foobar", action="store", dest="foobar_opt")
@pytest.hookimpl(tryfirst=True)
def pytest_load_initial_conftests(early_config):
opt = early_config.known_args_namespace.foobar_opt
print("--foobar=%s active! [%s]" % (opt, os.getpid()), file=sys.stderr)
"""
}
)
assert (pytester.path / "myplugin/src/foobarplugin.py").is_file()
monkeypatch.setenv(
"PYTHONPATH", str(pytester.path / "myplugin/src"), prepend=os.pathsep
)
source = pytester.mkdir("source")
dest = pytester.mkdir("dest")
subdir = source / "example_pkg"
subdir.mkdir()
subdir.joinpath("__init__.py").touch()
p = subdir / "test_one.py"
p.write_text("def test_5():\n assert not __file__.startswith(%r)" % str(p))
result = pytester.runpytest_subprocess(
"-v",
"-d",
"-s",
"-pfoobarplugin",
"--foobar=123",
"--dist=load",
f"--rsyncdir={subdir}",
f"--tx=popen//chdir={dest}",
p,
)
assert result.ret == 0
result.stdout.fnmatch_lines(
[
"*1 passed*",
]
)
result.stderr.fnmatch_lines(["--foobar=123 active! *"])
assert dest.joinpath(subdir.name).is_dir()
def test_data_exchange(self, pytester: pytest.Pytester) -> None:
pytester.makeconftest(
"""
# This hook only called on the controlling process.
def pytest_configure_node(node):
node.workerinput['a'] = 42
node.workerinput['b'] = 7
def pytest_configure(config):
# this attribute is only set on workers
if hasattr(config, 'workerinput'):
a = config.workerinput['a']
b = config.workerinput['b']
r = a + b
config.workeroutput['r'] = r
# This hook only called on the controlling process.
def pytest_testnodedown(node, error):
node.config.calc_result = node.workeroutput['r']
def pytest_terminal_summary(terminalreporter):
if not hasattr(terminalreporter.config, 'workerinput'):
calc_result = terminalreporter.config.calc_result
terminalreporter._tw.sep('-',
'calculated result is %s' % calc_result)
"""
)
p1 = pytester.makepyfile("def test_func(): pass")
result = pytester.runpytest("-v", p1, "-d", "--tx=popen")
result.stdout.fnmatch_lines(
[
"created: 1/1 worker",
"*calculated result is 49*",
"*1 passed*",
]
)
assert result.ret == 0
def test_keyboardinterrupt_hooks_issue79(self, pytester: pytest.Pytester) -> None:
pytester.makepyfile(
__init__="",
test_one="""
def test_hello():
raise KeyboardInterrupt()
""",
)
pytester.makeconftest(
"""
def pytest_sessionfinish(session):
# on the worker
if hasattr(session.config, 'workeroutput'):
session.config.workeroutput['s2'] = 42
# on the controller
def pytest_testnodedown(node, error):
assert node.workeroutput['s2'] == 42
print ("s2call-finished")
"""
)
args = ["-n1", "--debug"]
result = pytester.runpytest_subprocess(*args)
s = result.stdout.str()
assert result.ret == 2
assert "s2call" in s
assert "Interrupted" in s
def test_keyboard_interrupt_dist(self, pytester: pytest.Pytester) -> None:
# xxx could be refined to check for return code
pytester.makepyfile(
"""
def test_sleep():
import time
time.sleep(10)
"""
)
child = pytester.spawn_pytest("-n1 -v", expect_timeout=30.0)
child.expect(".*test_sleep.*")
child.kill(2) # keyboard interrupt
child.expect(".*KeyboardInterrupt.*")
# child.expect(".*seconds.*")
child.close()
# assert ret == 2
def test_dist_with_collectonly(self, pytester: pytest.Pytester) -> None:
p1 = pytester.makepyfile(
"""
def test_ok():
pass
"""
)
result = pytester.runpytest(p1, "-n1", "--collect-only")
assert result.ret == 0
result.stdout.fnmatch_lines(["*collected 1 item*"])
class TestDistEach:
def test_simple(self, pytester: pytest.Pytester) -> None:
pytester.makepyfile(
"""
def test_hello():
pass
"""
)
result = pytester.runpytest_subprocess("--debug", "--dist=each", "--tx=2*popen")
assert not result.ret
result.stdout.fnmatch_lines(["*2 pass*"])
@pytest.mark.xfail(
run=False, reason="other python versions might not have pytest installed"
)
def test_simple_diffoutput(self, pytester: pytest.Pytester) -> None:
interpreters = []
for name in ("python2.5", "python2.6"):
interp = shutil.which(name)
if interp is None:
pytest.skip("%s not found" % name)
interpreters.append(interp)
pytester.makepyfile(
__init__="",
test_one="""
import sys
def test_hello():
print("%s...%s" % sys.version_info[:2])
assert 0
""",
)
args = ["--dist=each", "-v"]
args += ["--tx", "popen//python=%s" % interpreters[0]]
args += ["--tx", "popen//python=%s" % interpreters[1]]
result = pytester.runpytest(*args)
s = result.stdout.str()
assert "2...5" in s
assert "2...6" in s
class TestTerminalReporting:
@pytest.mark.parametrize("verbosity", ["", "-q", "-v"])
def test_output_verbosity(self, pytester: pytest.Pytester, verbosity: str) -> None:
pytester.makepyfile(
"""
def test_ok():
pass
"""
)
args = ["-n1"]
if verbosity:
args.append(verbosity)
result = pytester.runpytest(*args)
out = result.stdout.str()
if verbosity == "-v":
assert "scheduling tests" in out
assert "1 worker [1 item]" in out
elif verbosity == "-q":
assert "scheduling tests" not in out
assert "gw" not in out
assert "bringing up nodes..." in out
else:
assert "scheduling tests" not in out
assert "1 worker [1 item]" in out
def test_pass_skip_fail(self, pytester: pytest.Pytester) -> None:
pytester.makepyfile(
"""
import pytest
def test_ok():
pass
def test_skip():
pytest.skip("xx")
def test_func():
assert 0
"""
)
result = pytester.runpytest("-n1", "-v")
result.stdout.fnmatch_lines_random(
[
"*PASS*test_pass_skip_fail.py*test_ok*",
"*SKIP*test_pass_skip_fail.py*test_skip*",
"*FAIL*test_pass_skip_fail.py*test_func*",
]
)
result.stdout.fnmatch_lines(
["*def test_func():", "> assert 0", "E assert 0"]
)
def test_fail_platinfo(self, pytester: pytest.Pytester) -> None:
pytester.makepyfile(
"""
def test_func():
assert 0
"""
)
result = pytester.runpytest("-n1", "-v")
result.stdout.fnmatch_lines(
[
"*FAIL*test_fail_platinfo.py*test_func*",
"*0*Python*",
"*def test_func():",
"> assert 0",
"E assert 0",
]
)
def test_logfinish_hook(self, pytester: pytest.Pytester) -> None:
"""Ensure the pytest_runtest_logfinish hook is being properly handled."""
pytester.makeconftest(
"""
def pytest_runtest_logfinish():
print('pytest_runtest_logfinish hook called')
"""
)
pytester.makepyfile(
"""
def test_func():
pass
"""
)
result = pytester.runpytest("-n1", "-s")
result.stdout.fnmatch_lines(["*pytest_runtest_logfinish hook called*"])
def test_teardownfails_one_function(pytester: pytest.Pytester) -> None:
p = pytester.makepyfile(
"""
def test_func():
pass
def teardown_function(function):
assert 0
"""
)
result = pytester.runpytest(p, "-n1", "--tx=popen")
result.stdout.fnmatch_lines(
["*def teardown_function(function):*", "*1 passed*1 error*"]
)
@pytest.mark.xfail
def test_terminate_on_hangingnode(pytester: pytest.Pytester) -> None:
p = pytester.makeconftest(
"""
def pytest_sessionfinish(session):
if session.nodeid == "my": # running on worker
import time
time.sleep(3)
"""
)
result = pytester.runpytest(p, "--dist=each", "--tx=popen//id=my")
assert result.duration < 2.0
result.stdout.fnmatch_lines(["*killed*my*"])
@pytest.mark.xfail(reason="works if run outside test suite", run=False)
def test_session_hooks(pytester: pytest.Pytester) -> None:
pytester.makeconftest(
"""
import sys
def pytest_sessionstart(session):
sys.pytestsessionhooks = session
def pytest_sessionfinish(session):
if hasattr(session.config, 'workerinput'):
name = "worker"
else:
name = "controller"
with open(name, "w") as f:
f.write("xy")
# let's fail on the worker
if name == "worker":
raise ValueError(42)
"""
)
p = pytester.makepyfile(
"""
import sys
def test_hello():
assert hasattr(sys, 'pytestsessionhooks')
"""
)
result = pytester.runpytest(p, "--dist=each", "--tx=popen")
result.stdout.fnmatch_lines(["*ValueError*", "*1 passed*"])
assert not result.ret
d = result.parseoutcomes()
assert d["passed"] == 1
assert pytester.path.joinpath("worker").exists()
assert pytester.path.joinpath("controller").exists()
def test_session_testscollected(pytester: pytest.Pytester) -> None:
"""
Make sure controller node is updating the session object with the number
of tests collected from the workers.
"""
pytester.makepyfile(
test_foo="""
import pytest
@pytest.mark.parametrize('i', range(3))
def test_ok(i):
pass
"""
)
pytester.makeconftest(
"""
def pytest_sessionfinish(session):
collected = getattr(session, 'testscollected', None)
with open('testscollected', 'w') as f:
f.write('collected = %s' % collected)
"""
)
result = pytester.inline_run("-n1")
result.assertoutcome(passed=3)
collected_file = pytester.path / "testscollected"
assert collected_file.is_file()
assert collected_file.read_text() == "collected = 3"
def test_fixture_teardown_failure(pytester: pytest.Pytester) -> None:
p = pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="module")
def myarg(request):
yield 42
raise ValueError(42)
def test_hello(myarg):
pass
"""
)
result = pytester.runpytest_subprocess(p, "-n1")
result.stdout.fnmatch_lines(["*ValueError*42*", "*1 passed*1 error*"])
assert result.ret
def test_config_initialization(
pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Ensure workers and controller are initialized consistently. Integration test for #445."""
pytester.makepyfile(
**{
"dir_a/test_foo.py": """
def test_1(request):
assert request.config.option.verbose == 2
"""
}
)
pytester.makefile(
".ini",
myconfig="""
[pytest]
testpaths=dir_a
""",
)
monkeypatch.setenv("PYTEST_ADDOPTS", "-v")
result = pytester.runpytest("-n2", "-c", "myconfig.ini", "-v")
result.stdout.fnmatch_lines(["dir_a/test_foo.py::test_1*", "*= 1 passed in *"])
assert result.ret == 0
@pytest.mark.parametrize("when", ["setup", "call", "teardown"])
def test_crashing_item(pytester: pytest.Pytester, when: str) -> None:
"""Ensure crashing item is correctly reported during all testing stages."""
code = dict(setup="", call="", teardown="")
code[when] = "os._exit(1)"
p = pytester.makepyfile(
"""
import os
import pytest
@pytest.fixture
def fix():
{setup}
yield
{teardown}
def test_crash(fix):
{call}
pass
def test_ok():
pass
""".format(**code)
)
passes = 2 if when == "teardown" else 1
result = pytester.runpytest("-n2", p)
result.stdout.fnmatch_lines(
["*crashed*test_crash*", "*1 failed*%d passed*" % passes]
)
def test_multiple_log_reports(pytester: pytest.Pytester) -> None:
"""
Ensure that pytest-xdist supports plugins that emit multiple logreports
(#206).
Inspired by pytest-rerunfailures.
"""
pytester.makeconftest(
"""
from _pytest.runner import runtestprotocol
def pytest_runtest_protocol(item, nextitem):
item.ihook.pytest_runtest_logstart(nodeid=item.nodeid,
location=item.location)
reports = runtestprotocol(item, nextitem=nextitem)
for report in reports:
item.ihook.pytest_runtest_logreport(report=report)
return True
"""
)
pytester.makepyfile(
"""
def test():
pass
"""
)
result = pytester.runpytest("-n1")
result.stdout.fnmatch_lines(["*2 passed*"])
def test_skipping(pytester: pytest.Pytester) -> None:
p = pytester.makepyfile(
"""
import pytest
def test_crash():
pytest.skip("hello")
"""
)
result = pytester.runpytest("-n1", "-rs", p)
assert result.ret == 0
result.stdout.fnmatch_lines(["*hello*", "*1 skipped*"])
def test_fixture_scope_caching_issue503(pytester: pytest.Pytester) -> None:
p1 = pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='session')
def fix():
assert fix.counter == 0, \
'session fixture was invoked multiple times'
fix.counter += 1
fix.counter = 0
def test_a(fix):
pass
def test_b(fix):
pass
"""
)
result = pytester.runpytest(p1, "-v", "-n1")
assert result.ret == 0
result.stdout.fnmatch_lines(["*2 passed*"])
def test_issue_594_random_parametrize(pytester: pytest.Pytester) -> None:
"""
Make sure that tests that are randomly parametrized display an appropriate
error message, instead of silently skipping the entire test run.
"""
p1 = pytester.makepyfile(
"""
import pytest
import random
xs = list(range(10))
random.shuffle(xs)
@pytest.mark.parametrize('x', xs)
def test_foo(x):
assert 1
"""
)
result = pytester.runpytest(p1, "-v", "-n4")
assert result.ret == 1
result.stdout.fnmatch_lines(["Different tests were collected between gw* and gw*"])
def test_tmpdir_disabled(pytester: pytest.Pytester) -> None:
"""Test xdist doesn't break if internal tmpdir plugin is disabled (#22)."""
p1 = pytester.makepyfile(
"""
def test_ok():
pass
"""
)
result = pytester.runpytest(p1, "-n1", "-p", "no:tmpdir")
assert result.ret == 0
result.stdout.fnmatch_lines("*1 passed*")
@pytest.mark.parametrize("plugin", ["xdist.looponfail"])
def test_sub_plugins_disabled(pytester: pytest.Pytester, plugin: str) -> None:
"""Test that xdist doesn't break if we disable any of its sub-plugins (#32)."""
p1 = pytester.makepyfile(
"""
def test_ok():
pass
"""
)
result = pytester.runpytest(p1, "-n1", "-p", f"no:{plugin}")
assert result.ret == 0
result.stdout.fnmatch_lines("*1 passed*")
class TestWarnings:
@pytest.mark.parametrize("n", ["-n0", "-n1"])
def test_warnings(self, pytester: pytest.Pytester, n: str) -> None:
pytester.makepyfile(
"""
import warnings, py, pytest
@pytest.mark.filterwarnings('ignore:config.warn has been deprecated')
def test_func(request):
warnings.warn(UserWarning('this is a warning'))
"""
)
result = pytester.runpytest(n)
result.stdout.fnmatch_lines(["*this is a warning*", "*1 passed, 1 warning*"])
def test_warning_captured_deprecated_in_pytest_6(
self, pytester: pytest.Pytester
) -> None:
"""Do not trigger the deprecated pytest_warning_captured hook in pytest 6+ (#562)."""
from _pytest import hookspec
if not hasattr(hookspec, "pytest_warning_captured"):
pytest.skip(
f"pytest {pytest.__version__} does not have the pytest_warning_captured hook."
)
pytester.makeconftest(
"""
def pytest_warning_captured(warning_message):
if warning_message == "my custom worker warning":
assert False, (
"this hook should not be called from workers "
"in this version: {}"
).format(warning_message)
"""
)
pytester.makepyfile(
"""
import warnings
def test():
warnings.warn("my custom worker warning")
"""
)
result = pytester.runpytest("-n1", "-Wignore")
result.stdout.fnmatch_lines(["*1 passed*"])
result.stdout.no_fnmatch_line("*this hook should not be called in this version")
@pytest.mark.parametrize("n", ["-n0", "-n1"])
def test_custom_subclass(self, pytester: pytest.Pytester, n: str) -> None:
"""Check that warning subclasses that don't honor the args attribute don't break
pytest-xdist (#344).
"""
pytester.makepyfile(
"""
import warnings, py, pytest
class MyWarning(UserWarning):
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
self.args = ()
def test_func(request):
warnings.warn(MyWarning("foo", 1))
"""
)
pytester.syspathinsert()
result = pytester.runpytest(n)
result.stdout.fnmatch_lines(["*MyWarning*", "*1 passed, 1 warning*"])
@pytest.mark.parametrize("n", ["-n0", "-n1"])
def test_unserializable_arguments(self, pytester: pytest.Pytester, n: str) -> None:
"""Check that warnings with unserializable arguments are handled correctly (#349)."""
pytester.makepyfile(
"""
import warnings, pytest
def test_func(tmp_path):
fn = tmp_path / 'foo.txt'
fn.touch()
with fn.open('r') as f:
warnings.warn(UserWarning("foo", f))
"""
)
pytester.syspathinsert()
result = pytester.runpytest(n)
result.stdout.fnmatch_lines(["*UserWarning*foo.txt*", "*1 passed, 1 warning*"])
@pytest.mark.parametrize("n", ["-n0", "-n1"])
def test_unserializable_warning_details(
self, pytester: pytest.Pytester, n: str
) -> None:
"""Check that warnings with unserializable _WARNING_DETAILS are
handled correctly (#379).
"""
pytester.makepyfile(
"""
import warnings, pytest
import socket
import gc
def abuse_socket():
s = socket.socket()
del s
# Deliberately provoke a ResourceWarning for an unclosed socket.
# The socket itself will end up attached as a value in
# _WARNING_DETAIL. We need to test that it is not serialized
# (it can't be, so the test will fail if we try to).
@pytest.mark.filterwarnings('always')
def test_func(tmp_path):
abuse_socket()
gc.collect()
"""
)
pytester.syspathinsert()
result = pytester.runpytest(n)
result.stdout.fnmatch_lines(
["*ResourceWarning*unclosed*", "*1 passed, 1 warning*"]
)
class TestNodeFailure:
def test_load_single(self, pytester: pytest.Pytester) -> None:
f = pytester.makepyfile(
"""
import os
def test_a(): os._exit(1)
def test_b(): pass
"""
)
res = pytester.runpytest(f, "-n1")
res.stdout.fnmatch_lines(
[
"replacing crashed worker gw*",
"worker*crashed while running*",
"*1 failed*1 passed*",
]
)
def test_load_multiple(self, pytester: pytest.Pytester) -> None:
f = pytester.makepyfile(
"""
import os
def test_a(): pass
def test_b(): os._exit(1)
def test_c(): pass
def test_d(): pass
"""
)
res = pytester.runpytest(f, "-n2")
res.stdout.fnmatch_lines(
[
"replacing crashed worker gw*",
"worker*crashed while running*",