Debian Codegraph @

hypothesis-python/tests/cover/test_randoms.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 import inspect
12 import math
13 from copy import copy
14
15 import pytest
16
17 from hypothesis import HealthCheck, assume, given, settings, strategies as st
18 from hypothesis.internal.compat import ExceptionGroup
19 from hypothesis.internal.conjecture.data import ConjectureData
20 from hypothesis.strategies._internal.random import (
21 RANDOM_METHODS,
22 ArtificialRandom,
23 HypothesisRandom,
24 TrueRandom,
25 convert_kwargs,
26 normalize_zero,
27 )
28
29 from tests.common.debug import assert_all_examples, find_any
30 from tests.common.utils import Why, xfail_on_crosshair
31
32
33 def test_implements_all_random_methods():
34 for name in dir(HypothesisRandom):
35 if not name.startswith("_") or name == "_randbelow":
36 f = getattr(HypothesisRandom, name)
37 if inspect.isfunction(f):
38 assert f.__module__ == "hypothesis.strategies._internal.random", name
39
40
41 any_random = st.randoms(use_true_random=False) | st.randoms(use_true_random=True)
42
43 beta_param = st.floats(0.01, 1000)
44 seq_param = st.lists(st.integers(), min_size=1)
45
46
47 METHOD_STRATEGIES = {}
48
49
50 def define_method_strategy(name, **kwargs):
51 METHOD_STRATEGIES[name] = kwargs
52
53
54 define_method_strategy("betavariate", alpha=beta_param, beta=beta_param)
55 define_method_strategy("binomialvariate", n=st.integers(min_value=1), p=st.floats(0, 1))
56 define_method_strategy("gammavariate", alpha=beta_param, beta=beta_param)
57 define_method_strategy("weibullvariate", alpha=beta_param, beta=beta_param)
58 define_method_strategy("choice", seq=seq_param)
59 define_method_strategy("choices", population=seq_param, k=st.integers(1, 100))
60 define_method_strategy("expovariate", lambd=beta_param)
61 define_method_strategy("_randbelow", n=st.integers(1, 2**64))
62 define_method_strategy("random")
63 define_method_strategy("getrandbits", n=st.integers(1, 128))
64 define_method_strategy("gauss", mu=st.floats(-1000, 1000), sigma=beta_param)
65 define_method_strategy("normalvariate", mu=st.floats(-1000, 1000), sigma=beta_param)
66 # the standard library lognormalvariate is weirdly bad at handling large floats
67 define_method_strategy(
68 "lognormvariate", mu=st.floats(0.1, 10), sigma=st.floats(0.1, 10)
69 )
70 define_method_strategy(
71 "vonmisesvariate", mu=st.floats(0, math.pi * 2), kappa=beta_param
72 )
73 # Small alpha may raise ZeroDivisionError, see https://bugs.python.org/issue41421
74 define_method_strategy("paretovariate", alpha=st.floats(min_value=1.0))
75 define_method_strategy("shuffle", x=st.lists(st.integers()))
76 define_method_strategy("randbytes", n=st.integers(0, 100))
77
78
79 INT64 = st.integers(-(2**63), 2**63 - 1)
80
81
82 @st.composite
83 def any_call_of_method(draw, method):
84 if method == "sample":
85 population = draw(seq_param)
86 k = draw(st.integers(0, len(population)))
87 kwargs = {"population": population, "k": k}
88 elif method == "randint":
89 a = draw(INT64)
90 b = draw(INT64)
91 a, b = sorted((a, b))
92 kwargs = {"a": a, "b": b}
93 elif method == "randrange":
94 a = draw(INT64)
95 b = draw(INT64)
96 assume(a != b)
97 a, b = sorted((a, b))
98 kwargs = {"start": a, "stop": b, "step": draw(st.integers(1, 3))}
99 elif method == "triangular":
100 a = normalize_zero(draw(st.floats(allow_infinity=False, allow_nan=False)))
101 b = normalize_zero(draw(st.floats(allow_infinity=False, allow_nan=False)))
102 a, b = sorted((a, b))
103 if draw(st.booleans()):
104 draw(st.floats(a, b))
105 kwargs = {"low": a, "high": b, "mode": None}
106 elif method == "uniform":
107 a = normalize_zero(draw(st.floats(allow_infinity=False, allow_nan=False)))
108 b = normalize_zero(draw(st.floats(allow_infinity=False, allow_nan=False)))
109 a, b = sorted((a, b))
110 kwargs = {"a": a, "b": b}
111 else:
112 kwargs = draw(st.fixed_dictionaries(METHOD_STRATEGIES[method]))
113
114 args, kwargs = convert_kwargs(method, kwargs)
115
116 return (args, kwargs)
117
118
119 @st.composite
120 def any_call(draw):
121 method = draw(st.sampled_from(RANDOM_METHODS))
122 return (method, *draw(any_call_of_method(method)))
123
124
125 @pytest.mark.parametrize("method", RANDOM_METHODS)
126 @given(any_random, st.data())
127 def test_call_all_methods(method, rnd, data):
128 args, kwargs = data.draw(any_call_of_method(method))
129 getattr(rnd, method)(*args, **kwargs)
130
131
132 @given(any_random, st.integers(1, 100))
133 def test_rand_below(rnd, n):
134 assert rnd._randbelow(n) < n
135
136
137 @given(any_random, beta_param, beta_param)
138 def test_beta_in_range(rnd, a, b):
139 assert 0 <= rnd.betavariate(a, b) <= 1
140
141
142 def test_multiple_randoms_are_unrelated():
143 @given(st.randoms(use_true_random=False), st.randoms(use_true_random=False))
144 def test(r1, r2):
145 assert r1.random() == r2.random()
146
147 with pytest.raises(AssertionError):
148 test()
149
150
151 @pytest.mark.parametrize("use_true_random", [False, True])
152 @given(data=st.data())
153 def test_randoms_can_be_synced(use_true_random, data):
154 r1 = data.draw(st.randoms(use_true_random=use_true_random))
155 r2 = data.draw(st.randoms(use_true_random=use_true_random))
156 r2.setstate(r1.getstate())
157 assert r1.random() == r2.random()
158
159
160 @pytest.mark.parametrize("use_true_random", [False, True])
161 @given(data=st.data(), method_call=any_call())
162 def test_seeding_to_same_value_synchronizes(use_true_random, data, method_call):
163 r1 = data.draw(st.randoms(use_true_random=use_true_random))
164 r2 = data.draw(st.randoms(use_true_random=use_true_random))
165 method, args, kwargs = method_call
166 r1.seed(0)
167 r2.seed(0)
168 assert getattr(r1, method)(*args, **kwargs) == getattr(r2, method)(*args, **kwargs)
169
170
171 @given(any_random, any_call())
172 def test_copying_synchronizes(r1, method_call):
173 method, args, kwargs = method_call
174 r2 = copy(r1)
175 assert getattr(r1, method)(*args, **kwargs) == getattr(r2, method)(*args, **kwargs)
176
177
178 @xfail_on_crosshair(Why.symbolic_outside_context, strict=False)
179 @pytest.mark.parametrize("use_true_random", [True, False])
180 def test_seeding_to_different_values_does_not_synchronize(use_true_random):
181 @given(
182 st.randoms(use_true_random=use_true_random),
183 st.randoms(use_true_random=use_true_random),
184 )
185 def test(r1, r2):
186 r1.seed(0)
187 r2.seed(1)
188 assert r1.random() == r2.random()
189
190 with pytest.raises(AssertionError):
191 test()
192
193
194 @xfail_on_crosshair(Why.symbolic_outside_context, strict=False)
195 @pytest.mark.parametrize("use_true_random", [True, False])
196 def test_unrelated_calls_desynchronizes(use_true_random):
197 @given(
198 st.randoms(use_true_random=use_true_random),
199 st.randoms(use_true_random=use_true_random),
200 )
201 def test(r1, r2):
202 r1.seed(0)
203 r2.seed(0)
204 r1.randrange(1, 10)
205 r2.getrandbits(128)
206 assert r1.random() == r2.random()
207
208 with pytest.raises(AssertionError):
209 test()
210
211
212 @given(st.randoms(use_true_random=False), st.randoms(use_true_random=False))
213 def test_state_is_consistent(r1, r2):
214 r2.setstate(r1.getstate())
215 assert r1.getstate() == r2.getstate()
216
217
218 @given(st.randoms())
219 def test_does_not_use_true_random_by_default(rnd):
220 assert not isinstance(rnd, TrueRandom)
221
222
223 @given(st.randoms(use_true_random=False))
224 def test_handles_singleton_uniforms_correctly(rnd):
225 assert rnd.uniform(1.0, 1.0) == 1.0
226 assert rnd.uniform(0.0, 0.0) == 0.0
227 assert rnd.uniform(-0.0, -0.0) == 0.0
228 assert rnd.uniform(0.0, -0.0) == 0.0
229
230
231 @given(st.randoms(use_true_random=False))
232 def test_handles_singleton_regions_of_triangular_correctly(rnd):
233 assert rnd.triangular(1.0, 1.0) == 1.0
234 assert rnd.triangular(0.0, 0.0) == 0.0
235 assert rnd.triangular(-0.0, -0.0) == 0.0
236 assert rnd.triangular(0.0, -0.0) == 0.0
237
238
239 @given(st.randoms(use_true_random=False))
240 def test_triangular_with_mode(rnd):
241 x = rnd.triangular(0.0, 1.0, mode=0.5)
242 assert 0.0 <= x <= 1.0
243
244
245 @pytest.mark.parametrize("use_true_random", [False, True])
246 def test_outputs_random_calls(use_true_random):
247 @given(st.randoms(use_true_random=use_true_random, note_method_calls=True))
248 def test(rnd):
249 rnd.uniform(0.1, 0.5)
250 raise AssertionError
251
252 with pytest.raises(AssertionError) as err:
253 test()
254 assert ".uniform(0.1, 0.5)" in "\n".join(err.value.__notes__)
255
256
257 @pytest.mark.skipif(
258 "choices" not in RANDOM_METHODS,
259 reason="choices not supported on this Python version",
260 )
261 @pytest.mark.parametrize("use_true_random", [False, True])
262 def test_converts_kwargs_correctly_in_output(use_true_random):
263 @given(st.randoms(use_true_random=use_true_random, note_method_calls=True))
264 def test(rnd):
265 rnd.choices([1, 2, 3, 4], k=2)
266 raise AssertionError
267
268 with pytest.raises(AssertionError) as err:
269 test()
270 assert ".choices([1, 2, 3, 4], k=2)" in "\n".join(err.value.__notes__)
271
272
273 @given(st.randoms(use_true_random=False))
274 def test_some_ranges_are_in_range(rnd):
275 assert 0 <= rnd.randrange(10) < 10
276 assert 11 <= rnd.randrange(11, 20) < 20
277 assert rnd.randrange(1, 100, 3) in range(1, 100, 3)
278 assert rnd.randrange(100, step=3) in range(0, 100, 3)
279
280
281 def test_invalid_range():
282 @given(st.randoms(use_true_random=False))
283 def test(rnd):
284 rnd.randrange(1, 1)
285
286 with pytest.raises(ValueError):
287 test()
288
289
290 def test_invalid_sample():
291 @given(st.randoms(use_true_random=False))
292 def test(rnd):
293 rnd.sample([1, 2], 3)
294
295 with pytest.raises(ValueError):
296 test()
297
298
299 def test_triangular_modes():
300 @settings(report_multiple_bugs=True)
301 @given(st.randoms(use_true_random=False))
302 def test(rnd):
303 x = rnd.triangular(0.0, 1.0, mode=0.5)
304 assert x < 0.5
305 assert x > 0.5
306
307 with pytest.raises(ExceptionGroup):
308 test()
309
310
311 @given(st.randoms(use_true_random=False), any_call_of_method("sample"))
312 def test_samples_have_right_length(rnd, sample):
313 (seq, k), _ = sample
314 assert len(rnd.sample(seq, k)) == k
315
316
317 @given(st.randoms(use_true_random=False), any_call_of_method("choices"))
318 def test_choices_have_right_length(rnd, choices):
319 args, kwargs = choices
320
321 seq = args[0]
322 k = kwargs.get("k", 1)
323 assert len(rnd.choices(seq, k=k)) == k
324
325
326 @given(any_random, st.integers(0, 100))
327 def test_randbytes_have_right_length(rnd, n):
328 assert len(rnd.randbytes(n)) == n
329
330
331 @pytest.mark.skipif(
332 settings.get_current_profile_name() == "crosshair",
333 reason="takes hours; may get faster after https://github.com/pschanely/CrossHair/issues/332",
334 )
335 @given(any_random)
336 def test_can_manage_very_long_ranges_with_step(rnd):
337 i = rnd.randrange(0, 2**256, 3)
338
339 assert i % 3 == 0
340 assert 0 <= i < 2**256
341 assert i in range(0, 2**256, 3)
342
343
344 @settings(suppress_health_check=[HealthCheck.too_slow])
345 @given(any_random, st.data())
346 def test_range_with_arbitrary_step_is_in_range(rnd, data):
347 endpoints = st.integers(-100, 100)
348 step = data.draw(st.integers(1, 3))
349 start, stop = sorted((data.draw(endpoints), data.draw(endpoints)))
350 assume(start < stop)
351 i = rnd.randrange(start, stop, step)
352 assert i in range(start, stop, step)
353
354
355 @given(any_random, st.integers(min_value=1))
356 def test_range_with_only_stop(rnd, n):
357 assert 0 <= rnd.randrange(n) < n
358
359
360 def test_can_find_end_of_range():
361 find_any(
362 st.randoms(use_true_random=False).map(lambda r: r.randrange(0, 11, 2)),
363 lambda n: n == 10,
364 )
365 find_any(
366 st.randoms(use_true_random=False).map(lambda r: r.randrange(0, 10, 2)),
367 lambda n: n == 8,
368 )
369
370
371 @given(st.randoms(use_true_random=False))
372 def test_can_sample_from_whole_range(rnd):
373 xs = list(map(str, range(10)))
374 ys = rnd.sample(xs, len(xs))
375 assert sorted(ys) == sorted(xs)
376
377
378 @given(st.randoms(use_true_random=False))
379 def test_can_sample_from_large_subset(rnd):
380 xs = list(map(str, range(10)))
381 n = len(xs) // 3
382 ys = rnd.sample(xs, n)
383 assert set(ys).issubset(set(xs))
384 assert len(ys) == len(set(ys)) == n
385
386
387 @given(st.randoms(use_true_random=False))
388 def test_can_draw_empty_from_empty_sequence(rnd):
389 assert rnd.sample([], 0) == []
390
391
392 def test_random_includes_zero_excludes_one():
393 strat = st.randoms(use_true_random=False).map(lambda r: r.random())
394 assert_all_examples(strat, lambda x: 0 <= x < 1)
395 find_any(strat, lambda x: x == 0)
396
397
398 def test_betavariate_includes_zero_and_one():
399 # https://github.com/HypothesisWorks/hypothesis/issues/4297#issuecomment-2720144709
400 strat = st.randoms(use_true_random=False).flatmap(
401 lambda r: st.builds(
402 r.betavariate, alpha=st.just(1.0) | beta_param, beta=beta_param
403 )
404 )
405 assert_all_examples(strat, lambda x: 0 <= x <= 1)
406 find_any(strat, lambda x: x == 0)
407 find_any(strat, lambda x: x == 1)
408
409
410 def test_artificial_random_with_already_initialized_states_for_ids():
411 # covering test for calling .getstate when data.states_for_ids is not None.
412 data = ConjectureData.for_choices([])
413 data.states_for_ids = {}
414 r = ArtificialRandom(note_method_calls=False, data=data)
415 r.getstate()