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