Debian Codegraph @

Lib/test/test_random.py

raw
1 import unittest
2 import unittest.mock
3 import random
4 import os
5 import time
6 import pickle
7 import shlex
8 import warnings
9 import test.support
10
11 from functools import partial
12 from math import log, exp, pi, fsum, sin, factorial
13 from test import support
14 from fractions import Fraction
15 from collections import abc, Counter
16
17
18 class MyIndex:
19 def __init__(self, value):
20 self.value = value
21
22 def __index__(self):
23 return self.value
24
25
26 class TestBasicOps:
27 # Superclass with tests common to all generators.
28 # Subclasses must arrange for self.gen to retrieve the Random instance
29 # to be tested.
30
31 def randomlist(self, n):
32 """Helper function to make a list of random numbers"""
33 return [self.gen.random() for i in range(n)]
34
35 def test_autoseed(self):
36 self.gen.seed()
37 state1 = self.gen.getstate()
38 time.sleep(0.1)
39 self.gen.seed() # different seeds at different times
40 state2 = self.gen.getstate()
41 self.assertNotEqual(state1, state2)
42
43 def test_saverestore(self):
44 N = 1000
45 self.gen.seed()
46 state = self.gen.getstate()
47 randseq = self.randomlist(N)
48 self.gen.setstate(state) # should regenerate the same sequence
49 self.assertEqual(randseq, self.randomlist(N))
50
51 def test_seedargs(self):
52 # Seed value with a negative hash.
53 class MySeed(object):
54 def __hash__(self):
55 return -1729
56 for arg in [None, 0, 1, -1, 10**20, -(10**20),
57 False, True, 3.14, 'a']:
58 self.gen.seed(arg)
59
60 for arg in [1+2j, tuple('abc'), MySeed()]:
61 with self.assertRaises(TypeError):
62 self.gen.seed(arg)
63
64 for arg in [list(range(3)), dict(one=1)]:
65 self.assertRaises(TypeError, self.gen.seed, arg)
66 self.assertRaises(TypeError, self.gen.seed, 1, 2, 3, 4)
67 self.assertRaises(TypeError, type(self.gen), [])
68
69 def test_seed_no_mutate_bug_44018(self):
70 a = bytearray(b'1234')
71 self.gen.seed(a)
72 self.assertEqual(a, bytearray(b'1234'))
73
74 @unittest.mock.patch('random._urandom') # os.urandom
75 def test_seed_when_randomness_source_not_found(self, urandom_mock):
76 # Random.seed() uses time.time() when an operating system specific
77 # randomness source is not found. To test this on machines where it
78 # exists, run the above test, test_seedargs(), again after mocking
79 # os.urandom() so that it raises the exception expected when the
80 # randomness source is not available.
81 urandom_mock.side_effect = NotImplementedError
82 self.test_seedargs()
83
84 def test_shuffle(self):
85 shuffle = self.gen.shuffle
86 lst = []
87 shuffle(lst)
88 self.assertEqual(lst, [])
89 lst = [37]
90 shuffle(lst)
91 self.assertEqual(lst, [37])
92 seqs = [list(range(n)) for n in range(10)]
93 shuffled_seqs = [list(range(n)) for n in range(10)]
94 for shuffled_seq in shuffled_seqs:
95 shuffle(shuffled_seq)
96 for (seq, shuffled_seq) in zip(seqs, shuffled_seqs):
97 self.assertEqual(len(seq), len(shuffled_seq))
98 self.assertEqual(set(seq), set(shuffled_seq))
99 # The above tests all would pass if the shuffle was a
100 # no-op. The following non-deterministic test covers that. It
101 # asserts that the shuffled sequence of 1000 distinct elements
102 # must be different from the original one. Although there is
103 # mathematically a non-zero probability that this could
104 # actually happen in a genuinely random shuffle, it is
105 # completely negligible, given that the number of possible
106 # permutations of 1000 objects is 1000! (factorial of 1000),
107 # which is considerably larger than the number of atoms in the
108 # universe...
109 lst = list(range(1000))
110 shuffled_lst = list(range(1000))
111 shuffle(shuffled_lst)
112 self.assertTrue(lst != shuffled_lst)
113 shuffle(lst)
114 self.assertTrue(lst != shuffled_lst)
115 self.assertRaises(TypeError, shuffle, (1, 2, 3))
116
117 def test_choice(self):
118 choice = self.gen.choice
119 with self.assertRaises(IndexError):
120 choice([])
121 self.assertEqual(choice([50]), 50)
122 self.assertIn(choice([25, 75]), [25, 75])
123
124 def test_choice_with_numpy(self):
125 # Accommodation for NumPy arrays which have disabled __bool__().
126 # See: https://github.com/python/cpython/issues/100805
127 choice = self.gen.choice
128
129 class NA(list):
130 "Simulate numpy.array() behavior"
131 def __bool__(self):
132 raise RuntimeError
133
134 with self.assertRaises(IndexError):
135 choice(NA([]))
136 self.assertEqual(choice(NA([50])), 50)
137 self.assertIn(choice(NA([25, 75])), [25, 75])
138
139 def test_sample(self):
140 # For the entire allowable range of 0 <= k <= N, validate that
141 # the sample is of the correct length and contains only unique items
142 N = 100
143 population = range(N)
144 for k in range(N+1):
145 s = self.gen.sample(population, k)
146 self.assertEqual(len(s), k)
147 uniq = set(s)
148 self.assertEqual(len(uniq), k)
149 self.assertTrue(uniq <= set(population))
150 self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0
151 # Exception raised if size of sample exceeds that of population
152 self.assertRaises(ValueError, self.gen.sample, population, N+1)
153 self.assertRaises(ValueError, self.gen.sample, [], -1)
154 self.assertRaises(TypeError, self.gen.sample, population, 1.0)
155
156 def test_sample_distribution(self):
157 # For the entire allowable range of 0 <= k <= N, validate that
158 # sample generates all possible permutations
159 n = 5
160 pop = range(n)
161 trials = 10000 # large num prevents false negatives without slowing normal case
162 for k in range(n):
163 expected = factorial(n) // factorial(n-k)
164 perms = {}
165 for i in range(trials):
166 perms[tuple(self.gen.sample(pop, k))] = None
167 if len(perms) == expected:
168 break
169 else:
170 self.fail()
171
172 def test_sample_inputs(self):
173 # SF bug #801342 -- population can be any iterable defining __len__()
174 self.gen.sample(range(20), 2)
175 self.gen.sample(range(20), 2)
176 self.gen.sample(str('abcdefghijklmnopqrst'), 2)
177 self.gen.sample(tuple('abcdefghijklmnopqrst'), 2)
178
179 def test_sample_on_dicts(self):
180 self.assertRaises(TypeError, self.gen.sample, dict.fromkeys('abcdef'), 2)
181
182 def test_sample_on_sets(self):
183 with self.assertRaises(TypeError):
184 population = {10, 20, 30, 40, 50, 60, 70}
185 self.gen.sample(population, k=5)
186
187 def test_sample_on_seqsets(self):
188 class SeqSet(abc.Sequence, abc.Set):
189 def __init__(self, items):
190 self._items = items
191
192 def __len__(self):
193 return len(self._items)
194
195 def __getitem__(self, index):
196 return self._items[index]
197
198 population = SeqSet([2, 4, 1, 3])
199 with warnings.catch_warnings():
200 warnings.simplefilter("error", DeprecationWarning)
201 self.gen.sample(population, k=2)
202
203 def test_sample_with_counts(self):
204 sample = self.gen.sample
205
206 # General case
207 colors = ['red', 'green', 'blue', 'orange', 'black', 'brown', 'amber']
208 counts = [500, 200, 20, 10, 5, 0, 1 ]
209 k = 700
210 summary = Counter(sample(colors, counts=counts, k=k))
211 self.assertEqual(sum(summary.values()), k)
212 for color, weight in zip(colors, counts):
213 self.assertLessEqual(summary[color], weight)
214 self.assertNotIn('brown', summary)
215
216 # Case that exhausts the population
217 k = sum(counts)
218 summary = Counter(sample(colors, counts=counts, k=k))
219 self.assertEqual(sum(summary.values()), k)
220 for color, weight in zip(colors, counts):
221 self.assertLessEqual(summary[color], weight)
222 self.assertNotIn('brown', summary)
223
224 # Case with population size of 1
225 summary = Counter(sample(['x'], counts=[10], k=8))
226 self.assertEqual(summary, Counter(x=8))
227
228 # Case with all counts equal.
229 nc = len(colors)
230 summary = Counter(sample(colors, counts=[10]*nc, k=10*nc))
231 self.assertEqual(summary, Counter(10*colors))
232
233 # Test error handling
234 with self.assertRaises(TypeError):
235 sample(['red', 'green', 'blue'], counts=10, k=10) # counts not iterable
236 with self.assertRaises(ValueError):
237 sample(['red', 'green', 'blue'], counts=[-3, -7, -8], k=2) # counts are negative
238 with self.assertRaises(ValueError):
239 sample(['red', 'green'], counts=[10, 10], k=21) # population too small
240 with self.assertRaises(ValueError):
241 sample(['red', 'green', 'blue'], counts=[1, 2], k=2) # too few counts
242 with self.assertRaises(ValueError):
243 sample(['red', 'green', 'blue'], counts=[1, 2, 3, 4], k=2) # too many counts
244
245 # Cases with zero counts match equivalents without counts (see gh-130285)
246 self.assertEqual(
247 sample('abc', k=0, counts=[0, 0, 0]),
248 sample([], k=0),
249 )
250 self.assertEqual(
251 sample([], 0, counts=[]),
252 sample([], 0),
253 )
254 with self.assertRaises(ValueError):
255 sample([], 1, counts=[])
256 with self.assertRaises(ValueError):
257 sample('x', 1, counts=[0])
258
259 def test_choices(self):
260 choices = self.gen.choices
261 data = ['red', 'green', 'blue', 'yellow']
262 str_data = 'abcd'
263 range_data = range(4)
264 set_data = set(range(4))
265
266 # basic functionality
267 for sample in [
268 choices(data, k=5),
269 choices(data, range(4), k=5),
270 choices(k=5, population=data, weights=range(4)),
271 choices(k=5, population=data, cum_weights=range(4)),
272 choices(data, k=MyIndex(5)),
273 ]:
274 self.assertEqual(len(sample), 5)
275 self.assertEqual(type(sample), list)
276 self.assertTrue(set(sample) <= set(data))
277
278 # test argument handling
279 with self.assertRaises(TypeError): # missing arguments
280 choices(2)
281
282 self.assertEqual(choices(data, k=0), []) # k == 0
283 self.assertEqual(choices(data, k=-1), []) # negative k behaves like ``[0] * -1``
284 with self.assertRaises(TypeError):
285 choices(data, k=2.5) # k is a float
286
287 self.assertTrue(set(choices(str_data, k=5)) <= set(str_data)) # population is a string sequence
288 self.assertTrue(set(choices(range_data, k=5)) <= set(range_data)) # population is a range
289 with self.assertRaises(TypeError):
290 choices(set_data, k=2) # population is not a sequence
291
292 self.assertTrue(set(choices(data, None, k=5)) <= set(data)) # weights is None
293 self.assertTrue(set(choices(data, weights=None, k=5)) <= set(data))
294 with self.assertRaises(ValueError):
295 choices(data, [1,2], k=5) # len(weights) != len(population)
296 with self.assertRaises(TypeError):
297 choices(data, 10, k=5) # non-iterable weights
298 with self.assertRaises(TypeError):
299 choices(data, [None]*4, k=5) # non-numeric weights
300 for weights in [
301 [15, 10, 25, 30], # integer weights
302 [15.1, 10.2, 25.2, 30.3], # float weights
303 [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional weights
304 [True, False, True, False] # booleans (include / exclude)
305 ]:
306 self.assertTrue(set(choices(data, weights, k=5)) <= set(data))
307
308 with self.assertRaises(ValueError):
309 choices(data, cum_weights=[1,2], k=5) # len(weights) != len(population)
310 with self.assertRaises(TypeError):
311 choices(data, cum_weights=10, k=5) # non-iterable cum_weights
312 with self.assertRaises(TypeError):
313 choices(data, cum_weights=[None]*4, k=5) # non-numeric cum_weights
314 with self.assertRaises(TypeError):
315 choices(data, range(4), cum_weights=range(4), k=5) # both weights and cum_weights
316 for weights in [
317 [15, 10, 25, 30], # integer cum_weights
318 [15.1, 10.2, 25.2, 30.3], # float cum_weights
319 [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional cum_weights
320 ]:
321 self.assertTrue(set(choices(data, cum_weights=weights, k=5)) <= set(data))
322
323 # Test weight focused on a single element of the population
324 self.assertEqual(choices('abcd', [1, 0, 0, 0]), ['a'])
325 self.assertEqual(choices('abcd', [0, 1, 0, 0]), ['b'])
326 self.assertEqual(choices('abcd', [0, 0, 1, 0]), ['c'])
327 self.assertEqual(choices('abcd', [0, 0, 0, 1]), ['d'])
328
329 # Test consistency with random.choice() for empty population
330 with self.assertRaises(IndexError):
331 choices([], k=1)
332 with self.assertRaises(IndexError):
333 choices([], weights=[], k=1)
334 with self.assertRaises(IndexError):
335 choices([], cum_weights=[], k=5)
336
337 def test_choices_subnormal(self):
338 # Subnormal weights would occasionally trigger an IndexError
339 # in choices() when the value returned by random() was large
340 # enough to make `random() * total` round up to the total.
341 # See https://bugs.python.org/msg275594 for more detail.
342 choices = self.gen.choices
343 choices(population=[1, 2], weights=[1e-323, 1e-323], k=5000)
344
345 def test_choices_with_all_zero_weights(self):
346 # See issue #38881
347 with self.assertRaises(ValueError):
348 self.gen.choices('AB', [0.0, 0.0])
349
350 def test_choices_negative_total(self):
351 with self.assertRaises(ValueError):
352 self.gen.choices('ABC', [3, -5, 1])
353
354 def test_choices_infinite_total(self):
355 with self.assertRaises(ValueError):
356 self.gen.choices('A', [float('inf')])
357 with self.assertRaises(ValueError):
358 self.gen.choices('AB', [0.0, float('inf')])
359 with self.assertRaises(ValueError):
360 self.gen.choices('AB', [-float('inf'), 123])
361 with self.assertRaises(ValueError):
362 self.gen.choices('AB', [0.0, float('nan')])
363 with self.assertRaises(ValueError):
364 self.gen.choices('AB', [float('-inf'), float('inf')])
365
366 def test_gauss(self):
367 # Ensure that the seed() method initializes all the hidden state. In
368 # particular, through 2.2.1 it failed to reset a piece of state used
369 # by (and only by) the .gauss() method.
370
371 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
372 self.gen.seed(seed)
373 x1 = self.gen.random()
374 y1 = self.gen.gauss(0, 1)
375
376 self.gen.seed(seed)
377 x2 = self.gen.random()
378 y2 = self.gen.gauss(0, 1)
379
380 self.assertEqual(x1, x2)
381 self.assertEqual(y1, y2)
382
383 @support.requires_IEEE_754
384 def test_53_bits_per_float(self):
385 span = 2 ** 53
386 cum = 0
387 for i in range(100):
388 cum |= int(self.gen.random() * span)
389 self.assertEqual(cum, span-1)
390
391 def test_getrandbits(self):
392 getrandbits = self.gen.getrandbits
393 # Verify ranges
394 for k in range(1, 1000):
395 self.assertTrue(0 <= getrandbits(k) < 2**k)
396 self.assertEqual(getrandbits(0), 0)
397
398 # Verify all bits active
399 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
400 all_bits = 2**span-1
401 cum = 0
402 cpl_cum = 0
403 for i in range(100):
404 v = getrandbits(span)
405 cum |= v
406 cpl_cum |= all_bits ^ v
407 self.assertEqual(cum, all_bits)
408 self.assertEqual(cpl_cum, all_bits)
409
410 # Verify argument checking
411 self.assertRaises(TypeError, getrandbits)
412 self.assertRaises(TypeError, getrandbits, 1, 2)
413 self.assertRaises(ValueError, getrandbits, -1)
414 self.assertRaises(OverflowError, getrandbits, 1<<1000)
415 self.assertRaises(ValueError, getrandbits, -1<<1000)
416 self.assertRaises(TypeError, getrandbits, 10.1)
417
418 def test_bigrand(self):
419 # The randrange routine should build-up the required number of bits
420 # in stages so that all bit positions are active.
421 span = 2 ** 500
422 cum = 0
423 for i in range(100):
424 r = self.gen.randrange(span)
425 self.assertTrue(0 <= r < span)
426 cum |= r
427 self.assertEqual(cum, span-1)
428
429 def test_bigrand_ranges(self):
430 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
431 start = self.gen.randrange(2 ** (i-2))
432 stop = self.gen.randrange(2 ** i)
433 if stop <= start:
434 continue
435 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
436
437 def test_rangelimits(self):
438 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
439 self.assertEqual(set(range(start,stop)),
440 set([self.gen.randrange(start,stop) for i in range(100)]))
441
442 def test_randrange_nonunit_step(self):
443 rint = self.gen.randrange(0, 10, 2)
444 self.assertIn(rint, (0, 2, 4, 6, 8))
445 rint = self.gen.randrange(0, 2, 2)
446 self.assertEqual(rint, 0)
447
448 def test_randrange_errors(self):
449 raises_value_error = partial(self.assertRaises, ValueError, self.gen.randrange)
450 raises_type_error = partial(self.assertRaises, TypeError, self.gen.randrange)
451
452 # Empty range
453 raises_value_error(3, 3)
454 raises_value_error(-721)
455 raises_value_error(0, 100, -12)
456
457 # Zero step
458 raises_value_error(0, 42, 0)
459 raises_type_error(0, 42, 0.0)
460 raises_type_error(0, 0, 0.0)
461
462 # Non-integer stop
463 raises_type_error(3.14159)
464 raises_type_error(3.0)
465 raises_type_error(Fraction(3, 1))
466 raises_type_error('3')
467 raises_type_error(0, 2.71827)
468 raises_type_error(0, 2.0)
469 raises_type_error(0, Fraction(2, 1))
470 raises_type_error(0, '2')
471 raises_type_error(0, 2.71827, 2)
472
473 # Non-integer start
474 raises_type_error(2.71827, 5)
475 raises_type_error(2.0, 5)
476 raises_type_error(Fraction(2, 1), 5)
477 raises_type_error('2', 5)
478 raises_type_error(2.71827, 5, 2)
479
480 # Non-integer step
481 raises_type_error(0, 42, 3.14159)
482 raises_type_error(0, 42, 3.0)
483 raises_type_error(0, 42, Fraction(3, 1))
484 raises_type_error(0, 42, '3')
485 raises_type_error(0, 42, 1.0)
486 raises_type_error(0, 0, 1.0)
487
488 def test_randrange_step(self):
489 # bpo-42772: When stop is None, the step argument was being ignored.
490 randrange = self.gen.randrange
491 with self.assertRaises(TypeError):
492 randrange(1000, step=100)
493 with self.assertRaises(TypeError):
494 randrange(1000, None, step=100)
495 with self.assertRaises(TypeError):
496 randrange(1000, step=MyIndex(1))
497 with self.assertRaises(TypeError):
498 randrange(1000, None, step=MyIndex(1))
499
500 def test_randbelow_logic(self, _log=log, int=int):
501 # check bitcount transition points: 2**i and 2**(i+1)-1
502 # show that: k = int(1.001 + _log(n, 2))
503 # is equal to or one greater than the number of bits in n
504 for i in range(1, 1000):
505 n = 1 << i # check an exact power of two
506 numbits = i+1
507 k = int(1.00001 + _log(n, 2))
508 self.assertEqual(k, numbits)
509 self.assertEqual(n, 2**(k-1))
510
511 n += n - 1 # check 1 below the next power of two
512 k = int(1.00001 + _log(n, 2))
513 self.assertIn(k, [numbits, numbits+1])
514 self.assertTrue(2**k > n > 2**(k-2))
515
516 n -= n >> 15 # check a little farther below the next power of two
517 k = int(1.00001 + _log(n, 2))
518 self.assertEqual(k, numbits) # note the stronger assertion
519 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
520
521 def test_randrange_index(self):
522 randrange = self.gen.randrange
523 self.assertIn(randrange(MyIndex(5)), range(5))
524 self.assertIn(randrange(MyIndex(2), MyIndex(7)), range(2, 7))
525 self.assertIn(randrange(MyIndex(5), MyIndex(15), MyIndex(2)), range(5, 15, 2))
526
527 def test_randint(self):
528 randint = self.gen.randint
529 self.assertIn(randint(2, 5), (2, 3, 4, 5))
530 self.assertEqual(randint(2, 2), 2)
531 self.assertIn(randint(MyIndex(2), MyIndex(5)), (2, 3, 4, 5))
532 self.assertEqual(randint(MyIndex(2), MyIndex(2)), 2)
533
534 self.assertRaises(ValueError, randint, 5, 2)
535 self.assertRaises(TypeError, randint)
536 self.assertRaises(TypeError, randint, 2)
537 self.assertRaises(TypeError, randint, 2, 5, 1)
538 self.assertRaises(TypeError, randint, 2.0, 5)
539 self.assertRaises(TypeError, randint, 2, 5.0)
540
541 def test_pickling(self):
542 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
543 state = pickle.dumps(self.gen, proto)
544 origseq = [self.gen.random() for i in range(10)]
545 newgen = pickle.loads(state)
546 restoredseq = [newgen.random() for i in range(10)]
547 self.assertEqual(origseq, restoredseq)
548
549 def test_bug_1727780(self):
550 # verify that version-2-pickles can be loaded
551 # fine, whether they are created on 32-bit or 64-bit
552 # platforms, and that version-3-pickles load fine.
553 files = [("randv2_32.pck", 780),
554 ("randv2_64.pck", 866),
555 ("randv3.pck", 343)]
556 for file, value in files:
557 with open(support.findfile(file),"rb") as f:
558 r = pickle.load(f)
559 self.assertEqual(int(r.random()*1000), value)
560
561 def test_bug_9025(self):
562 # Had problem with an uneven distribution in int(n*random())
563 # Verify the fix by checking that distributions fall within expectations.
564 n = 100000
565 randrange = self.gen.randrange
566 k = sum(randrange(6755399441055744) % 3 == 2 for i in range(n))
567 self.assertTrue(0.30 < k/n < .37, (k/n))
568
569 def test_randrange_bug_1590891(self):
570 start = 1000000000000
571 stop = -100000000000000000000
572 step = -200
573 x = self.gen.randrange(start, stop, step)
574 self.assertTrue(stop < x <= start)
575 self.assertEqual((x+stop)%step, 0)
576
577 def test_randbytes(self):
578 # Verify ranges
579 for n in range(1, 10):
580 data = self.gen.randbytes(n)
581 self.assertEqual(type(data), bytes)
582 self.assertEqual(len(data), n)
583
584 self.assertEqual(self.gen.randbytes(0), b'')
585
586 # Verify argument checking
587 self.assertRaises(TypeError, self.gen.randbytes)
588 self.assertRaises(TypeError, self.gen.randbytes, 1, 2)
589 self.assertRaises(ValueError, self.gen.randbytes, -1)
590 self.assertRaises(OverflowError, self.gen.randbytes, 1<<1000)
591 self.assertRaises((ValueError, OverflowError), self.gen.randbytes, -1<<1000)
592 self.assertRaises(TypeError, self.gen.randbytes, 1.0)
593
594 def test_mu_sigma_default_args(self):
595 self.assertIsInstance(self.gen.normalvariate(), float)
596 self.assertIsInstance(self.gen.gauss(), float)
597
598
599 try:
600 random.SystemRandom().random()
601 except NotImplementedError:
602 SystemRandom_available = False
603 else:
604 SystemRandom_available = True
605
606 @unittest.skipUnless(SystemRandom_available, "random.SystemRandom not available")
607 class SystemRandom_TestBasicOps(TestBasicOps, unittest.TestCase):
608 gen = random.SystemRandom()
609
610 def test_autoseed(self):
611 # Doesn't need to do anything except not fail
612 self.gen.seed()
613
614 def test_saverestore(self):
615 self.assertRaises(NotImplementedError, self.gen.getstate)
616 self.assertRaises(NotImplementedError, self.gen.setstate, None)
617
618 def test_seedargs(self):
619 # Doesn't need to do anything except not fail
620 self.gen.seed(100)
621
622 def test_gauss(self):
623 self.gen.gauss_next = None
624 self.gen.seed(100)
625 self.assertEqual(self.gen.gauss_next, None)
626
627 def test_pickling(self):
628 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
629 self.assertRaises(NotImplementedError, pickle.dumps, self.gen, proto)
630
631
632 class TestRawMersenneTwister(unittest.TestCase):
633 @test.support.cpython_only
634 def test_bug_41052(self):
635 # _random.Random should not be allowed to serialization
636 import _random
637 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
638 r = _random.Random()
639 self.assertRaises(TypeError, pickle.dumps, r, proto)
640
641 @test.support.cpython_only
642 def test_bug_42008(self):
643 # _random.Random should call seed with first element of arg tuple
644 import _random
645 r1 = _random.Random()
646 r1.seed(8675309)
647 r2 = _random.Random(8675309)
648 self.assertEqual(r1.random(), r2.random())
649
650
651 class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase):
652 gen = random.Random()
653
654 def test_guaranteed_stable(self):
655 # These sequences are guaranteed to stay the same across versions of python
656 self.gen.seed(3456147, version=1)
657 self.assertEqual([self.gen.random().hex() for i in range(4)],
658 ['0x1.ac362300d90d2p-1', '0x1.9d16f74365005p-1',
659 '0x1.1ebb4352e4c4dp-1', '0x1.1a7422abf9c11p-1'])
660 self.gen.seed("the quick brown fox", version=2)
661 self.assertEqual([self.gen.random().hex() for i in range(4)],
662 ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4',
663 '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1'])
664
665 def test_bug_27706(self):
666 # Verify that version 1 seeds are unaffected by hash randomization
667
668 self.gen.seed('nofar', version=1) # hash('nofar') == 5990528763808513177
669 self.assertEqual([self.gen.random().hex() for i in range(4)],
670 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
671 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
672
673 self.gen.seed('rachel', version=1) # hash('rachel') == -9091735575445484789
674 self.assertEqual([self.gen.random().hex() for i in range(4)],
675 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
676 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
677
678 self.gen.seed('', version=1) # hash('') == 0
679 self.assertEqual([self.gen.random().hex() for i in range(4)],
680 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
681 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
682
683 def test_bug_31478(self):
684 # There shouldn't be an assertion failure in _random.Random.seed() in
685 # case the argument has a bad __abs__() method.
686 class BadInt(int):
687 def __abs__(self):
688 return None
689 try:
690 self.gen.seed(BadInt())
691 except TypeError:
692 pass
693
694 def test_bug_31482(self):
695 # Verify that version 1 seeds are unaffected by hash randomization
696 # when the seeds are expressed as bytes rather than strings.
697 # The hash(b) values listed are the Python2.7 hash() values
698 # which were used for seeding.
699
700 self.gen.seed(b'nofar', version=1) # hash('nofar') == 5990528763808513177
701 self.assertEqual([self.gen.random().hex() for i in range(4)],
702 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
703 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
704
705 self.gen.seed(b'rachel', version=1) # hash('rachel') == -9091735575445484789
706 self.assertEqual([self.gen.random().hex() for i in range(4)],
707 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
708 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
709
710 self.gen.seed(b'', version=1) # hash('') == 0
711 self.assertEqual([self.gen.random().hex() for i in range(4)],
712 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
713 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
714
715 b = b'\x00\x20\x40\x60\x80\xA0\xC0\xE0\xF0'
716 self.gen.seed(b, version=1) # hash(b) == 5015594239749365497
717 self.assertEqual([self.gen.random().hex() for i in range(4)],
718 ['0x1.52c2fde444d23p-1', '0x1.875174f0daea4p-2',
719 '0x1.9e9b2c50e5cd2p-1', '0x1.fa57768bd321cp-2'])
720
721 def test_setstate_first_arg(self):
722 self.assertRaises(ValueError, self.gen.setstate, (1, None, None))
723
724 def test_setstate_middle_arg(self):
725 start_state = self.gen.getstate()
726 # Wrong type, s/b tuple
727 self.assertRaises(TypeError, self.gen.setstate, (2, None, None))
728 # Wrong length, s/b 625
729 self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None))
730 # Wrong type, s/b tuple of 625 ints
731 self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None))
732 # Last element s/b an int also
733 self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None))
734 # Last element s/b between 0 and 624
735 with self.assertRaises((ValueError, OverflowError)):
736 self.gen.setstate((2, (1,)*624+(625,), None))
737 with self.assertRaises((ValueError, OverflowError)):
738 self.gen.setstate((2, (1,)*624+(-1,), None))
739 # Failed calls to setstate() should not have changed the state.
740 bits100 = self.gen.getrandbits(100)
741 self.gen.setstate(start_state)
742 self.assertEqual(self.gen.getrandbits(100), bits100)
743
744 # Little trick to make "tuple(x % (2**32) for x in internalstate)"
745 # raise ValueError. I cannot think of a simple way to achieve this, so
746 # I am opting for using a generator as the middle argument of setstate
747 # which attempts to cast a NaN to integer.
748 state_values = self.gen.getstate()[1]
749 state_values = list(state_values)
750 state_values[-1] = float('nan')
751 state = (int(x) for x in state_values)
752 self.assertRaises(TypeError, self.gen.setstate, (2, state, None))
753
754 def test_referenceImplementation(self):
755 # Compare the python implementation with results from the original
756 # code. Create 2000 53-bit precision random floats. Compare only
757 # the last ten entries to show that the independent implementations
758 # are tracking. Here is the main() function needed to create the
759 # list of expected random numbers:
760 # void main(void){
761 # int i;
762 # unsigned long init[4]={61731, 24903, 614, 42143}, length=4;
763 # init_by_array(init, length);
764 # for (i=0; i<2000; i++) {
765 # printf("%.15f ", genrand_res53());
766 # if (i%5==4) printf("\n");
767 # }
768 # }
769 expected = [0.45839803073713259,
770 0.86057815201978782,
771 0.92848331726782152,
772 0.35932681119782461,
773 0.081823493762449573,
774 0.14332226470169329,
775 0.084297823823520024,
776 0.53814864671831453,
777 0.089215024911993401,
778 0.78486196105372907]
779
780 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
781 actual = self.randomlist(2000)[-10:]
782 for a, e in zip(actual, expected):
783 self.assertAlmostEqual(a,e,places=14)
784
785 def test_strong_reference_implementation(self):
786 # Like test_referenceImplementation, but checks for exact bit-level
787 # equality. This should pass on any box where C double contains
788 # at least 53 bits of precision (the underlying algorithm suffers
789 # no rounding errors -- all results are exact).
790 from math import ldexp
791
792 expected = [0x0eab3258d2231f,
793 0x1b89db315277a5,
794 0x1db622a5518016,
795 0x0b7f9af0d575bf,
796 0x029e4c4db82240,
797 0x04961892f5d673,
798 0x02b291598e4589,
799 0x11388382c15694,
800 0x02dad977c9e1fe,
801 0x191d96d4d334c6]
802 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
803 actual = self.randomlist(2000)[-10:]
804 for a, e in zip(actual, expected):
805 self.assertEqual(int(ldexp(a, 53)), e)
806
807 def test_long_seed(self):
808 # This is most interesting to run in debug mode, just to make sure
809 # nothing blows up. Under the covers, a dynamically resized array
810 # is allocated, consuming space proportional to the number of bits
811 # in the seed. Unfortunately, that's a quadratic-time algorithm,
812 # so don't make this horribly big.
813 seed = (1 << (10000 * 8)) - 1 # about 10K bytes
814 self.gen.seed(seed)
815
816 def test_getrandbits(self):
817 super().test_getrandbits()
818
819 # Verify cross-platform repeatability
820 self.gen.seed(1234567)
821 self.assertEqual(self.gen.getrandbits(100),
822 97904845777343510404718956115)
823 self.gen.seed(1234567)
824 self.assertEqual(self.gen.getrandbits(MyIndex(100)),
825 97904845777343510404718956115)
826
827 def test_getrandbits_2G_bits(self):
828 size = 2**31
829 self.gen.seed(1234567)
830 x = self.gen.getrandbits(size)
831 self.assertEqual(x.bit_length(), size)
832 self.assertEqual(x & (2**100-1), 890186470919986886340158459475)
833 self.assertEqual(x >> (size-100), 1226514312032729439655761284440)
834
835 @support.bigmemtest(size=2**32, memuse=1/8+2/15, dry_run=False)
836 def test_getrandbits_4G_bits(self, size):
837 self.gen.seed(1234568)
838 x = self.gen.getrandbits(size)
839 self.assertEqual(x.bit_length(), size)
840 self.assertEqual(x & (2**100-1), 287241425661104632871036099814)
841 self.assertEqual(x >> (size-100), 739728759900339699429794460738)
842
843 def test_randrange_uses_getrandbits(self):
844 # Verify use of getrandbits by randrange
845 # Use same seed as in the cross-platform repeatability test
846 # in test_getrandbits above.
847 self.gen.seed(1234567)
848 # If randrange uses getrandbits, it should pick getrandbits(100)
849 # when called with a 100-bits stop argument.
850 self.assertEqual(self.gen.randrange(2**99),
851 97904845777343510404718956115)
852
853 def test_randbelow_without_getrandbits(self):
854 # Random._randbelow() can only use random() when the built-in one
855 # has been overridden but no new getrandbits() method was supplied.
856 maxsize = 1<<random.BPF
857 with warnings.catch_warnings():
858 warnings.simplefilter("ignore", UserWarning)
859 # Population range too large (n >= maxsize)
860 self.gen._randbelow_without_getrandbits(
861 maxsize+1, maxsize=maxsize
862 )
863 self.gen._randbelow_without_getrandbits(5640, maxsize=maxsize)
864
865 # This might be going too far to test a single line, but because of our
866 # noble aim of achieving 100% test coverage we need to write a case in
867 # which the following line in Random._randbelow() gets executed:
868 #
869 # rem = maxsize % n
870 # limit = (maxsize - rem) / maxsize
871 # r = random()
872 # while r >= limit:
873 # r = random() # <== *This line* <==<
874 #
875 # Therefore, to guarantee that the while loop is executed at least
876 # once, we need to mock random() so that it returns a number greater
877 # than 'limit' the first time it gets called.
878
879 n = 42
880 epsilon = 0.01
881 limit = (maxsize - (maxsize % n)) / maxsize
882 with unittest.mock.patch.object(random.Random, 'random') as random_mock:
883 random_mock.side_effect = [limit + epsilon, limit - epsilon]
884 self.gen._randbelow_without_getrandbits(n, maxsize=maxsize)
885 self.assertEqual(random_mock.call_count, 2)
886
887 def test_choices_algorithms(self):
888 # The various ways of specifying weights should produce the same results
889 choices = self.gen.choices
890 n = 104729
891
892 self.gen.seed(8675309)
893 a = self.gen.choices(range(n), k=10000)
894
895 self.gen.seed(8675309)
896 b = self.gen.choices(range(n), [1]*n, k=10000)
897 self.assertEqual(a, b)
898
899 self.gen.seed(8675309)
900 c = self.gen.choices(range(n), cum_weights=range(1, n+1), k=10000)
901 self.assertEqual(a, c)
902
903 # American Roulette
904 population = ['Red', 'Black', 'Green']
905 weights = [18, 18, 2]
906 cum_weights = [18, 36, 38]
907 expanded_population = ['Red'] * 18 + ['Black'] * 18 + ['Green'] * 2
908
909 self.gen.seed(9035768)
910 a = self.gen.choices(expanded_population, k=10000)
911
912 self.gen.seed(9035768)
913 b = self.gen.choices(population, weights, k=10000)
914 self.assertEqual(a, b)
915
916 self.gen.seed(9035768)
917 c = self.gen.choices(population, cum_weights=cum_weights, k=10000)
918 self.assertEqual(a, c)
919
920 def test_randbytes(self):
921 super().test_randbytes()
922
923 # Mersenne Twister randbytes() is deterministic
924 # and does not depend on the endian and bitness.
925 seed = 8675309
926 expected = b'3\xa8\xf9f\xf4\xa4\xd06\x19\x8f\x9f\x82\x02oe\xf0'
927
928 self.gen.seed(seed)
929 self.assertEqual(self.gen.randbytes(16), expected)
930
931 # randbytes(0) must not consume any entropy
932 self.gen.seed(seed)
933 self.assertEqual(self.gen.randbytes(0), b'')
934 self.assertEqual(self.gen.randbytes(16), expected)
935
936 # Four randbytes(4) calls give the same output than randbytes(16)
937 self.gen.seed(seed)
938 self.assertEqual(b''.join([self.gen.randbytes(4) for _ in range(4)]),
939 expected)
940
941 # Each randbytes(1), randbytes(2) or randbytes(3) call consumes
942 # 4 bytes of entropy
943 self.gen.seed(seed)
944 expected1 = expected[3::4]
945 self.assertEqual(b''.join(self.gen.randbytes(1) for _ in range(4)),
946 expected1)
947
948 self.gen.seed(seed)
949 expected2 = b''.join(expected[i + 2: i + 4]
950 for i in range(0, len(expected), 4))
951 self.assertEqual(b''.join(self.gen.randbytes(2) for _ in range(4)),
952 expected2)
953
954 self.gen.seed(seed)
955 expected3 = b''.join(expected[i + 1: i + 4]
956 for i in range(0, len(expected), 4))
957 self.assertEqual(b''.join(self.gen.randbytes(3) for _ in range(4)),
958 expected3)
959
960 def test_randbytes_getrandbits(self):
961 # There is a simple relation between randbytes() and getrandbits()
962 seed = 2849427419
963 gen2 = random.Random()
964 self.gen.seed(seed)
965 gen2.seed(seed)
966 for n in range(9):
967 self.assertEqual(self.gen.randbytes(n),
968 gen2.getrandbits(n * 8).to_bytes(n, 'little'))
969
970 @support.bigmemtest(size=2**29, memuse=1+16/15, dry_run=False)
971 def test_randbytes_256M(self, size):
972 self.gen.seed(2849427419)
973 x = self.gen.randbytes(size)
974 self.assertEqual(len(x), size)
975 self.assertEqual(x[:12].hex(), 'f6fd9ae63855ab91ea238b4f')
976 self.assertEqual(x[-12:].hex(), '0e7af69a84ee99bf4a11becc')
977
978 def test_sample_counts_equivalence(self):
979 # Test the documented strong equivalence to a sample with repeated elements.
980 # We run this test on random.Random() which makes deterministic selections
981 # for a given seed value.
982 sample = self.gen.sample
983 seed = self.gen.seed
984
985 colors = ['red', 'green', 'blue', 'orange', 'black', 'amber']
986 counts = [500, 200, 20, 10, 5, 1 ]
987 k = 700
988 seed(8675309)
989 s1 = sample(colors, counts=counts, k=k)
990 seed(8675309)
991 expanded = [color for (color, count) in zip(colors, counts) for i in range(count)]
992 self.assertEqual(len(expanded), sum(counts))
993 s2 = sample(expanded, k=k)
994 self.assertEqual(s1, s2)
995
996 pop = 'abcdefghi'
997 counts = [10, 9, 8, 7, 6, 5, 4, 3, 2]
998 seed(8675309)
999 s1 = ''.join(sample(pop, counts=counts, k=30))
1000 expanded = ''.join([letter for (letter, count) in zip(pop, counts) for i in range(count)])
1001 seed(8675309)
1002 s2 = ''.join(sample(expanded, k=30))
1003 self.assertEqual(s1, s2)
1004
1005
1006 def gamma(z, sqrt2pi=(2.0*pi)**0.5):
1007 # Reflection to right half of complex plane
1008 if z < 0.5:
1009 return pi / sin(pi*z) / gamma(1.0-z)
1010 # Lanczos approximation with g=7
1011 az = z + (7.0 - 0.5)
1012 return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
1013 0.9999999999995183,
1014 676.5203681218835 / z,
1015 -1259.139216722289 / (z+1.0),
1016 771.3234287757674 / (z+2.0),
1017 -176.6150291498386 / (z+3.0),
1018 12.50734324009056 / (z+4.0),
1019 -0.1385710331296526 / (z+5.0),
1020 0.9934937113930748e-05 / (z+6.0),
1021 0.1659470187408462e-06 / (z+7.0),
1022 ])
1023
1024 class TestDistributions(unittest.TestCase):
1025 def test_zeroinputs(self):
1026 # Verify that distributions can handle a series of zero inputs'
1027 g = random.Random()
1028 x = [g.random() for i in range(50)] + [0.0]*5
1029 g.random = x[:].pop; g.uniform(1,10)
1030 g.random = x[:].pop; g.paretovariate(1.0)
1031 g.random = x[:].pop; g.expovariate(1.0)
1032 g.random = x[:].pop; g.expovariate()
1033 g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
1034 g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
1035 g.random = x[:].pop; g.normalvariate(0.0, 1.0)
1036 g.random = x[:].pop; g.gauss(0.0, 1.0)
1037 g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
1038 g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
1039 g.random = x[:].pop; g.gammavariate(0.01, 1.0)
1040 g.random = x[:].pop; g.gammavariate(1.0, 1.0)
1041 g.random = x[:].pop; g.gammavariate(200.0, 1.0)
1042 g.random = x[:].pop; g.betavariate(3.0, 3.0)
1043 g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
1044
1045 def test_avg_std(self):
1046 # Use integration to test distribution average and standard deviation.
1047 # Only works for distributions which do not consume variates in pairs
1048 g = random.Random()
1049 N = 5000
1050 x = [i/float(N) for i in range(1,N)]
1051 for variate, args, mu, sigmasqrd in [
1052 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
1053 (g.triangular, (0.0, 1.0, 1.0/3.0), 4.0/9.0, 7.0/9.0/18.0),
1054 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
1055 (g.vonmisesvariate, (1.23, 0), pi, pi**2/3),
1056 (g.paretovariate, (5.0,), 5.0/(5.0-1),
1057 5.0/((5.0-1)**2*(5.0-2))),
1058 (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0),
1059 gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
1060 g.random = x[:].pop
1061 y = []
1062 for i in range(len(x)):
1063 try:
1064 y.append(variate(*args))
1065 except IndexError:
1066 pass
1067 s1 = s2 = 0
1068 for e in y:
1069 s1 += e
1070 s2 += (e - mu) ** 2
1071 N = len(y)
1072 self.assertAlmostEqual(s1/N, mu, places=2,
1073 msg='%s%r' % (variate.__name__, args))
1074 self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2,
1075 msg='%s%r' % (variate.__name__, args))
1076
1077 def test_constant(self):
1078 g = random.Random()
1079 N = 100
1080 for variate, args, expected in [
1081 (g.uniform, (10.0, 10.0), 10.0),
1082 (g.triangular, (10.0, 10.0), 10.0),
1083 (g.triangular, (10.0, 10.0, 10.0), 10.0),
1084 (g.expovariate, (float('inf'),), 0.0),
1085 (g.vonmisesvariate, (3.0, float('inf')), 3.0),
1086 (g.gauss, (10.0, 0.0), 10.0),
1087 (g.lognormvariate, (0.0, 0.0), 1.0),
1088 (g.lognormvariate, (-float('inf'), 0.0), 0.0),
1089 (g.normalvariate, (10.0, 0.0), 10.0),
1090 (g.binomialvariate, (0, 0.5), 0),
1091 (g.binomialvariate, (10, 0.0), 0),
1092 (g.binomialvariate, (10, 1.0), 10),
1093 (g.paretovariate, (float('inf'),), 1.0),
1094 (g.weibullvariate, (10.0, float('inf')), 10.0),
1095 (g.weibullvariate, (0.0, 10.0), 0.0),
1096 ]:
1097 for i in range(N):
1098 self.assertEqual(variate(*args), expected)
1099
1100 def test_binomialvariate(self):
1101 B = random.binomialvariate
1102
1103 # Cover all the code paths
1104 with self.assertRaises(ValueError):
1105 B(n=-1) # Negative n
1106 with self.assertRaises(ValueError):
1107 B(n=1, p=-0.5) # Negative p
1108 with self.assertRaises(ValueError):
1109 B(n=1, p=1.5) # p > 1.0
1110 self.assertEqual(B(0, 0.5), 0) # n == 0
1111 self.assertEqual(B(10, 0.0), 0) # p == 0.0
1112 self.assertEqual(B(10, 1.0), 10) # p == 1.0
1113 self.assertTrue(B(1, 0.3) in {0, 1}) # n == 1 fast path
1114 self.assertTrue(B(1, 0.9) in {0, 1}) # n == 1 fast path
1115 self.assertTrue(B(1, 0.0) in {0}) # n == 1 fast path
1116 self.assertTrue(B(1, 1.0) in {1}) # n == 1 fast path
1117
1118 # BG method very small p
1119 self.assertEqual(B(5, 1e-18), 0)
1120
1121 # BG method p <= 0.5 and n*p=1.25
1122 self.assertTrue(B(5, 0.25) in set(range(6)))
1123
1124 # BG method p >= 0.5 and n*(1-p)=1.25
1125 self.assertTrue(B(5, 0.75) in set(range(6)))
1126
1127 # BTRS method p <= 0.5 and n*p=25
1128 self.assertTrue(B(100, 0.25) in set(range(101)))
1129
1130 # BTRS method p > 0.5 and n*(1-p)=25
1131 self.assertTrue(B(100, 0.75) in set(range(101)))
1132
1133 # Statistical tests chosen such that they are
1134 # exceedingly unlikely to ever fail for correct code.
1135
1136 # BG code path
1137 # Expected dist: [31641, 42188, 21094, 4688, 391]
1138 c = Counter(B(4, 0.25) for i in range(100_000))
1139 self.assertTrue(29_641 <= c[0] <= 33_641, c)
1140 self.assertTrue(40_188 <= c[1] <= 44_188)
1141 self.assertTrue(19_094 <= c[2] <= 23_094)
1142 self.assertTrue(2_688 <= c[3] <= 6_688)
1143 self.assertEqual(set(c), {0, 1, 2, 3, 4})
1144
1145 # BTRS code path
1146 # Sum of c[20], c[21], c[22], c[23], c[24] expected to be 36,214
1147 c = Counter(B(100, 0.25) for i in range(100_000))
1148 self.assertTrue(34_214 <= c[20]+c[21]+c[22]+c[23]+c[24] <= 38_214)
1149 self.assertTrue(set(c) <= set(range(101)))
1150 self.assertEqual(c.total(), 100_000)
1151
1152 # Demonstrate the BTRS works for huge values of n
1153 self.assertTrue(19_000_000 <= B(100_000_000, 0.2) <= 21_000_000)
1154 self.assertTrue(89_000_000 <= B(100_000_000, 0.9) <= 91_000_000)
1155
1156
1157 def test_von_mises_range(self):
1158 # Issue 17149: von mises variates were not consistently in the
1159 # range [0, 2*PI].
1160 g = random.Random()
1161 N = 100
1162 for mu in 0.0, 0.1, 3.1, 6.2:
1163 for kappa in 0.0, 2.3, 500.0:
1164 for _ in range(N):
1165 sample = g.vonmisesvariate(mu, kappa)
1166 self.assertTrue(
1167 0 <= sample <= random.TWOPI,
1168 msg=("vonmisesvariate({}, {}) produced a result {} out"
1169 " of range [0, 2*pi]").format(mu, kappa, sample))
1170
1171 def test_von_mises_large_kappa(self):
1172 # Issue #17141: vonmisesvariate() was hang for large kappas
1173 random.vonmisesvariate(0, 1e15)
1174 random.vonmisesvariate(0, 1e100)
1175
1176 def test_gammavariate_errors(self):
1177 # Both alpha and beta must be > 0.0
1178 self.assertRaises(ValueError, random.gammavariate, -1, 3)
1179 self.assertRaises(ValueError, random.gammavariate, 0, 2)
1180 self.assertRaises(ValueError, random.gammavariate, 2, 0)
1181 self.assertRaises(ValueError, random.gammavariate, 1, -3)
1182
1183 # There are three different possibilities in the current implementation
1184 # of random.gammavariate(), depending on the value of 'alpha'. What we
1185 # are going to do here is to fix the values returned by random() to
1186 # generate test cases that provide 100% line coverage of the method.
1187 @unittest.mock.patch('random.Random.random')
1188 def test_gammavariate_alpha_greater_one(self, random_mock):
1189
1190 # #1: alpha > 1.0.
1191 # We want the first random number to be outside the
1192 # [1e-7, .9999999] range, so that the continue statement executes
1193 # once. The values of u1 and u2 will be 0.5 and 0.3, respectively.
1194 random_mock.side_effect = [1e-8, 0.5, 0.3]
1195 returned_value = random.gammavariate(1.1, 2.3)
1196 self.assertAlmostEqual(returned_value, 2.53)
1197
1198 @unittest.mock.patch('random.Random.random')
1199 def test_gammavariate_alpha_equal_one(self, random_mock):
1200
1201 # #2.a: alpha == 1.
1202 # The execution body of the while loop executes once.
1203 # Then random.random() returns 0.45,
1204 # which causes while to stop looping and the algorithm to terminate.
1205 random_mock.side_effect = [0.45]
1206 returned_value = random.gammavariate(1.0, 3.14)
1207 self.assertAlmostEqual(returned_value, 1.877208182372648)
1208
1209 @unittest.mock.patch('random.Random.random')
1210 def test_gammavariate_alpha_equal_one_equals_expovariate(self, random_mock):
1211
1212 # #2.b: alpha == 1.
1213 # It must be equivalent of calling expovariate(1.0 / beta).
1214 beta = 3.14
1215 random_mock.side_effect = [1e-8, 1e-8]
1216 gammavariate_returned_value = random.gammavariate(1.0, beta)
1217 expovariate_returned_value = random.expovariate(1.0 / beta)
1218 self.assertAlmostEqual(gammavariate_returned_value, expovariate_returned_value)
1219
1220 @unittest.mock.patch('random.Random.random')
1221 def test_gammavariate_alpha_between_zero_and_one(self, random_mock):
1222
1223 # #3: 0 < alpha < 1.
1224 # This is the most complex region of code to cover,
1225 # as there are multiple if-else statements. Let's take a look at the
1226 # source code, and determine the values that we need accordingly:
1227 #
1228 # while 1:
1229 # u = random()
1230 # b = (_e + alpha)/_e
1231 # p = b*u
1232 # if p <= 1.0: # <=== (A)
1233 # x = p ** (1.0/alpha)
1234 # else: # <=== (B)
1235 # x = -_log((b-p)/alpha)
1236 # u1 = random()
1237 # if p > 1.0: # <=== (C)
1238 # if u1 <= x ** (alpha - 1.0): # <=== (D)
1239 # break
1240 # elif u1 <= _exp(-x): # <=== (E)
1241 # break
1242 # return x * beta
1243 #
1244 # First, we want (A) to be True. For that we need that:
1245 # b*random() <= 1.0
1246 # r1 = random() <= 1.0 / b
1247 #
1248 # We now get to the second if-else branch, and here, since p <= 1.0,
1249 # (C) is False and we take the elif branch, (E). For it to be True,
1250 # so that the break is executed, we need that:
1251 # r2 = random() <= _exp(-x)
1252 # r2 <= _exp(-(p ** (1.0/alpha)))
1253 # r2 <= _exp(-((b*r1) ** (1.0/alpha)))
1254
1255 _e = random._e
1256 _exp = random._exp
1257 _log = random._log
1258 alpha = 0.35
1259 beta = 1.45
1260 b = (_e + alpha)/_e
1261 epsilon = 0.01
1262
1263 r1 = 0.8859296441566 # 1.0 / b
1264 r2 = 0.3678794411714 # _exp(-((b*r1) ** (1.0/alpha)))
1265
1266 # These four "random" values result in the following trace:
1267 # (A) True, (E) False --> [next iteration of while]
1268 # (A) True, (E) True --> [while loop breaks]
1269 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
1270 returned_value = random.gammavariate(alpha, beta)
1271 self.assertAlmostEqual(returned_value, 1.4499999999997544)
1272
1273 # Let's now make (A) be False. If this is the case, when we get to the
1274 # second if-else 'p' is greater than 1, so (C) evaluates to True. We
1275 # now encounter a second if statement, (D), which in order to execute
1276 # must satisfy the following condition:
1277 # r2 <= x ** (alpha - 1.0)
1278 # r2 <= (-_log((b-p)/alpha)) ** (alpha - 1.0)
1279 # r2 <= (-_log((b-(b*r1))/alpha)) ** (alpha - 1.0)
1280 r1 = 0.8959296441566 # (1.0 / b) + epsilon -- so that (A) is False
1281 r2 = 0.9445400408898141
1282
1283 # And these four values result in the following trace:
1284 # (B) and (C) True, (D) False --> [next iteration of while]
1285 # (B) and (C) True, (D) True [while loop breaks]
1286 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
1287 returned_value = random.gammavariate(alpha, beta)
1288 self.assertAlmostEqual(returned_value, 1.5830349561760781)
1289
1290 @unittest.mock.patch('random.Random.gammavariate')
1291 def test_betavariate_return_zero(self, gammavariate_mock):
1292 # betavariate() returns zero when the Gamma distribution
1293 # that it uses internally returns this same value.
1294 gammavariate_mock.return_value = 0.0
1295 self.assertEqual(0.0, random.betavariate(2.71828, 3.14159))
1296
1297
1298 class TestRandomSubclassing(unittest.TestCase):
1299 def test_random_subclass_with_kwargs(self):
1300 # SF bug #1486663 -- this used to erroneously raise a TypeError
1301 class Subclass(random.Random):
1302 def __init__(self, newarg=None):
1303 random.Random.__init__(self)
1304 Subclass(newarg=1)
1305
1306 def test_subclasses_overriding_methods(self):
1307 # Subclasses with an overridden random, but only the original
1308 # getrandbits method should not rely on getrandbits in for randrange,
1309 # but should use a getrandbits-independent implementation instead.
1310
1311 # subclass providing its own random **and** getrandbits methods
1312 # like random.SystemRandom does => keep relying on getrandbits for
1313 # randrange
1314 class SubClass1(random.Random):
1315 def random(self):
1316 called.add('SubClass1.random')
1317 return random.Random.random(self)
1318
1319 def getrandbits(self, n):
1320 called.add('SubClass1.getrandbits')
1321 return random.Random.getrandbits(self, n)
1322 called = set()
1323 SubClass1().randrange(42)
1324 self.assertEqual(called, {'SubClass1.getrandbits'})
1325
1326 # subclass providing only random => can only use random for randrange
1327 class SubClass2(random.Random):
1328 def random(self):
1329 called.add('SubClass2.random')
1330 return random.Random.random(self)
1331 called = set()
1332 SubClass2().randrange(42)
1333 self.assertEqual(called, {'SubClass2.random'})
1334
1335 # subclass defining getrandbits to complement its inherited random
1336 # => can now rely on getrandbits for randrange again
1337 class SubClass3(SubClass2):
1338 def getrandbits(self, n):
1339 called.add('SubClass3.getrandbits')
1340 return random.Random.getrandbits(self, n)
1341 called = set()
1342 SubClass3().randrange(42)
1343 self.assertEqual(called, {'SubClass3.getrandbits'})
1344
1345 # subclass providing only random and inherited getrandbits
1346 # => random takes precedence
1347 class SubClass4(SubClass3):
1348 def random(self):
1349 called.add('SubClass4.random')
1350 return random.Random.random(self)
1351 called = set()
1352 SubClass4().randrange(42)
1353 self.assertEqual(called, {'SubClass4.random'})
1354
1355 # Following subclasses don't define random or getrandbits directly,
1356 # but inherit them from classes which are not subclasses of Random
1357 class Mixin1:
1358 def random(self):
1359 called.add('Mixin1.random')
1360 return random.Random.random(self)
1361 class Mixin2:
1362 def getrandbits(self, n):
1363 called.add('Mixin2.getrandbits')
1364 return random.Random.getrandbits(self, n)
1365
1366 class SubClass5(Mixin1, random.Random):
1367 pass
1368 called = set()
1369 SubClass5().randrange(42)
1370 self.assertEqual(called, {'Mixin1.random'})
1371
1372 class SubClass6(Mixin2, random.Random):
1373 pass
1374 called = set()
1375 SubClass6().randrange(42)
1376 self.assertEqual(called, {'Mixin2.getrandbits'})
1377
1378 class SubClass7(Mixin1, Mixin2, random.Random):
1379 pass
1380 called = set()
1381 SubClass7().randrange(42)
1382 self.assertEqual(called, {'Mixin1.random'})
1383
1384 class SubClass8(Mixin2, Mixin1, random.Random):
1385 pass
1386 called = set()
1387 SubClass8().randrange(42)
1388 self.assertEqual(called, {'Mixin2.getrandbits'})
1389
1390
1391 class TestModule(unittest.TestCase):
1392 def testMagicConstants(self):
1393 self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141)
1394 self.assertAlmostEqual(random.TWOPI, 6.28318530718)
1395 self.assertAlmostEqual(random.LOG4, 1.38629436111989)
1396 self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627)
1397
1398 def test__all__(self):
1399 # tests validity but not completeness of the __all__ list
1400 self.assertTrue(set(random.__all__) <= set(dir(random)))
1401
1402 @test.support.requires_fork()
1403 def test_after_fork(self):
1404 # Test the global Random instance gets reseeded in child
1405 r, w = os.pipe()
1406 pid = os.fork()
1407 if pid == 0:
1408 # child process
1409 try:
1410 val = random.getrandbits(128)
1411 with open(w, "w") as f:
1412 f.write(str(val))
1413 finally:
1414 os._exit(0)
1415 else:
1416 # parent process
1417 os.close(w)
1418 val = random.getrandbits(128)
1419 with open(r, "r") as f:
1420 child_val = eval(f.read())
1421 self.assertNotEqual(val, child_val)
1422
1423 support.wait_process(pid, exitcode=0)
1424
1425
1426 class CommandLineTest(unittest.TestCase):
1427 @support.force_not_colorized
1428 def test_parse_args(self):
1429 args, help_text = random._parse_args(shlex.split("--choice a b c"))
1430 self.assertEqual(args.choice, ["a", "b", "c"])
1431 self.assertStartsWith(help_text, "usage: ")
1432
1433 args, help_text = random._parse_args(shlex.split("--integer 5"))
1434 self.assertEqual(args.integer, 5)
1435 self.assertStartsWith(help_text, "usage: ")
1436
1437 args, help_text = random._parse_args(shlex.split("--float 2.5"))
1438 self.assertEqual(args.float, 2.5)
1439 self.assertStartsWith(help_text, "usage: ")
1440
1441 args, help_text = random._parse_args(shlex.split("a b c"))
1442 self.assertEqual(args.input, ["a", "b", "c"])
1443 self.assertStartsWith(help_text, "usage: ")
1444
1445 args, help_text = random._parse_args(shlex.split("5"))
1446 self.assertEqual(args.input, ["5"])
1447 self.assertStartsWith(help_text, "usage: ")
1448
1449 args, help_text = random._parse_args(shlex.split("2.5"))
1450 self.assertEqual(args.input, ["2.5"])
1451 self.assertStartsWith(help_text, "usage: ")
1452
1453 def test_main(self):
1454 for command, expected in [
1455 ("--choice a b c", "b"),
1456 ('"a b c"', "b"),
1457 ("a b c", "b"),
1458 ("--choice 'a a' 'b b' 'c c'", "b b"),
1459 ("'a a' 'b b' 'c c'", "b b"),
1460 ("--integer 5", 4),
1461 ("5", 4),
1462 ("--float 2.5", 2.1110546288126204),
1463 ("2.5", 2.1110546288126204),
1464 ]:
1465 random.seed(0)
1466 self.assertEqual(random.main(shlex.split(command)), expected)
1467
1468
1469 if __name__ == "__main__":
1470 unittest.main()