-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathtest_pytest_randomly.py
857 lines (654 loc) · 21.2 KB
/
test_pytest_randomly.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
from __future__ import annotations
import shutil
from unittest import mock
import pytest
import pytest_randomly
pytest_plugins = ["pytester"]
@pytest.fixture(autouse=True)
def reset_entrypoints_cache():
yield
pytest_randomly.entrypoint_reseeds = None
@pytest.fixture
def ourtester(pytester):
pytester.makefile(
".ini",
pytest="""
[pytest]
console_output_style = classic
""",
)
# Change from default running pytest in-process to running in a subprocess
# because numpy imports break with weird:
# File ".../site-packages/numpy/core/overrides.py", line 204, in decorator
# add_docstring(implementation, dispatcher.__doc__)
# RuntimeError: empty_like method already has a docstring
# testdir._runpytest_method = testdir.runpytest_subprocess
yield pytester
@pytest.fixture
def simpletester(ourtester):
ourtester.makepyfile(
test_one="""
def test_a():
assert True
""",
)
yield ourtester
def test_it_reports_a_header_when_not_set(simpletester):
out = simpletester.runpytest()
assert len([x for x in out.outlines if x.startswith("Using --randomly-seed=")]) == 1
def test_it_reports_a_header_when_set(simpletester):
out = simpletester.runpytest("--randomly-seed=10")
lines = [x for x in out.outlines if x.startswith("Using --randomly-seed=")]
assert lines == ["Using --randomly-seed=10"]
def test_it_reuses_the_same_random_seed_per_test(ourtester):
"""
Run a pair of tests that generate the a number and then assert they got
what the other did.
"""
ourtester.makepyfile(
test_one="""
import random
def test_a():
test_a.num = random.random()
if hasattr(test_b, 'num'):
assert test_a.num == test_b.num
def test_b():
test_b.num = random.random()
if hasattr(test_a, 'num'):
assert test_b.num == test_a.num
"""
)
out = ourtester.runpytest(
"--randomly-dont-reorganize", "--randomly-dont-seed-per-test"
)
out.assert_outcomes(passed=2, failed=0)
def test_it_uses_different_random_seed_per_test(ourtester):
"""
Run a pair of tests that generate a number and assert they produce
different numbers.
"""
ourtester.makepyfile(
test_one="""
import random
def test_a():
test_a.num = random.random()
if hasattr(test_b, 'num'):
assert test_a.num != test_b.num
def test_b():
test_b.num = random.random()
if hasattr(test_a, 'num'):
assert test_b.num != test_a.num
"""
)
out = ourtester.runpytest()
out.assert_outcomes(passed=2, failed=0)
def test_without_cacheprovider(ourtester):
ourtester.makepyfile(
test_one="""
def test_a():
pass
"""
)
out = ourtester.runpytest("-p", "no:cacheprovider")
out.assert_outcomes(passed=1, failed=0)
def test_using_last_seed(ourtester):
ourtester.makepyfile(
test_one="""
def test_a():
pass
"""
)
out = ourtester.runpytest()
out.assert_outcomes(passed=1, failed=0)
seed_line = [x for x in out.stdout.lines if x.startswith("Using --randomly-seed=")][
0
]
out = ourtester.runpytest("--randomly-seed=last")
out.assert_outcomes(passed=1, failed=0)
out.stdout.fnmatch_lines([seed_line])
def test_using_last_explicit_seed(ourtester):
ourtester.makepyfile(
test_one="""
def test_a():
pass
"""
)
out = ourtester.runpytest("--randomly-seed=33")
out.assert_outcomes(passed=1, failed=0)
out.stdout.fnmatch_lines(["Using --randomly-seed=33"])
out = ourtester.runpytest("--randomly-seed=last")
out.assert_outcomes(passed=1, failed=0)
out.stdout.fnmatch_lines(["Using --randomly-seed=33"])
def test_passing_nonsense_for_randomly_seed(ourtester):
ourtester.makepyfile(
test_one="""
def test_a():
pass
"""
)
out = ourtester.runpytest("--randomly-seed=invalidvalue")
assert out.ret != 0
out.stderr.fnmatch_lines(
[
(
"*: error: argument --randomly-seed: 'invalidvalue' "
+ "is not an integer or the string 'last'"
)
]
)
def test_it_resets_the_random_seed_at_the_start_of_test_classes(ourtester):
ourtester.makepyfile(
test_one="""
import random
from unittest import TestCase
class A(TestCase):
@classmethod
def setUpClass(cls):
super(A, cls).setUpClass()
cls.suc_num = random.random()
assert cls.suc_num == getattr(B, 'suc_num', cls.suc_num)
def test_fake(self):
assert True
class B(TestCase):
@classmethod
def setUpClass(cls):
super(B, cls).setUpClass()
cls.suc_num = random.random()
assert cls.suc_num == getattr(A, 'suc_num', cls.suc_num)
def test_fake(self):
assert True
"""
)
out = ourtester.runpytest()
out.assert_outcomes(passed=2, failed=0)
def test_it_resets_the_random_seed_at_the_end_of_test_classes(ourtester):
ourtester.makepyfile(
test_one="""
import random
from unittest import TestCase
class A(TestCase):
def test_fake(self):
assert True
@classmethod
def tearDownClass(cls):
super(A, cls).tearDownClass()
cls.suc_num = random.random()
assert cls.suc_num == getattr(B, 'suc_num', cls.suc_num)
class B(TestCase):
def test_fake(self):
assert True
@classmethod
def tearDownClass(cls):
super(B, cls).tearDownClass()
cls.suc_num = random.random()
assert cls.suc_num == getattr(A, 'suc_num', cls.suc_num)
"""
)
out = ourtester.runpytest()
out.assert_outcomes(passed=2, failed=0)
def test_the_same_random_seed_per_test_can_be_turned_off(ourtester):
ourtester.makepyfile(
test_one="""
import random
def test_a():
test_a.state1 = random.getstate()
assert test_a.state1 == random.getstate() # sanity check
assert random.random() >= 0 # mutate state
test_a.state2 = random.getstate()
def test_b():
test_b.state = random.getstate()
assert test_b.state == random.getstate() # sanity check
assert test_a.state1 != test_b.state
assert test_a.state2 == test_b.state
"""
)
out = ourtester.runpytest(
"--randomly-dont-reset-seed", "--randomly-dont-reorganize"
)
out.assert_outcomes(passed=2, failed=0)
def test_files_reordered(ourtester):
code = """
def test_it():
pass
"""
ourtester.makepyfile(test_a=code, test_b=code, test_c=code, test_d=code)
args = ["-v", "--randomly-seed=15"]
out = ourtester.runpytest(*args)
out.assert_outcomes(passed=4, failed=0)
assert out.outlines[9:13] == [
"test_b.py::test_it PASSED",
"test_a.py::test_it PASSED",
"test_d.py::test_it PASSED",
"test_c.py::test_it PASSED",
]
def test_files_reordered_when_seed_not_reset(ourtester):
code = """
def test_it():
pass
"""
ourtester.makepyfile(test_a=code, test_b=code, test_c=code, test_d=code)
args = ["-v", "--randomly-seed=15"]
args.append("--randomly-dont-reset-seed")
out = ourtester.runpytest(*args)
out.assert_outcomes(passed=4, failed=0)
assert out.outlines[9:13] == [
"test_b.py::test_it PASSED",
"test_a.py::test_it PASSED",
"test_d.py::test_it PASSED",
"test_c.py::test_it PASSED",
]
def test_classes_reordered(ourtester):
ourtester.makepyfile(
test_one="""
from unittest import TestCase
class A(TestCase):
def test_a(self):
pass
class B(TestCase):
def test_b(self):
pass
class C(TestCase):
def test_c(self):
pass
class D(TestCase):
def test_d(self):
pass
"""
)
args = ["-v", "--randomly-seed=15"]
out = ourtester.runpytest(*args)
out.assert_outcomes(passed=4, failed=0)
assert out.outlines[9:13] == [
"test_one.py::D::test_d PASSED",
"test_one.py::B::test_b PASSED",
"test_one.py::C::test_c PASSED",
"test_one.py::A::test_a PASSED",
]
def test_class_test_methods_reordered(ourtester):
ourtester.makepyfile(
test_one="""
from unittest import TestCase
class T(TestCase):
def test_a(self):
pass
def test_b(self):
pass
def test_c(self):
pass
def test_d(self):
pass
"""
)
args = ["-v", "--randomly-seed=15"]
out = ourtester.runpytest(*args)
out.assert_outcomes(passed=4, failed=0)
assert out.outlines[9:13] == [
"test_one.py::T::test_c PASSED",
"test_one.py::T::test_b PASSED",
"test_one.py::T::test_a PASSED",
"test_one.py::T::test_d PASSED",
]
def test_test_functions_reordered(ourtester):
ourtester.makepyfile(
test_one="""
def test_a():
pass
def test_b():
pass
def test_c():
pass
def test_d():
pass
"""
)
args = ["-v", "--randomly-seed=15"]
out = ourtester.runpytest(*args)
out.assert_outcomes(passed=4, failed=0)
assert out.outlines[9:13] == [
"test_one.py::test_c PASSED",
"test_one.py::test_a PASSED",
"test_one.py::test_b PASSED",
"test_one.py::test_d PASSED",
]
def test_test_functions_reordered_when_randomness_in_module(ourtester):
ourtester.makepyfile(
test_one="""
import random
import time
random.seed(time.time() * 100)
def test_a():
pass
def test_b():
pass
def test_c():
pass
def test_d():
pass
"""
)
args = ["-v", "--randomly-seed=15"]
out = ourtester.runpytest(*args)
out.assert_outcomes(passed=4, failed=0)
assert out.outlines[9:13] == [
"test_one.py::test_c PASSED",
"test_one.py::test_a PASSED",
"test_one.py::test_b PASSED",
"test_one.py::test_d PASSED",
]
def test_doctests_reordered(ourtester):
ourtester.makepyfile(
test_one="""
def foo():
'''
>>> foo()
9001
'''
return 9001
def bar():
'''
>>> bar()
9002
'''
return 9002
"""
)
args = ["-v", "--doctest-modules", "--randomly-seed=1"]
out = ourtester.runpytest(*args)
out.assert_outcomes(passed=2)
assert out.outlines[9:11] == [
"test_one.py::test_one.bar PASSED",
"test_one.py::test_one.foo PASSED",
]
def test_it_works_with_the_simplest_test_items(ourtester):
ourtester.makepyfile(
conftest="""
import sys
import pytest
class MyCollector(pytest.Collector):
def __init__(self, fspath, items, **kwargs):
super(MyCollector, self).__init__(fspath, **kwargs)
self.items = items
def collect(self):
return self.items
class NoOpItem(pytest.Item):
def __init__(self, name, parent, module=None):
super(NoOpItem, self).__init__(name=name, parent=parent)
if module is not None:
self.module = module
def runtest(self):
pass
def pytest_collect_file(path, parent):
if not str(path).endswith('.py'):
return
return MyCollector.from_parent(
parent=parent,
fspath=str(path),
items=[
NoOpItem.from_parent(
name=str(path) + "1",
parent=parent,
module=sys.modules[__name__],
),
NoOpItem.from_parent(
name=str(path) + "1",
parent=parent,
module=sys.modules[__name__],
),
NoOpItem.from_parent(
name=str(path) + "2",
parent=parent,
),
],
)
"""
)
args = ["-v"]
out = ourtester.runpytest(*args)
out.assert_outcomes(passed=3)
def test_doctests_in_txt_files_reordered(ourtester):
ourtester.makefile(
".txt",
test="""
>>> 2 + 2
4
""",
test2="""
>>> 2 - 2
0
""",
)
args = ["-v", "--randomly-seed=2"]
out = ourtester.runpytest(*args)
out.assert_outcomes(passed=2)
assert out.outlines[9:11] == [
"test2.txt::test2.txt PASSED",
"test.txt::test.txt PASSED",
]
def test_it_runs_before_stepwise(ourtester):
ourtester.makepyfile(
test_one="""
def test_a():
assert 0
def test_b():
assert 0
"""
)
out = ourtester.runpytest("-v", "--randomly-seed=1", "--stepwise")
out.assert_outcomes(failed=1)
# Now make test_b pass
ourtester.makepyfile(
test_one="""
def test_a():
assert 0
def test_b():
assert 1
"""
)
shutil.rmtree(ourtester.path / "__pycache__")
out = ourtester.runpytest("-v", "--randomly-seed=1", "--stepwise")
out.assert_outcomes(passed=1, failed=1)
out = ourtester.runpytest("-v", "--randomly-seed=1", "--stepwise")
out.assert_outcomes(failed=1)
def test_fixtures_get_different_random_state_to_tests(ourtester):
ourtester.makepyfile(
test_one="""
import random
import pytest
@pytest.fixture()
def myfixture():
return random.getstate()
def test_one(myfixture):
assert myfixture != random.getstate()
"""
)
out = ourtester.runpytest()
out.assert_outcomes(passed=1)
def test_fixtures_dont_interfere_with_tests_getting_same_random_state(ourtester):
ourtester.makepyfile(
test_one="""
import random
import pytest
random.seed(2)
state_at_seed_two = random.getstate()
@pytest.fixture(scope='module')
def myfixture():
return random.random()
@pytest.mark.one()
def test_one(myfixture):
assert random.getstate() == state_at_seed_two
@pytest.mark.two()
def test_two(myfixture):
assert random.getstate() == state_at_seed_two
"""
)
args = ["--randomly-seed=2", "--randomly-dont-seed-per-test"]
out = ourtester.runpytest(*args)
out.assert_outcomes(passed=2)
out = ourtester.runpytest("-m", "one", *args)
out.assert_outcomes(passed=1)
out = ourtester.runpytest("-m", "two", *args)
out.assert_outcomes(passed=1)
def test_factory_boy(ourtester):
"""
Rather than set up factories etc., just check the random generator it uses
is set between two tests to output the same number.
"""
ourtester.makepyfile(
test_one="""
from factory.random import randgen
def test_a():
test_a.num = randgen.random()
if hasattr(test_b, 'num'):
assert test_a.num == test_b.num
def test_b():
test_b.num = randgen.random()
if hasattr(test_a, 'num'):
assert test_b.num == test_a.num
"""
)
out = ourtester.runpytest("--randomly-seed=1", "--randomly-dont-seed-per-test")
out.assert_outcomes(passed=2)
def test_faker(ourtester):
ourtester.makepyfile(
test_one="""
from faker import Faker
fake = Faker()
def test_one():
assert fake.name() == 'Justin Richard'
def test_two():
assert fake.name() == 'Tiffany Williams'
"""
)
out = ourtester.runpytest("--randomly-seed=1")
out.assert_outcomes(passed=2)
def test_faker_fixture(ourtester):
ourtester.makepyfile(
test_one="""
def test_one(faker):
assert faker.name() == 'Ryan Gallagher'
def test_two(faker):
assert faker.name() == 'Ryan Gallagher'
"""
)
out = ourtester.runpytest("--randomly-seed=1")
out.assert_outcomes(passed=2)
def test_model_bakery(ourtester):
"""
Rather than set up models, just check the random generator it uses is set
between two tests to output the same number.
"""
ourtester.makepyfile(
test_one="""
from model_bakery.random_gen import baker_random
def test_a():
test_a.num = baker_random.random()
if hasattr(test_b, 'num'):
assert test_a.num == test_b.num
def test_b():
test_b.num = baker_random.random()
if hasattr(test_a, 'num'):
assert test_b.num == test_a.num
"""
)
out = ourtester.runpytest("--randomly-seed=1", "--randomly-dont-seed-per-test")
out.assert_outcomes(passed=2)
def test_numpy(ourtester):
ourtester.makepyfile(
test_one="""
import numpy as np
def test_one():
assert np.random.rand() == 0.46479378116435255
def test_two():
assert np.random.rand() == 0.6413112443155088
"""
)
out = ourtester.runpytest("--randomly-seed=1")
out.assert_outcomes(passed=2)
def test_numpy_doesnt_crash_with_large_seed(ourtester):
ourtester.makepyfile(
test_one="""
import numpy as np
def test_one():
assert np.random.rand() >= 0.0
"""
)
out = ourtester.runpytest("--randomly-seed=7106521602475165645")
out.assert_outcomes(passed=1)
def test_failing_import(testdir):
"""Test with pytest raising CollectError or ImportError.
This happens when trying to access item.module during
pytest_collection_modifyitems.
"""
modcol = testdir.getmodulecol("import alksdjalskdjalkjals")
assert modcol.instance is None
modcol = testdir.getmodulecol("pytest_plugins='xasdlkj',")
with pytest.raises(ImportError):
modcol.obj
def test_entrypoint_injection(pytester, monkeypatch):
"""Test that registered entry points are seeded"""
(pytester.path / "test_one.py").write_text("def test_one(): pass\n")
class _FakeEntryPoint:
"""Minimal surface of Entry point API to allow testing"""
def __init__(self, name: str, obj: mock.Mock) -> None:
self.name = name
self._obj = obj
def load(self) -> mock.Mock:
return self._obj
entry_points: list[_FakeEntryPoint] = []
def fake_entry_points(*, group):
return entry_points
monkeypatch.setattr(pytest_randomly, "entry_points", fake_entry_points)
reseed = mock.Mock()
entry_points.append(_FakeEntryPoint("test_seeder", reseed))
# Need to run in-process so that monkeypatching works
pytester.runpytest_inprocess("--randomly-seed=1", "--randomly-dont-seed-per-test")
assert reseed.mock_calls == [
mock.call(1),
mock.call(1),
mock.call(0),
mock.call(1),
mock.call(2),
]
reseed.mock_calls[:] = []
pytester.runpytest_inprocess(
"--randomly-seed=424242", "--randomly-dont-seed-per-test"
)
assert reseed.mock_calls == [
mock.call(424242),
mock.call(424242),
mock.call(424241),
mock.call(424242),
mock.call(424243),
]
def test_entrypoint_missing(pytester, monkeypatch):
"""
Test that if there aren't any registered entrypoints, it doesn't crash
"""
(pytester.path / "test_one.py").write_text("def test_one(): pass\n")
def fake_entry_points(group):
return []
monkeypatch.setattr(pytest_randomly, "entry_points", fake_entry_points)
# Need to run in-process so that monkeypatching works
result = pytester.runpytest_inprocess("--randomly-seed=1")
assert result.ret == 0
def test_works_without_xdist(simpletester):
out = simpletester.runpytest("-p", "no:xdist")
out.assert_outcomes(passed=1)
@pytest.mark.parametrize("n", list(range(5)))
def test_xdist(n, ourtester):
"""
This test does not expose the original bug (non-shared default seeds) with
a very high probability, hence multiple runs.
"""
ourtester.makepyfile(
test_one="def test_a(): pass",
test_two="def test_a(): pass",
test_three="def test_a(): pass",
test_four="def test_a(): pass",
test_five="def test_a(): pass",
test_six="def test_a(): pass",
)
out = ourtester.runpytest("-n", "6", "-v", "--dist=loadfile")
out.assert_outcomes(passed=6)
# Can't make any assertion on the order, since output comes back from
# workers non-deterministically