/
pytest_randomly.py
233 lines (176 loc) · 5.86 KB
/
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
import argparse
import random
import sys
import time
from pytest import Collector
if sys.version_info >= (3, 8):
from importlib.metadata import entry_points
else:
from importlib_metadata import entry_points
# factory-boy
try:
from factory.random import set_random_state as factory_set_random_state
have_factory_boy = True
except ImportError:
# old versions
try:
from factory.fuzzy import set_random_state as factory_set_random_state
have_factory_boy = True
except ImportError:
have_factory_boy = False
# faker
try:
from faker.generator import random as faker_random
have_faker = True
except ImportError:
have_faker = False
# numpy
try:
from numpy import random as np_random
have_numpy = True
except ImportError:
have_numpy = False
default_seed = int(time.time())
def seed_type(string):
if string in ("default", "last"):
return string
try:
return int(string)
except ValueError:
raise argparse.ArgumentTypeError(
"{} is not an integer or the string 'last'".format(repr(string))
)
def pytest_addoption(parser):
group = parser.getgroup("randomly", "Randomizes tests")
group._addoption(
"--randomly-seed",
action="store",
dest="randomly_seed",
default="default",
type=seed_type,
help="""Set the seed that pytest-randomly uses (int), or pass the
special value 'last' to reuse the seed from the previous run.
Default behaviour: use int(time.time()), so the seed is
different on each run.""",
)
group._addoption(
"--randomly-dont-reset-seed",
action="store_false",
dest="randomly_reset_seed",
default=True,
help="""Stop pytest-randomly from resetting random.seed() at the
start of every test context (e.g. TestCase) and individual
test.""",
)
group._addoption(
"--randomly-dont-reorganize",
action="store_false",
dest="randomly_reorganize",
default=True,
help="Stop pytest-randomly from randomly reorganizing the test order.",
)
def pytest_configure(config):
seed_value = config.getoption("randomly_seed")
if seed_value == "last":
seed = config.cache.get("randomly_seed", default_seed)
elif seed_value == "default":
if hasattr(config, "workerinput"):
# pytest-xdist: use seed generated on master.
seed = config.workerinput["randomly_seed"]
else:
seed = default_seed
else:
seed = seed_value
config.cache.set("randomly_seed", seed)
config.option.randomly_seed = seed
def pytest_configure_node(node):
"""
pytest-xdist hook. Send the selected seed through to the nodes.
"""
node.workerinput["randomly_seed"] = node.config.getoption("randomly_seed")
random_states = {}
np_random_states = {}
entrypoint_reseeds = None
def _reseed(config, offset=0):
global entrypoint_reseeds
seed = config.getoption("randomly_seed") + offset
if seed not in random_states:
random.seed(seed)
random_states[seed] = random.getstate()
else:
random.setstate(random_states[seed])
if have_factory_boy:
factory_set_random_state(random_states[seed])
if have_faker:
faker_random.setstate(random_states[seed])
if have_numpy:
if seed not in np_random_states:
np_random.seed(seed)
np_random_states[seed] = np_random.get_state()
else:
np_random.set_state(np_random_states[seed])
if entrypoint_reseeds is None:
entrypoint_reseeds = [
e.load() for e in entry_points().get("pytest_randomly.random_seeder", [])
]
for reseed in entrypoint_reseeds:
reseed(seed)
def pytest_report_header(config):
seed = config.getoption("randomly_seed")
_reseed(config)
return "Using --randomly-seed={}".format(seed)
def pytest_runtest_setup(item):
if item.config.getoption("randomly_reset_seed"):
_reseed(item.config, -1)
def pytest_runtest_call(item):
if item.config.getoption("randomly_reset_seed"):
_reseed(item.config)
def pytest_runtest_teardown(item):
if item.config.getoption("randomly_reset_seed"):
_reseed(item.config, 1)
def pytest_collection_modifyitems(session, config, items):
if not config.getoption("randomly_reorganize"):
return
_reseed(config)
module_items = []
current_module = None
current_items = []
for item in items:
try:
item_module = getattr(item, "module", None)
except (ImportError, Collector.CollectError):
item_module = None
if current_module is None:
current_module = item_module
if item_module != current_module:
module_items.append(shuffle_by_class(current_items))
current_items = [item]
current_module = item_module
else:
current_items.append(item)
module_items.append(shuffle_by_class(current_items))
random.shuffle(module_items)
items[:] = reduce_list_of_lists(module_items)
def shuffle_by_class(items):
class_items = []
current_cls = None
current_items = []
for item in items:
if current_cls is None:
current_cls = getattr(item, "cls", None)
if getattr(item, "cls", None) != current_cls:
random.shuffle(current_items)
class_items.append(current_items)
current_items = [item]
current_cls = item.cls
else:
current_items.append(item)
random.shuffle(current_items)
class_items.append(current_items)
random.shuffle(class_items)
return reduce_list_of_lists(class_items)
def reduce_list_of_lists(lists):
new_list = []
for list_ in lists:
new_list.extend(list_)
return new_list