blob: 6d87d21cf22c6b4340c4207f23aed690ce003cf9 [file] [log] [blame]
Raymond Hettinger40f62172002-12-29 23:03:38 +00001import unittest
R David Murraye3e1c172013-04-02 12:47:23 -04002import unittest.mock
Tim Peters46c04e12002-05-05 20:40:00 +00003import random
Antoine Pitrou346cbd32017-05-27 17:50:54 +02004import os
Raymond Hettinger40f62172002-12-29 23:03:38 +00005import time
Raymond Hettinger5f078ff2003-06-24 20:29:04 +00006import pickle
Raymond Hettinger2f726e92003-10-05 09:09:15 +00007import warnings
R David Murraye3e1c172013-04-02 12:47:23 -04008from functools import partial
Victor Stinnerbd1b49a2016-10-19 10:11:37 +02009from math import log, exp, pi, fsum, sin, factorial
Benjamin Petersonee8712c2008-05-20 21:35:26 +000010from test import support
Raymond Hettingere8f1e002016-09-06 17:15:29 -070011from fractions import Fraction
Tim Peters46c04e12002-05-05 20:40:00 +000012
csabellaf111fd22017-05-11 11:19:35 -040013
Ezio Melotti3e4a98b2013-04-19 05:45:27 +030014class TestBasicOps:
Raymond Hettinger40f62172002-12-29 23:03:38 +000015 # Superclass with tests common to all generators.
16 # Subclasses must arrange for self.gen to retrieve the Random instance
17 # to be tested.
Tim Peters46c04e12002-05-05 20:40:00 +000018
Raymond Hettinger40f62172002-12-29 23:03:38 +000019 def randomlist(self, n):
20 """Helper function to make a list of random numbers"""
Guido van Rossum805365e2007-05-07 22:24:25 +000021 return [self.gen.random() for i in range(n)]
Tim Peters46c04e12002-05-05 20:40:00 +000022
Raymond Hettinger40f62172002-12-29 23:03:38 +000023 def test_autoseed(self):
24 self.gen.seed()
25 state1 = self.gen.getstate()
Raymond Hettinger3081d592003-08-09 18:30:57 +000026 time.sleep(0.1)
Mike53f7a7c2017-12-14 14:04:53 +030027 self.gen.seed() # different seeds at different times
Raymond Hettinger40f62172002-12-29 23:03:38 +000028 state2 = self.gen.getstate()
29 self.assertNotEqual(state1, state2)
Tim Peters46c04e12002-05-05 20:40:00 +000030
Raymond Hettinger40f62172002-12-29 23:03:38 +000031 def test_saverestore(self):
32 N = 1000
33 self.gen.seed()
34 state = self.gen.getstate()
35 randseq = self.randomlist(N)
36 self.gen.setstate(state) # should regenerate the same sequence
37 self.assertEqual(randseq, self.randomlist(N))
38
39 def test_seedargs(self):
Mark Dickinson95aeae02012-06-24 11:05:30 +010040 # Seed value with a negative hash.
41 class MySeed(object):
42 def __hash__(self):
43 return -1729
Xtreaka06d6832019-09-12 09:13:20 +010044 for arg in [None, 0, 1, -1, 10**20, -(10**20),
Victor Stinner00d7cd82020-03-10 15:15:14 +010045 False, True, 3.14, 'a']:
Raymond Hettinger40f62172002-12-29 23:03:38 +000046 self.gen.seed(arg)
Xtreaka06d6832019-09-12 09:13:20 +010047
48 for arg in [1+2j, tuple('abc'), MySeed()]:
49 with self.assertWarns(DeprecationWarning):
50 self.gen.seed(arg)
51
Guido van Rossum805365e2007-05-07 22:24:25 +000052 for arg in [list(range(3)), dict(one=1)]:
Xtreaka06d6832019-09-12 09:13:20 +010053 with self.assertWarns(DeprecationWarning):
54 self.assertRaises(TypeError, self.gen.seed, arg)
Raymond Hettingerf763a722010-09-07 00:38:15 +000055 self.assertRaises(TypeError, self.gen.seed, 1, 2, 3, 4)
Raymond Hettinger58335872004-07-09 14:26:18 +000056 self.assertRaises(TypeError, type(self.gen), [])
Raymond Hettinger40f62172002-12-29 23:03:38 +000057
R David Murraye3e1c172013-04-02 12:47:23 -040058 @unittest.mock.patch('random._urandom') # os.urandom
59 def test_seed_when_randomness_source_not_found(self, urandom_mock):
60 # Random.seed() uses time.time() when an operating system specific
csabellaf111fd22017-05-11 11:19:35 -040061 # randomness source is not found. To test this on machines where it
R David Murraye3e1c172013-04-02 12:47:23 -040062 # exists, run the above test, test_seedargs(), again after mocking
63 # os.urandom() so that it raises the exception expected when the
64 # randomness source is not available.
65 urandom_mock.side_effect = NotImplementedError
66 self.test_seedargs()
67
Antoine Pitrou5e394332012-11-04 02:10:33 +010068 def test_shuffle(self):
69 shuffle = self.gen.shuffle
70 lst = []
71 shuffle(lst)
72 self.assertEqual(lst, [])
73 lst = [37]
74 shuffle(lst)
75 self.assertEqual(lst, [37])
76 seqs = [list(range(n)) for n in range(10)]
77 shuffled_seqs = [list(range(n)) for n in range(10)]
78 for shuffled_seq in shuffled_seqs:
79 shuffle(shuffled_seq)
80 for (seq, shuffled_seq) in zip(seqs, shuffled_seqs):
81 self.assertEqual(len(seq), len(shuffled_seq))
82 self.assertEqual(set(seq), set(shuffled_seq))
Antoine Pitrou5e394332012-11-04 02:10:33 +010083 # The above tests all would pass if the shuffle was a
84 # no-op. The following non-deterministic test covers that. It
85 # asserts that the shuffled sequence of 1000 distinct elements
86 # must be different from the original one. Although there is
87 # mathematically a non-zero probability that this could
88 # actually happen in a genuinely random shuffle, it is
89 # completely negligible, given that the number of possible
90 # permutations of 1000 objects is 1000! (factorial of 1000),
91 # which is considerably larger than the number of atoms in the
92 # universe...
93 lst = list(range(1000))
94 shuffled_lst = list(range(1000))
95 shuffle(shuffled_lst)
96 self.assertTrue(lst != shuffled_lst)
97 shuffle(lst)
98 self.assertTrue(lst != shuffled_lst)
csabellaf111fd22017-05-11 11:19:35 -040099 self.assertRaises(TypeError, shuffle, (1, 2, 3))
100
101 def test_shuffle_random_argument(self):
102 # Test random argument to shuffle.
103 shuffle = self.gen.shuffle
104 mock_random = unittest.mock.Mock(return_value=0.5)
105 seq = bytearray(b'abcdefghijk')
106 shuffle(seq, mock_random)
107 mock_random.assert_called_with()
Antoine Pitrou5e394332012-11-04 02:10:33 +0100108
Raymond Hettingerdc4872e2010-09-07 10:06:56 +0000109 def test_choice(self):
110 choice = self.gen.choice
111 with self.assertRaises(IndexError):
112 choice([])
113 self.assertEqual(choice([50]), 50)
114 self.assertIn(choice([25, 75]), [25, 75])
115
Raymond Hettinger40f62172002-12-29 23:03:38 +0000116 def test_sample(self):
117 # For the entire allowable range of 0 <= k <= N, validate that
118 # the sample is of the correct length and contains only unique items
119 N = 100
Guido van Rossum805365e2007-05-07 22:24:25 +0000120 population = range(N)
121 for k in range(N+1):
Raymond Hettinger40f62172002-12-29 23:03:38 +0000122 s = self.gen.sample(population, k)
123 self.assertEqual(len(s), k)
Raymond Hettingera690a992003-11-16 16:17:49 +0000124 uniq = set(s)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000125 self.assertEqual(len(uniq), k)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000126 self.assertTrue(uniq <= set(population))
Raymond Hettinger8ec78812003-01-04 05:55:11 +0000127 self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0
R David Murraye3e1c172013-04-02 12:47:23 -0400128 # Exception raised if size of sample exceeds that of population
129 self.assertRaises(ValueError, self.gen.sample, population, N+1)
Raymond Hettingerbf871262016-11-21 14:34:33 -0800130 self.assertRaises(ValueError, self.gen.sample, [], -1)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000131
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000132 def test_sample_distribution(self):
133 # For the entire allowable range of 0 <= k <= N, validate that
134 # sample generates all possible permutations
135 n = 5
136 pop = range(n)
137 trials = 10000 # large num prevents false negatives without slowing normal case
Guido van Rossum805365e2007-05-07 22:24:25 +0000138 for k in range(n):
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +0000139 expected = factorial(n) // factorial(n-k)
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000140 perms = {}
Guido van Rossum805365e2007-05-07 22:24:25 +0000141 for i in range(trials):
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000142 perms[tuple(self.gen.sample(pop, k))] = None
143 if len(perms) == expected:
144 break
145 else:
146 self.fail()
147
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000148 def test_sample_inputs(self):
149 # SF bug #801342 -- population can be any iterable defining __len__()
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000150 self.gen.sample(range(20), 2)
Guido van Rossum805365e2007-05-07 22:24:25 +0000151 self.gen.sample(range(20), 2)
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000152 self.gen.sample(str('abcdefghijklmnopqrst'), 2)
153 self.gen.sample(tuple('abcdefghijklmnopqrst'), 2)
154
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000155 def test_sample_on_dicts(self):
Raymond Hettinger1acde192008-01-14 01:00:53 +0000156 self.assertRaises(TypeError, self.gen.sample, dict.fromkeys('abcdef'), 2)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000157
Raymond Hettinger4fe00202020-04-19 00:36:42 -0700158 def test_sample_on_sets(self):
159 with self.assertWarns(DeprecationWarning):
160 population = {10, 20, 30, 40, 50, 60, 70}
161 self.gen.sample(population, k=5)
162
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700163 def test_choices(self):
164 choices = self.gen.choices
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700165 data = ['red', 'green', 'blue', 'yellow']
166 str_data = 'abcd'
167 range_data = range(4)
168 set_data = set(range(4))
169
170 # basic functionality
171 for sample in [
Raymond Hettinger9016f282016-09-26 21:45:57 -0700172 choices(data, k=5),
173 choices(data, range(4), k=5),
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700174 choices(k=5, population=data, weights=range(4)),
175 choices(k=5, population=data, cum_weights=range(4)),
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700176 ]:
177 self.assertEqual(len(sample), 5)
178 self.assertEqual(type(sample), list)
179 self.assertTrue(set(sample) <= set(data))
180
181 # test argument handling
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700182 with self.assertRaises(TypeError): # missing arguments
183 choices(2)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700184
Raymond Hettinger9016f282016-09-26 21:45:57 -0700185 self.assertEqual(choices(data, k=0), []) # k == 0
186 self.assertEqual(choices(data, k=-1), []) # negative k behaves like ``[0] * -1``
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700187 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700188 choices(data, k=2.5) # k is a float
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700189
Raymond Hettinger9016f282016-09-26 21:45:57 -0700190 self.assertTrue(set(choices(str_data, k=5)) <= set(str_data)) # population is a string sequence
191 self.assertTrue(set(choices(range_data, k=5)) <= set(range_data)) # population is a range
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700192 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700193 choices(set_data, k=2) # population is not a sequence
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700194
Raymond Hettinger9016f282016-09-26 21:45:57 -0700195 self.assertTrue(set(choices(data, None, k=5)) <= set(data)) # weights is None
196 self.assertTrue(set(choices(data, weights=None, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700197 with self.assertRaises(ValueError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700198 choices(data, [1,2], k=5) # len(weights) != len(population)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700199 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700200 choices(data, 10, k=5) # non-iterable weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700201 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700202 choices(data, [None]*4, k=5) # non-numeric weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700203 for weights in [
204 [15, 10, 25, 30], # integer weights
205 [15.1, 10.2, 25.2, 30.3], # float weights
206 [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional weights
207 [True, False, True, False] # booleans (include / exclude)
208 ]:
Raymond Hettinger9016f282016-09-26 21:45:57 -0700209 self.assertTrue(set(choices(data, weights, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700210
211 with self.assertRaises(ValueError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700212 choices(data, cum_weights=[1,2], k=5) # len(weights) != len(population)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700213 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700214 choices(data, cum_weights=10, k=5) # non-iterable cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700215 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700216 choices(data, cum_weights=[None]*4, k=5) # non-numeric cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700217 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700218 choices(data, range(4), cum_weights=range(4), k=5) # both weights and cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700219 for weights in [
220 [15, 10, 25, 30], # integer cum_weights
221 [15.1, 10.2, 25.2, 30.3], # float cum_weights
222 [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional cum_weights
223 ]:
Raymond Hettinger9016f282016-09-26 21:45:57 -0700224 self.assertTrue(set(choices(data, cum_weights=weights, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700225
Raymond Hettinger7b166522016-10-14 01:19:38 -0400226 # Test weight focused on a single element of the population
227 self.assertEqual(choices('abcd', [1, 0, 0, 0]), ['a'])
228 self.assertEqual(choices('abcd', [0, 1, 0, 0]), ['b'])
229 self.assertEqual(choices('abcd', [0, 0, 1, 0]), ['c'])
230 self.assertEqual(choices('abcd', [0, 0, 0, 1]), ['d'])
231
232 # Test consistency with random.choice() for empty population
233 with self.assertRaises(IndexError):
234 choices([], k=1)
235 with self.assertRaises(IndexError):
236 choices([], weights=[], k=1)
237 with self.assertRaises(IndexError):
238 choices([], cum_weights=[], k=5)
239
Raymond Hettingerddf71712018-06-27 01:08:31 -0700240 def test_choices_subnormal(self):
Min ho Kim96e12d52019-07-22 06:12:33 +1000241 # Subnormal weights would occasionally trigger an IndexError
Raymond Hettingerddf71712018-06-27 01:08:31 -0700242 # in choices() when the value returned by random() was large
243 # enough to make `random() * total` round up to the total.
244 # See https://bugs.python.org/msg275594 for more detail.
245 choices = self.gen.choices
246 choices(population=[1, 2], weights=[1e-323, 1e-323], k=5000)
247
Raymond Hettinger041d8b42019-11-23 02:22:13 -0800248 def test_choices_with_all_zero_weights(self):
249 # See issue #38881
250 with self.assertRaises(ValueError):
251 self.gen.choices('AB', [0.0, 0.0])
252
Raymond Hettinger40f62172002-12-29 23:03:38 +0000253 def test_gauss(self):
254 # Ensure that the seed() method initializes all the hidden state. In
255 # particular, through 2.2.1 it failed to reset a piece of state used
256 # by (and only by) the .gauss() method.
257
258 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
259 self.gen.seed(seed)
260 x1 = self.gen.random()
261 y1 = self.gen.gauss(0, 1)
262
263 self.gen.seed(seed)
264 x2 = self.gen.random()
265 y2 = self.gen.gauss(0, 1)
266
267 self.assertEqual(x1, x2)
268 self.assertEqual(y1, y2)
269
Antoine Pitrou75a33782020-04-17 19:32:14 +0200270 def test_getrandbits(self):
271 # Verify ranges
272 for k in range(1, 1000):
273 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
274 self.assertEqual(self.gen.getrandbits(0), 0)
275
276 # Verify all bits active
277 getbits = self.gen.getrandbits
278 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
279 all_bits = 2**span-1
280 cum = 0
281 cpl_cum = 0
282 for i in range(100):
283 v = getbits(span)
284 cum |= v
285 cpl_cum |= all_bits ^ v
286 self.assertEqual(cum, all_bits)
287 self.assertEqual(cpl_cum, all_bits)
288
289 # Verify argument checking
290 self.assertRaises(TypeError, self.gen.getrandbits)
291 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
292 self.assertRaises(ValueError, self.gen.getrandbits, -1)
293 self.assertRaises(TypeError, self.gen.getrandbits, 10.1)
294
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000295 def test_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200296 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
297 state = pickle.dumps(self.gen, proto)
298 origseq = [self.gen.random() for i in range(10)]
299 newgen = pickle.loads(state)
300 restoredseq = [newgen.random() for i in range(10)]
301 self.assertEqual(origseq, restoredseq)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000302
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000303 def test_bug_1727780(self):
304 # verify that version-2-pickles can be loaded
305 # fine, whether they are created on 32-bit or 64-bit
306 # platforms, and that version-3-pickles load fine.
307 files = [("randv2_32.pck", 780),
308 ("randv2_64.pck", 866),
309 ("randv3.pck", 343)]
310 for file, value in files:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +0200311 with open(support.findfile(file),"rb") as f:
312 r = pickle.load(f)
Raymond Hettinger05156612010-09-07 04:44:52 +0000313 self.assertEqual(int(r.random()*1000), value)
314
315 def test_bug_9025(self):
316 # Had problem with an uneven distribution in int(n*random())
317 # Verify the fix by checking that distributions fall within expectations.
318 n = 100000
319 randrange = self.gen.randrange
320 k = sum(randrange(6755399441055744) % 3 == 2 for i in range(n))
321 self.assertTrue(0.30 < k/n < .37, (k/n))
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000322
Victor Stinner9f5fe792020-04-17 19:05:35 +0200323 def test_randbytes(self):
324 # Verify ranges
325 for n in range(1, 10):
326 data = self.gen.randbytes(n)
327 self.assertEqual(type(data), bytes)
328 self.assertEqual(len(data), n)
329
330 self.assertEqual(self.gen.randbytes(0), b'')
331
332 # Verify argument checking
333 self.assertRaises(TypeError, self.gen.randbytes)
334 self.assertRaises(TypeError, self.gen.randbytes, 1, 2)
335 self.assertRaises(ValueError, self.gen.randbytes, -1)
336 self.assertRaises(TypeError, self.gen.randbytes, 1.0)
337
338
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300339try:
340 random.SystemRandom().random()
341except NotImplementedError:
342 SystemRandom_available = False
343else:
344 SystemRandom_available = True
345
346@unittest.skipUnless(SystemRandom_available, "random.SystemRandom not available")
347class SystemRandom_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000348 gen = random.SystemRandom()
Raymond Hettinger356a4592004-08-30 06:14:31 +0000349
350 def test_autoseed(self):
351 # Doesn't need to do anything except not fail
352 self.gen.seed()
353
354 def test_saverestore(self):
355 self.assertRaises(NotImplementedError, self.gen.getstate)
356 self.assertRaises(NotImplementedError, self.gen.setstate, None)
357
358 def test_seedargs(self):
359 # Doesn't need to do anything except not fail
360 self.gen.seed(100)
361
Raymond Hettinger356a4592004-08-30 06:14:31 +0000362 def test_gauss(self):
363 self.gen.gauss_next = None
364 self.gen.seed(100)
365 self.assertEqual(self.gen.gauss_next, None)
366
367 def test_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200368 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
369 self.assertRaises(NotImplementedError, pickle.dumps, self.gen, proto)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000370
371 def test_53_bits_per_float(self):
372 # This should pass whenever a C double has 53 bit precision.
373 span = 2 ** 53
374 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000375 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000376 cum |= int(self.gen.random() * span)
377 self.assertEqual(cum, span-1)
378
379 def test_bigrand(self):
380 # The randrange routine should build-up the required number of bits
381 # in stages so that all bit positions are active.
382 span = 2 ** 500
383 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000384 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000385 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000386 self.assertTrue(0 <= r < span)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000387 cum |= r
388 self.assertEqual(cum, span-1)
389
390 def test_bigrand_ranges(self):
391 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600392 start = self.gen.randrange(2 ** (i-2))
393 stop = self.gen.randrange(2 ** i)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000394 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600395 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000396 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000397
398 def test_rangelimits(self):
399 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
400 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000401 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000402
R David Murraye3e1c172013-04-02 12:47:23 -0400403 def test_randrange_nonunit_step(self):
404 rint = self.gen.randrange(0, 10, 2)
405 self.assertIn(rint, (0, 2, 4, 6, 8))
406 rint = self.gen.randrange(0, 2, 2)
407 self.assertEqual(rint, 0)
408
409 def test_randrange_errors(self):
410 raises = partial(self.assertRaises, ValueError, self.gen.randrange)
411 # Empty range
412 raises(3, 3)
413 raises(-721)
414 raises(0, 100, -12)
415 # Non-integer start/stop
416 raises(3.14159)
417 raises(0, 2.71828)
418 # Zero and non-integer step
419 raises(0, 42, 0)
420 raises(0, 42, 3.14159)
421
Raymond Hettinger356a4592004-08-30 06:14:31 +0000422 def test_randbelow_logic(self, _log=log, int=int):
423 # check bitcount transition points: 2**i and 2**(i+1)-1
424 # show that: k = int(1.001 + _log(n, 2))
425 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000426 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000427 n = 1 << i # check an exact power of two
Raymond Hettinger356a4592004-08-30 06:14:31 +0000428 numbits = i+1
429 k = int(1.00001 + _log(n, 2))
430 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000431 self.assertEqual(n, 2**(k-1))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000432
433 n += n - 1 # check 1 below the next power of two
434 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000435 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000436 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000437
438 n -= n >> 15 # check a little farther below the next power of two
439 k = int(1.00001 + _log(n, 2))
440 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000441 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger356a4592004-08-30 06:14:31 +0000442
443
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300444class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger40f62172002-12-29 23:03:38 +0000445 gen = random.Random()
446
Raymond Hettingerf763a722010-09-07 00:38:15 +0000447 def test_guaranteed_stable(self):
448 # These sequences are guaranteed to stay the same across versions of python
449 self.gen.seed(3456147, version=1)
450 self.assertEqual([self.gen.random().hex() for i in range(4)],
451 ['0x1.ac362300d90d2p-1', '0x1.9d16f74365005p-1',
452 '0x1.1ebb4352e4c4dp-1', '0x1.1a7422abf9c11p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000453 self.gen.seed("the quick brown fox", version=2)
454 self.assertEqual([self.gen.random().hex() for i in range(4)],
Raymond Hettinger3fcf0022010-12-08 01:13:53 +0000455 ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4',
456 '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000457
Raymond Hettingerc7bab7c2016-08-31 15:01:08 -0700458 def test_bug_27706(self):
459 # Verify that version 1 seeds are unaffected by hash randomization
460
461 self.gen.seed('nofar', version=1) # hash('nofar') == 5990528763808513177
462 self.assertEqual([self.gen.random().hex() for i in range(4)],
463 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
464 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
465
466 self.gen.seed('rachel', version=1) # hash('rachel') == -9091735575445484789
467 self.assertEqual([self.gen.random().hex() for i in range(4)],
468 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
469 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
470
471 self.gen.seed('', version=1) # hash('') == 0
472 self.assertEqual([self.gen.random().hex() for i in range(4)],
473 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
474 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
475
Oren Milmand780b2d2017-09-28 10:50:01 +0300476 def test_bug_31478(self):
477 # There shouldn't be an assertion failure in _random.Random.seed() in
478 # case the argument has a bad __abs__() method.
479 class BadInt(int):
480 def __abs__(self):
481 return None
482 try:
483 self.gen.seed(BadInt())
484 except TypeError:
485 pass
486
Raymond Hettinger132a7d72017-09-17 09:04:30 -0700487 def test_bug_31482(self):
488 # Verify that version 1 seeds are unaffected by hash randomization
489 # when the seeds are expressed as bytes rather than strings.
490 # The hash(b) values listed are the Python2.7 hash() values
491 # which were used for seeding.
492
493 self.gen.seed(b'nofar', version=1) # hash('nofar') == 5990528763808513177
494 self.assertEqual([self.gen.random().hex() for i in range(4)],
495 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
496 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
497
498 self.gen.seed(b'rachel', version=1) # hash('rachel') == -9091735575445484789
499 self.assertEqual([self.gen.random().hex() for i in range(4)],
500 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
501 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
502
503 self.gen.seed(b'', version=1) # hash('') == 0
504 self.assertEqual([self.gen.random().hex() for i in range(4)],
505 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
506 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
507
508 b = b'\x00\x20\x40\x60\x80\xA0\xC0\xE0\xF0'
509 self.gen.seed(b, version=1) # hash(b) == 5015594239749365497
510 self.assertEqual([self.gen.random().hex() for i in range(4)],
511 ['0x1.52c2fde444d23p-1', '0x1.875174f0daea4p-2',
512 '0x1.9e9b2c50e5cd2p-1', '0x1.fa57768bd321cp-2'])
513
Raymond Hettinger58335872004-07-09 14:26:18 +0000514 def test_setstate_first_arg(self):
515 self.assertRaises(ValueError, self.gen.setstate, (1, None, None))
516
517 def test_setstate_middle_arg(self):
bladebryan9616a822017-04-21 23:10:46 -0700518 start_state = self.gen.getstate()
Raymond Hettinger58335872004-07-09 14:26:18 +0000519 # Wrong type, s/b tuple
520 self.assertRaises(TypeError, self.gen.setstate, (2, None, None))
521 # Wrong length, s/b 625
522 self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None))
523 # Wrong type, s/b tuple of 625 ints
524 self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None))
525 # Last element s/b an int also
526 self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None))
Serhiy Storchaka178f0b62015-07-24 09:02:53 +0300527 # Last element s/b between 0 and 624
528 with self.assertRaises((ValueError, OverflowError)):
529 self.gen.setstate((2, (1,)*624+(625,), None))
530 with self.assertRaises((ValueError, OverflowError)):
531 self.gen.setstate((2, (1,)*624+(-1,), None))
bladebryan9616a822017-04-21 23:10:46 -0700532 # Failed calls to setstate() should not have changed the state.
533 bits100 = self.gen.getrandbits(100)
534 self.gen.setstate(start_state)
535 self.assertEqual(self.gen.getrandbits(100), bits100)
Raymond Hettinger58335872004-07-09 14:26:18 +0000536
R David Murraye3e1c172013-04-02 12:47:23 -0400537 # Little trick to make "tuple(x % (2**32) for x in internalstate)"
538 # raise ValueError. I cannot think of a simple way to achieve this, so
539 # I am opting for using a generator as the middle argument of setstate
540 # which attempts to cast a NaN to integer.
541 state_values = self.gen.getstate()[1]
542 state_values = list(state_values)
543 state_values[-1] = float('nan')
544 state = (int(x) for x in state_values)
545 self.assertRaises(TypeError, self.gen.setstate, (2, state, None))
546
Raymond Hettinger40f62172002-12-29 23:03:38 +0000547 def test_referenceImplementation(self):
548 # Compare the python implementation with results from the original
549 # code. Create 2000 53-bit precision random floats. Compare only
550 # the last ten entries to show that the independent implementations
551 # are tracking. Here is the main() function needed to create the
552 # list of expected random numbers:
553 # void main(void){
554 # int i;
555 # unsigned long init[4]={61731, 24903, 614, 42143}, length=4;
556 # init_by_array(init, length);
557 # for (i=0; i<2000; i++) {
558 # printf("%.15f ", genrand_res53());
559 # if (i%5==4) printf("\n");
560 # }
561 # }
562 expected = [0.45839803073713259,
563 0.86057815201978782,
564 0.92848331726782152,
565 0.35932681119782461,
566 0.081823493762449573,
567 0.14332226470169329,
568 0.084297823823520024,
569 0.53814864671831453,
570 0.089215024911993401,
571 0.78486196105372907]
572
Guido van Rossume2a383d2007-01-15 16:59:06 +0000573 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000574 actual = self.randomlist(2000)[-10:]
575 for a, e in zip(actual, expected):
576 self.assertAlmostEqual(a,e,places=14)
577
578 def test_strong_reference_implementation(self):
579 # Like test_referenceImplementation, but checks for exact bit-level
580 # equality. This should pass on any box where C double contains
581 # at least 53 bits of precision (the underlying algorithm suffers
582 # no rounding errors -- all results are exact).
583 from math import ldexp
584
Guido van Rossume2a383d2007-01-15 16:59:06 +0000585 expected = [0x0eab3258d2231f,
586 0x1b89db315277a5,
587 0x1db622a5518016,
588 0x0b7f9af0d575bf,
589 0x029e4c4db82240,
590 0x04961892f5d673,
591 0x02b291598e4589,
592 0x11388382c15694,
593 0x02dad977c9e1fe,
594 0x191d96d4d334c6]
595 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000596 actual = self.randomlist(2000)[-10:]
597 for a, e in zip(actual, expected):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000598 self.assertEqual(int(ldexp(a, 53)), e)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000599
600 def test_long_seed(self):
601 # This is most interesting to run in debug mode, just to make sure
602 # nothing blows up. Under the covers, a dynamically resized array
603 # is allocated, consuming space proportional to the number of bits
604 # in the seed. Unfortunately, that's a quadratic-time algorithm,
605 # so don't make this horribly big.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000606 seed = (1 << (10000 * 8)) - 1 # about 10K bytes
Raymond Hettinger40f62172002-12-29 23:03:38 +0000607 self.gen.seed(seed)
608
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000609 def test_53_bits_per_float(self):
610 # This should pass whenever a C double has 53 bit precision.
611 span = 2 ** 53
612 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000613 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000614 cum |= int(self.gen.random() * span)
615 self.assertEqual(cum, span-1)
616
617 def test_bigrand(self):
618 # The randrange routine should build-up the required number of bits
619 # in stages so that all bit positions are active.
620 span = 2 ** 500
621 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000622 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000623 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000624 self.assertTrue(0 <= r < span)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000625 cum |= r
626 self.assertEqual(cum, span-1)
627
628 def test_bigrand_ranges(self):
629 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600630 start = self.gen.randrange(2 ** (i-2))
631 stop = self.gen.randrange(2 ** i)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000632 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600633 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000634 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000635
636 def test_rangelimits(self):
637 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
Raymond Hettingera690a992003-11-16 16:17:49 +0000638 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000639 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000640
Antoine Pitrou75a33782020-04-17 19:32:14 +0200641 def test_getrandbits(self):
642 super().test_getrandbits()
643
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000644 # Verify cross-platform repeatability
645 self.gen.seed(1234567)
646 self.assertEqual(self.gen.getrandbits(100),
Guido van Rossume2a383d2007-01-15 16:59:06 +0000647 97904845777343510404718956115)
Raymond Hettinger58335872004-07-09 14:26:18 +0000648
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200649 def test_randrange_uses_getrandbits(self):
650 # Verify use of getrandbits by randrange
651 # Use same seed as in the cross-platform repeatability test
Antoine Pitrou75a33782020-04-17 19:32:14 +0200652 # in test_getrandbits above.
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200653 self.gen.seed(1234567)
654 # If randrange uses getrandbits, it should pick getrandbits(100)
655 # when called with a 100-bits stop argument.
656 self.assertEqual(self.gen.randrange(2**99),
657 97904845777343510404718956115)
658
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000659 def test_randbelow_logic(self, _log=log, int=int):
660 # check bitcount transition points: 2**i and 2**(i+1)-1
661 # show that: k = int(1.001 + _log(n, 2))
662 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000663 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000664 n = 1 << i # check an exact power of two
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000665 numbits = i+1
666 k = int(1.00001 + _log(n, 2))
667 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000668 self.assertEqual(n, 2**(k-1))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000669
670 n += n - 1 # check 1 below the next power of two
671 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000672 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000673 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000674
675 n -= n >> 15 # check a little farther below the next power of two
676 k = int(1.00001 + _log(n, 2))
677 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000678 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000679
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200680 def test_randbelow_without_getrandbits(self):
R David Murraye3e1c172013-04-02 12:47:23 -0400681 # Random._randbelow() can only use random() when the built-in one
682 # has been overridden but no new getrandbits() method was supplied.
R David Murraye3e1c172013-04-02 12:47:23 -0400683 maxsize = 1<<random.BPF
684 with warnings.catch_warnings():
685 warnings.simplefilter("ignore", UserWarning)
686 # Population range too large (n >= maxsize)
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200687 self.gen._randbelow_without_getrandbits(
688 maxsize+1, maxsize=maxsize
689 )
690 self.gen._randbelow_without_getrandbits(5640, maxsize=maxsize)
Raymond Hettinger4168f1e2020-05-01 10:34:19 -0700691 # issue 33203: test that _randbelow returns zero on
Wolfgang Maier091e95e2018-04-05 17:19:44 +0200692 # n == 0 also in its getrandbits-independent branch.
Raymond Hettinger4168f1e2020-05-01 10:34:19 -0700693 x = self.gen._randbelow_without_getrandbits(0, maxsize=maxsize)
694 self.assertEqual(x, 0)
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200695
R David Murraye3e1c172013-04-02 12:47:23 -0400696 # This might be going too far to test a single line, but because of our
697 # noble aim of achieving 100% test coverage we need to write a case in
698 # which the following line in Random._randbelow() gets executed:
699 #
700 # rem = maxsize % n
701 # limit = (maxsize - rem) / maxsize
702 # r = random()
703 # while r >= limit:
704 # r = random() # <== *This line* <==<
705 #
706 # Therefore, to guarantee that the while loop is executed at least
707 # once, we need to mock random() so that it returns a number greater
708 # than 'limit' the first time it gets called.
709
710 n = 42
711 epsilon = 0.01
712 limit = (maxsize - (maxsize % n)) / maxsize
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200713 with unittest.mock.patch.object(random.Random, 'random') as random_mock:
714 random_mock.side_effect = [limit + epsilon, limit - epsilon]
715 self.gen._randbelow_without_getrandbits(n, maxsize=maxsize)
716 self.assertEqual(random_mock.call_count, 2)
R David Murraye3e1c172013-04-02 12:47:23 -0400717
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000718 def test_randrange_bug_1590891(self):
719 start = 1000000000000
720 stop = -100000000000000000000
721 step = -200
722 x = self.gen.randrange(start, stop, step)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000723 self.assertTrue(stop < x <= start)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000724 self.assertEqual((x+stop)%step, 0)
725
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700726 def test_choices_algorithms(self):
Raymond Hettinger24e42392016-11-13 00:42:56 -0500727 # The various ways of specifying weights should produce the same results
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700728 choices = self.gen.choices
Raymond Hettinger6023d332016-11-21 15:32:08 -0800729 n = 104729
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700730
731 self.gen.seed(8675309)
732 a = self.gen.choices(range(n), k=10000)
733
734 self.gen.seed(8675309)
735 b = self.gen.choices(range(n), [1]*n, k=10000)
736 self.assertEqual(a, b)
737
738 self.gen.seed(8675309)
739 c = self.gen.choices(range(n), cum_weights=range(1, n+1), k=10000)
740 self.assertEqual(a, c)
741
penguindustin96466302019-05-06 14:57:17 -0400742 # American Roulette
Raymond Hettinger77d574d2016-10-29 17:42:36 -0700743 population = ['Red', 'Black', 'Green']
744 weights = [18, 18, 2]
745 cum_weights = [18, 36, 38]
746 expanded_population = ['Red'] * 18 + ['Black'] * 18 + ['Green'] * 2
747
748 self.gen.seed(9035768)
749 a = self.gen.choices(expanded_population, k=10000)
750
751 self.gen.seed(9035768)
752 b = self.gen.choices(population, weights, k=10000)
753 self.assertEqual(a, b)
754
755 self.gen.seed(9035768)
756 c = self.gen.choices(population, cum_weights=cum_weights, k=10000)
757 self.assertEqual(a, c)
758
Victor Stinner9f5fe792020-04-17 19:05:35 +0200759 def test_randbytes(self):
760 super().test_randbytes()
761
762 # Mersenne Twister randbytes() is deterministic
763 # and does not depend on the endian and bitness.
764 seed = 8675309
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300765 expected = b'3\xa8\xf9f\xf4\xa4\xd06\x19\x8f\x9f\x82\x02oe\xf0'
Victor Stinner9f5fe792020-04-17 19:05:35 +0200766
767 self.gen.seed(seed)
768 self.assertEqual(self.gen.randbytes(16), expected)
769
770 # randbytes(0) must not consume any entropy
771 self.gen.seed(seed)
772 self.assertEqual(self.gen.randbytes(0), b'')
773 self.assertEqual(self.gen.randbytes(16), expected)
774
775 # Four randbytes(4) calls give the same output than randbytes(16)
776 self.gen.seed(seed)
777 self.assertEqual(b''.join([self.gen.randbytes(4) for _ in range(4)]),
778 expected)
779
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300780 # Each randbytes(1), randbytes(2) or randbytes(3) call consumes
781 # 4 bytes of entropy
Victor Stinner9f5fe792020-04-17 19:05:35 +0200782 self.gen.seed(seed)
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300783 expected1 = expected[3::4]
784 self.assertEqual(b''.join(self.gen.randbytes(1) for _ in range(4)),
785 expected1)
786
787 self.gen.seed(seed)
788 expected2 = b''.join(expected[i + 2: i + 4]
Victor Stinner9f5fe792020-04-17 19:05:35 +0200789 for i in range(0, len(expected), 4))
790 self.assertEqual(b''.join(self.gen.randbytes(2) for _ in range(4)),
791 expected2)
792
793 self.gen.seed(seed)
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300794 expected3 = b''.join(expected[i + 1: i + 4]
Victor Stinner9f5fe792020-04-17 19:05:35 +0200795 for i in range(0, len(expected), 4))
796 self.assertEqual(b''.join(self.gen.randbytes(3) for _ in range(4)),
797 expected3)
798
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300799 def test_randbytes_getrandbits(self):
800 # There is a simple relation between randbytes() and getrandbits()
801 seed = 2849427419
802 gen2 = random.Random()
803 self.gen.seed(seed)
804 gen2.seed(seed)
805 for n in range(9):
806 self.assertEqual(self.gen.randbytes(n),
807 gen2.getrandbits(n * 8).to_bytes(n, 'little'))
808
Victor Stinner9f5fe792020-04-17 19:05:35 +0200809
Raymond Hettinger2d0c2562009-02-19 09:53:18 +0000810def gamma(z, sqrt2pi=(2.0*pi)**0.5):
811 # Reflection to right half of complex plane
812 if z < 0.5:
813 return pi / sin(pi*z) / gamma(1.0-z)
814 # Lanczos approximation with g=7
815 az = z + (7.0 - 0.5)
816 return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
817 0.9999999999995183,
818 676.5203681218835 / z,
819 -1259.139216722289 / (z+1.0),
820 771.3234287757674 / (z+2.0),
821 -176.6150291498386 / (z+3.0),
822 12.50734324009056 / (z+4.0),
823 -0.1385710331296526 / (z+5.0),
824 0.9934937113930748e-05 / (z+6.0),
825 0.1659470187408462e-06 / (z+7.0),
826 ])
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000827
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000828class TestDistributions(unittest.TestCase):
829 def test_zeroinputs(self):
830 # Verify that distributions can handle a series of zero inputs'
831 g = random.Random()
Guido van Rossum805365e2007-05-07 22:24:25 +0000832 x = [g.random() for i in range(50)] + [0.0]*5
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000833 g.random = x[:].pop; g.uniform(1,10)
834 g.random = x[:].pop; g.paretovariate(1.0)
835 g.random = x[:].pop; g.expovariate(1.0)
836 g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200837 g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000838 g.random = x[:].pop; g.normalvariate(0.0, 1.0)
839 g.random = x[:].pop; g.gauss(0.0, 1.0)
840 g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
841 g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
842 g.random = x[:].pop; g.gammavariate(0.01, 1.0)
843 g.random = x[:].pop; g.gammavariate(1.0, 1.0)
844 g.random = x[:].pop; g.gammavariate(200.0, 1.0)
845 g.random = x[:].pop; g.betavariate(3.0, 3.0)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000846 g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000847
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000848 def test_avg_std(self):
849 # Use integration to test distribution average and standard deviation.
850 # Only works for distributions which do not consume variates in pairs
851 g = random.Random()
852 N = 5000
Guido van Rossum805365e2007-05-07 22:24:25 +0000853 x = [i/float(N) for i in range(1,N)]
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000854 for variate, args, mu, sigmasqrd in [
855 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
Christian Heimesfe337bf2008-03-23 21:54:12 +0000856 (g.triangular, (0.0, 1.0, 1.0/3.0), 4.0/9.0, 7.0/9.0/18.0),
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000857 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200858 (g.vonmisesvariate, (1.23, 0), pi, pi**2/3),
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000859 (g.paretovariate, (5.0,), 5.0/(5.0-1),
860 5.0/((5.0-1)**2*(5.0-2))),
861 (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0),
862 gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
863 g.random = x[:].pop
864 y = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000865 for i in range(len(x)):
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000866 try:
867 y.append(variate(*args))
868 except IndexError:
869 pass
870 s1 = s2 = 0
871 for e in y:
872 s1 += e
873 s2 += (e - mu) ** 2
874 N = len(y)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200875 self.assertAlmostEqual(s1/N, mu, places=2,
876 msg='%s%r' % (variate.__name__, args))
877 self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2,
878 msg='%s%r' % (variate.__name__, args))
879
880 def test_constant(self):
881 g = random.Random()
882 N = 100
883 for variate, args, expected in [
884 (g.uniform, (10.0, 10.0), 10.0),
885 (g.triangular, (10.0, 10.0), 10.0),
Raymond Hettinger978c6ab2014-05-25 17:25:27 -0700886 (g.triangular, (10.0, 10.0, 10.0), 10.0),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200887 (g.expovariate, (float('inf'),), 0.0),
888 (g.vonmisesvariate, (3.0, float('inf')), 3.0),
889 (g.gauss, (10.0, 0.0), 10.0),
890 (g.lognormvariate, (0.0, 0.0), 1.0),
891 (g.lognormvariate, (-float('inf'), 0.0), 0.0),
892 (g.normalvariate, (10.0, 0.0), 10.0),
893 (g.paretovariate, (float('inf'),), 1.0),
894 (g.weibullvariate, (10.0, float('inf')), 10.0),
895 (g.weibullvariate, (0.0, 10.0), 0.0),
896 ]:
897 for i in range(N):
898 self.assertEqual(variate(*args), expected)
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000899
Mark Dickinsonbe5f9192013-02-10 14:16:10 +0000900 def test_von_mises_range(self):
901 # Issue 17149: von mises variates were not consistently in the
902 # range [0, 2*PI].
903 g = random.Random()
904 N = 100
905 for mu in 0.0, 0.1, 3.1, 6.2:
906 for kappa in 0.0, 2.3, 500.0:
907 for _ in range(N):
908 sample = g.vonmisesvariate(mu, kappa)
909 self.assertTrue(
910 0 <= sample <= random.TWOPI,
911 msg=("vonmisesvariate({}, {}) produced a result {} out"
912 " of range [0, 2*pi]").format(mu, kappa, sample))
913
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200914 def test_von_mises_large_kappa(self):
915 # Issue #17141: vonmisesvariate() was hang for large kappas
916 random.vonmisesvariate(0, 1e15)
917 random.vonmisesvariate(0, 1e100)
918
R David Murraye3e1c172013-04-02 12:47:23 -0400919 def test_gammavariate_errors(self):
920 # Both alpha and beta must be > 0.0
921 self.assertRaises(ValueError, random.gammavariate, -1, 3)
922 self.assertRaises(ValueError, random.gammavariate, 0, 2)
923 self.assertRaises(ValueError, random.gammavariate, 2, 0)
924 self.assertRaises(ValueError, random.gammavariate, 1, -3)
925
leodema63d15222018-12-24 07:54:25 +0100926 # There are three different possibilities in the current implementation
927 # of random.gammavariate(), depending on the value of 'alpha'. What we
928 # are going to do here is to fix the values returned by random() to
929 # generate test cases that provide 100% line coverage of the method.
R David Murraye3e1c172013-04-02 12:47:23 -0400930 @unittest.mock.patch('random.Random.random')
leodema63d15222018-12-24 07:54:25 +0100931 def test_gammavariate_alpha_greater_one(self, random_mock):
R David Murraye3e1c172013-04-02 12:47:23 -0400932
leodema63d15222018-12-24 07:54:25 +0100933 # #1: alpha > 1.0.
934 # We want the first random number to be outside the
R David Murraye3e1c172013-04-02 12:47:23 -0400935 # [1e-7, .9999999] range, so that the continue statement executes
936 # once. The values of u1 and u2 will be 0.5 and 0.3, respectively.
937 random_mock.side_effect = [1e-8, 0.5, 0.3]
938 returned_value = random.gammavariate(1.1, 2.3)
939 self.assertAlmostEqual(returned_value, 2.53)
940
leodema63d15222018-12-24 07:54:25 +0100941 @unittest.mock.patch('random.Random.random')
942 def test_gammavariate_alpha_equal_one(self, random_mock):
R David Murraye3e1c172013-04-02 12:47:23 -0400943
leodema63d15222018-12-24 07:54:25 +0100944 # #2.a: alpha == 1.
945 # The execution body of the while loop executes once.
946 # Then random.random() returns 0.45,
947 # which causes while to stop looping and the algorithm to terminate.
948 random_mock.side_effect = [0.45]
949 returned_value = random.gammavariate(1.0, 3.14)
950 self.assertAlmostEqual(returned_value, 1.877208182372648)
951
952 @unittest.mock.patch('random.Random.random')
953 def test_gammavariate_alpha_equal_one_equals_expovariate(self, random_mock):
954
955 # #2.b: alpha == 1.
956 # It must be equivalent of calling expovariate(1.0 / beta).
957 beta = 3.14
958 random_mock.side_effect = [1e-8, 1e-8]
959 gammavariate_returned_value = random.gammavariate(1.0, beta)
960 expovariate_returned_value = random.expovariate(1.0 / beta)
961 self.assertAlmostEqual(gammavariate_returned_value, expovariate_returned_value)
962
963 @unittest.mock.patch('random.Random.random')
964 def test_gammavariate_alpha_between_zero_and_one(self, random_mock):
965
966 # #3: 0 < alpha < 1.
967 # This is the most complex region of code to cover,
R David Murraye3e1c172013-04-02 12:47:23 -0400968 # as there are multiple if-else statements. Let's take a look at the
969 # source code, and determine the values that we need accordingly:
970 #
971 # while 1:
972 # u = random()
973 # b = (_e + alpha)/_e
974 # p = b*u
975 # if p <= 1.0: # <=== (A)
976 # x = p ** (1.0/alpha)
977 # else: # <=== (B)
978 # x = -_log((b-p)/alpha)
979 # u1 = random()
980 # if p > 1.0: # <=== (C)
981 # if u1 <= x ** (alpha - 1.0): # <=== (D)
982 # break
983 # elif u1 <= _exp(-x): # <=== (E)
984 # break
985 # return x * beta
986 #
987 # First, we want (A) to be True. For that we need that:
988 # b*random() <= 1.0
989 # r1 = random() <= 1.0 / b
990 #
991 # We now get to the second if-else branch, and here, since p <= 1.0,
992 # (C) is False and we take the elif branch, (E). For it to be True,
993 # so that the break is executed, we need that:
994 # r2 = random() <= _exp(-x)
995 # r2 <= _exp(-(p ** (1.0/alpha)))
996 # r2 <= _exp(-((b*r1) ** (1.0/alpha)))
997
998 _e = random._e
999 _exp = random._exp
1000 _log = random._log
1001 alpha = 0.35
1002 beta = 1.45
1003 b = (_e + alpha)/_e
1004 epsilon = 0.01
1005
1006 r1 = 0.8859296441566 # 1.0 / b
1007 r2 = 0.3678794411714 # _exp(-((b*r1) ** (1.0/alpha)))
1008
1009 # These four "random" values result in the following trace:
1010 # (A) True, (E) False --> [next iteration of while]
1011 # (A) True, (E) True --> [while loop breaks]
1012 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
1013 returned_value = random.gammavariate(alpha, beta)
1014 self.assertAlmostEqual(returned_value, 1.4499999999997544)
1015
1016 # Let's now make (A) be False. If this is the case, when we get to the
1017 # second if-else 'p' is greater than 1, so (C) evaluates to True. We
1018 # now encounter a second if statement, (D), which in order to execute
1019 # must satisfy the following condition:
1020 # r2 <= x ** (alpha - 1.0)
1021 # r2 <= (-_log((b-p)/alpha)) ** (alpha - 1.0)
1022 # r2 <= (-_log((b-(b*r1))/alpha)) ** (alpha - 1.0)
1023 r1 = 0.8959296441566 # (1.0 / b) + epsilon -- so that (A) is False
1024 r2 = 0.9445400408898141
1025
1026 # And these four values result in the following trace:
1027 # (B) and (C) True, (D) False --> [next iteration of while]
1028 # (B) and (C) True, (D) True [while loop breaks]
1029 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
1030 returned_value = random.gammavariate(alpha, beta)
1031 self.assertAlmostEqual(returned_value, 1.5830349561760781)
1032
1033 @unittest.mock.patch('random.Random.gammavariate')
1034 def test_betavariate_return_zero(self, gammavariate_mock):
1035 # betavariate() returns zero when the Gamma distribution
1036 # that it uses internally returns this same value.
1037 gammavariate_mock.return_value = 0.0
1038 self.assertEqual(0.0, random.betavariate(2.71828, 3.14159))
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +02001039
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001040
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001041class TestRandomSubclassing(unittest.TestCase):
1042 def test_random_subclass_with_kwargs(self):
1043 # SF bug #1486663 -- this used to erroneously raise a TypeError
1044 class Subclass(random.Random):
1045 def __init__(self, newarg=None):
1046 random.Random.__init__(self)
1047 Subclass(newarg=1)
1048
1049 def test_subclasses_overriding_methods(self):
1050 # Subclasses with an overridden random, but only the original
1051 # getrandbits method should not rely on getrandbits in for randrange,
1052 # but should use a getrandbits-independent implementation instead.
1053
1054 # subclass providing its own random **and** getrandbits methods
1055 # like random.SystemRandom does => keep relying on getrandbits for
1056 # randrange
1057 class SubClass1(random.Random):
1058 def random(self):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001059 called.add('SubClass1.random')
1060 return random.Random.random(self)
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001061
1062 def getrandbits(self, n):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001063 called.add('SubClass1.getrandbits')
1064 return random.Random.getrandbits(self, n)
1065 called = set()
1066 SubClass1().randrange(42)
1067 self.assertEqual(called, {'SubClass1.getrandbits'})
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001068
1069 # subclass providing only random => can only use random for randrange
1070 class SubClass2(random.Random):
1071 def random(self):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001072 called.add('SubClass2.random')
1073 return random.Random.random(self)
1074 called = set()
1075 SubClass2().randrange(42)
1076 self.assertEqual(called, {'SubClass2.random'})
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001077
1078 # subclass defining getrandbits to complement its inherited random
1079 # => can now rely on getrandbits for randrange again
1080 class SubClass3(SubClass2):
1081 def getrandbits(self, n):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001082 called.add('SubClass3.getrandbits')
1083 return random.Random.getrandbits(self, n)
1084 called = set()
1085 SubClass3().randrange(42)
1086 self.assertEqual(called, {'SubClass3.getrandbits'})
1087
1088 # subclass providing only random and inherited getrandbits
1089 # => random takes precedence
1090 class SubClass4(SubClass3):
1091 def random(self):
1092 called.add('SubClass4.random')
1093 return random.Random.random(self)
1094 called = set()
1095 SubClass4().randrange(42)
1096 self.assertEqual(called, {'SubClass4.random'})
1097
1098 # Following subclasses don't define random or getrandbits directly,
1099 # but inherit them from classes which are not subclasses of Random
1100 class Mixin1:
1101 def random(self):
1102 called.add('Mixin1.random')
1103 return random.Random.random(self)
1104 class Mixin2:
1105 def getrandbits(self, n):
1106 called.add('Mixin2.getrandbits')
1107 return random.Random.getrandbits(self, n)
1108
1109 class SubClass5(Mixin1, random.Random):
1110 pass
1111 called = set()
1112 SubClass5().randrange(42)
1113 self.assertEqual(called, {'Mixin1.random'})
1114
1115 class SubClass6(Mixin2, random.Random):
1116 pass
1117 called = set()
1118 SubClass6().randrange(42)
1119 self.assertEqual(called, {'Mixin2.getrandbits'})
1120
1121 class SubClass7(Mixin1, Mixin2, random.Random):
1122 pass
1123 called = set()
1124 SubClass7().randrange(42)
1125 self.assertEqual(called, {'Mixin1.random'})
1126
1127 class SubClass8(Mixin2, Mixin1, random.Random):
1128 pass
1129 called = set()
1130 SubClass8().randrange(42)
1131 self.assertEqual(called, {'Mixin2.getrandbits'})
1132
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001133
Raymond Hettinger40f62172002-12-29 23:03:38 +00001134class TestModule(unittest.TestCase):
1135 def testMagicConstants(self):
1136 self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141)
1137 self.assertAlmostEqual(random.TWOPI, 6.28318530718)
1138 self.assertAlmostEqual(random.LOG4, 1.38629436111989)
1139 self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627)
1140
1141 def test__all__(self):
1142 # tests validity but not completeness of the __all__ list
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001143 self.assertTrue(set(random.__all__) <= set(dir(random)))
Raymond Hettinger40f62172002-12-29 23:03:38 +00001144
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001145 @unittest.skipUnless(hasattr(os, "fork"), "fork() required")
1146 def test_after_fork(self):
1147 # Test the global Random instance gets reseeded in child
1148 r, w = os.pipe()
Victor Stinnerda5e9302017-08-09 17:59:05 +02001149 pid = os.fork()
1150 if pid == 0:
1151 # child process
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001152 try:
1153 val = random.getrandbits(128)
1154 with open(w, "w") as f:
1155 f.write(str(val))
1156 finally:
1157 os._exit(0)
1158 else:
Victor Stinnerda5e9302017-08-09 17:59:05 +02001159 # parent process
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001160 os.close(w)
1161 val = random.getrandbits(128)
1162 with open(r, "r") as f:
1163 child_val = eval(f.read())
1164 self.assertNotEqual(val, child_val)
1165
Victor Stinner278c1e12020-03-31 20:08:12 +02001166 support.wait_process(pid, exitcode=0)
Victor Stinnerda5e9302017-08-09 17:59:05 +02001167
Thomas Woutersb2137042007-02-01 18:02:27 +00001168
Raymond Hettinger40f62172002-12-29 23:03:38 +00001169if __name__ == "__main__":
Ezio Melotti3e4a98b2013-04-19 05:45:27 +03001170 unittest.main()