blob: 50d4e94ca22f8965bc677106f273b1316a9b32d4 [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 Hettingera690a992003-11-16 16:17:49 +0000150 self.gen.sample(set(range(20)), 2)
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000151 self.gen.sample(range(20), 2)
Guido van Rossum805365e2007-05-07 22:24:25 +0000152 self.gen.sample(range(20), 2)
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000153 self.gen.sample(str('abcdefghijklmnopqrst'), 2)
154 self.gen.sample(tuple('abcdefghijklmnopqrst'), 2)
155
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000156 def test_sample_on_dicts(self):
Raymond Hettinger1acde192008-01-14 01:00:53 +0000157 self.assertRaises(TypeError, self.gen.sample, dict.fromkeys('abcdef'), 2)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000158
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700159 def test_choices(self):
160 choices = self.gen.choices
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700161 data = ['red', 'green', 'blue', 'yellow']
162 str_data = 'abcd'
163 range_data = range(4)
164 set_data = set(range(4))
165
166 # basic functionality
167 for sample in [
Raymond Hettinger9016f282016-09-26 21:45:57 -0700168 choices(data, k=5),
169 choices(data, range(4), k=5),
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700170 choices(k=5, population=data, weights=range(4)),
171 choices(k=5, population=data, cum_weights=range(4)),
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700172 ]:
173 self.assertEqual(len(sample), 5)
174 self.assertEqual(type(sample), list)
175 self.assertTrue(set(sample) <= set(data))
176
177 # test argument handling
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700178 with self.assertRaises(TypeError): # missing arguments
179 choices(2)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700180
Raymond Hettinger9016f282016-09-26 21:45:57 -0700181 self.assertEqual(choices(data, k=0), []) # k == 0
182 self.assertEqual(choices(data, k=-1), []) # negative k behaves like ``[0] * -1``
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700183 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700184 choices(data, k=2.5) # k is a float
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700185
Raymond Hettinger9016f282016-09-26 21:45:57 -0700186 self.assertTrue(set(choices(str_data, k=5)) <= set(str_data)) # population is a string sequence
187 self.assertTrue(set(choices(range_data, k=5)) <= set(range_data)) # population is a range
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700188 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700189 choices(set_data, k=2) # population is not a sequence
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700190
Raymond Hettinger9016f282016-09-26 21:45:57 -0700191 self.assertTrue(set(choices(data, None, k=5)) <= set(data)) # weights is None
192 self.assertTrue(set(choices(data, weights=None, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700193 with self.assertRaises(ValueError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700194 choices(data, [1,2], k=5) # len(weights) != len(population)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700195 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700196 choices(data, 10, k=5) # non-iterable weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700197 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700198 choices(data, [None]*4, k=5) # non-numeric weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700199 for weights in [
200 [15, 10, 25, 30], # integer weights
201 [15.1, 10.2, 25.2, 30.3], # float weights
202 [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional weights
203 [True, False, True, False] # booleans (include / exclude)
204 ]:
Raymond Hettinger9016f282016-09-26 21:45:57 -0700205 self.assertTrue(set(choices(data, weights, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700206
207 with self.assertRaises(ValueError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700208 choices(data, cum_weights=[1,2], k=5) # len(weights) != len(population)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700209 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700210 choices(data, cum_weights=10, k=5) # non-iterable cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700211 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700212 choices(data, cum_weights=[None]*4, k=5) # non-numeric cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700213 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700214 choices(data, range(4), cum_weights=range(4), k=5) # both weights and cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700215 for weights in [
216 [15, 10, 25, 30], # integer cum_weights
217 [15.1, 10.2, 25.2, 30.3], # float cum_weights
218 [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional cum_weights
219 ]:
Raymond Hettinger9016f282016-09-26 21:45:57 -0700220 self.assertTrue(set(choices(data, cum_weights=weights, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700221
Raymond Hettinger7b166522016-10-14 01:19:38 -0400222 # Test weight focused on a single element of the population
223 self.assertEqual(choices('abcd', [1, 0, 0, 0]), ['a'])
224 self.assertEqual(choices('abcd', [0, 1, 0, 0]), ['b'])
225 self.assertEqual(choices('abcd', [0, 0, 1, 0]), ['c'])
226 self.assertEqual(choices('abcd', [0, 0, 0, 1]), ['d'])
227
228 # Test consistency with random.choice() for empty population
229 with self.assertRaises(IndexError):
230 choices([], k=1)
231 with self.assertRaises(IndexError):
232 choices([], weights=[], k=1)
233 with self.assertRaises(IndexError):
234 choices([], cum_weights=[], k=5)
235
Raymond Hettingerddf71712018-06-27 01:08:31 -0700236 def test_choices_subnormal(self):
Min ho Kim96e12d52019-07-22 06:12:33 +1000237 # Subnormal weights would occasionally trigger an IndexError
Raymond Hettingerddf71712018-06-27 01:08:31 -0700238 # in choices() when the value returned by random() was large
239 # enough to make `random() * total` round up to the total.
240 # See https://bugs.python.org/msg275594 for more detail.
241 choices = self.gen.choices
242 choices(population=[1, 2], weights=[1e-323, 1e-323], k=5000)
243
Raymond Hettinger041d8b42019-11-23 02:22:13 -0800244 def test_choices_with_all_zero_weights(self):
245 # See issue #38881
246 with self.assertRaises(ValueError):
247 self.gen.choices('AB', [0.0, 0.0])
248
Raymond Hettinger40f62172002-12-29 23:03:38 +0000249 def test_gauss(self):
250 # Ensure that the seed() method initializes all the hidden state. In
251 # particular, through 2.2.1 it failed to reset a piece of state used
252 # by (and only by) the .gauss() method.
253
254 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
255 self.gen.seed(seed)
256 x1 = self.gen.random()
257 y1 = self.gen.gauss(0, 1)
258
259 self.gen.seed(seed)
260 x2 = self.gen.random()
261 y2 = self.gen.gauss(0, 1)
262
263 self.assertEqual(x1, x2)
264 self.assertEqual(y1, y2)
265
Antoine Pitrou75a33782020-04-17 19:32:14 +0200266 def test_getrandbits(self):
267 # Verify ranges
268 for k in range(1, 1000):
269 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
270 self.assertEqual(self.gen.getrandbits(0), 0)
271
272 # Verify all bits active
273 getbits = self.gen.getrandbits
274 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
275 all_bits = 2**span-1
276 cum = 0
277 cpl_cum = 0
278 for i in range(100):
279 v = getbits(span)
280 cum |= v
281 cpl_cum |= all_bits ^ v
282 self.assertEqual(cum, all_bits)
283 self.assertEqual(cpl_cum, all_bits)
284
285 # Verify argument checking
286 self.assertRaises(TypeError, self.gen.getrandbits)
287 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
288 self.assertRaises(ValueError, self.gen.getrandbits, -1)
289 self.assertRaises(TypeError, self.gen.getrandbits, 10.1)
290
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000291 def test_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200292 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
293 state = pickle.dumps(self.gen, proto)
294 origseq = [self.gen.random() for i in range(10)]
295 newgen = pickle.loads(state)
296 restoredseq = [newgen.random() for i in range(10)]
297 self.assertEqual(origseq, restoredseq)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000298
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000299 def test_bug_1727780(self):
300 # verify that version-2-pickles can be loaded
301 # fine, whether they are created on 32-bit or 64-bit
302 # platforms, and that version-3-pickles load fine.
303 files = [("randv2_32.pck", 780),
304 ("randv2_64.pck", 866),
305 ("randv3.pck", 343)]
306 for file, value in files:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +0200307 with open(support.findfile(file),"rb") as f:
308 r = pickle.load(f)
Raymond Hettinger05156612010-09-07 04:44:52 +0000309 self.assertEqual(int(r.random()*1000), value)
310
311 def test_bug_9025(self):
312 # Had problem with an uneven distribution in int(n*random())
313 # Verify the fix by checking that distributions fall within expectations.
314 n = 100000
315 randrange = self.gen.randrange
316 k = sum(randrange(6755399441055744) % 3 == 2 for i in range(n))
317 self.assertTrue(0.30 < k/n < .37, (k/n))
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000318
Victor Stinner9f5fe792020-04-17 19:05:35 +0200319 def test_randbytes(self):
320 # Verify ranges
321 for n in range(1, 10):
322 data = self.gen.randbytes(n)
323 self.assertEqual(type(data), bytes)
324 self.assertEqual(len(data), n)
325
326 self.assertEqual(self.gen.randbytes(0), b'')
327
328 # Verify argument checking
329 self.assertRaises(TypeError, self.gen.randbytes)
330 self.assertRaises(TypeError, self.gen.randbytes, 1, 2)
331 self.assertRaises(ValueError, self.gen.randbytes, -1)
332 self.assertRaises(TypeError, self.gen.randbytes, 1.0)
333
334
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300335try:
336 random.SystemRandom().random()
337except NotImplementedError:
338 SystemRandom_available = False
339else:
340 SystemRandom_available = True
341
342@unittest.skipUnless(SystemRandom_available, "random.SystemRandom not available")
343class SystemRandom_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000344 gen = random.SystemRandom()
Raymond Hettinger356a4592004-08-30 06:14:31 +0000345
346 def test_autoseed(self):
347 # Doesn't need to do anything except not fail
348 self.gen.seed()
349
350 def test_saverestore(self):
351 self.assertRaises(NotImplementedError, self.gen.getstate)
352 self.assertRaises(NotImplementedError, self.gen.setstate, None)
353
354 def test_seedargs(self):
355 # Doesn't need to do anything except not fail
356 self.gen.seed(100)
357
Raymond Hettinger356a4592004-08-30 06:14:31 +0000358 def test_gauss(self):
359 self.gen.gauss_next = None
360 self.gen.seed(100)
361 self.assertEqual(self.gen.gauss_next, None)
362
363 def test_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200364 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
365 self.assertRaises(NotImplementedError, pickle.dumps, self.gen, proto)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000366
367 def test_53_bits_per_float(self):
368 # This should pass whenever a C double has 53 bit precision.
369 span = 2 ** 53
370 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000371 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000372 cum |= int(self.gen.random() * span)
373 self.assertEqual(cum, span-1)
374
375 def test_bigrand(self):
376 # The randrange routine should build-up the required number of bits
377 # in stages so that all bit positions are active.
378 span = 2 ** 500
379 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000380 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000381 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000382 self.assertTrue(0 <= r < span)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000383 cum |= r
384 self.assertEqual(cum, span-1)
385
386 def test_bigrand_ranges(self):
387 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600388 start = self.gen.randrange(2 ** (i-2))
389 stop = self.gen.randrange(2 ** i)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000390 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600391 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000392 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000393
394 def test_rangelimits(self):
395 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
396 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000397 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000398
R David Murraye3e1c172013-04-02 12:47:23 -0400399 def test_randrange_nonunit_step(self):
400 rint = self.gen.randrange(0, 10, 2)
401 self.assertIn(rint, (0, 2, 4, 6, 8))
402 rint = self.gen.randrange(0, 2, 2)
403 self.assertEqual(rint, 0)
404
405 def test_randrange_errors(self):
406 raises = partial(self.assertRaises, ValueError, self.gen.randrange)
407 # Empty range
408 raises(3, 3)
409 raises(-721)
410 raises(0, 100, -12)
411 # Non-integer start/stop
412 raises(3.14159)
413 raises(0, 2.71828)
414 # Zero and non-integer step
415 raises(0, 42, 0)
416 raises(0, 42, 3.14159)
417
Raymond Hettinger356a4592004-08-30 06:14:31 +0000418 def test_randbelow_logic(self, _log=log, int=int):
419 # check bitcount transition points: 2**i and 2**(i+1)-1
420 # show that: k = int(1.001 + _log(n, 2))
421 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000422 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000423 n = 1 << i # check an exact power of two
Raymond Hettinger356a4592004-08-30 06:14:31 +0000424 numbits = i+1
425 k = int(1.00001 + _log(n, 2))
426 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000427 self.assertEqual(n, 2**(k-1))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000428
429 n += n - 1 # check 1 below the next power of two
430 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000431 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000432 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000433
434 n -= n >> 15 # check a little farther below the next power of two
435 k = int(1.00001 + _log(n, 2))
436 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000437 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger356a4592004-08-30 06:14:31 +0000438
439
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300440class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger40f62172002-12-29 23:03:38 +0000441 gen = random.Random()
442
Raymond Hettingerf763a722010-09-07 00:38:15 +0000443 def test_guaranteed_stable(self):
444 # These sequences are guaranteed to stay the same across versions of python
445 self.gen.seed(3456147, version=1)
446 self.assertEqual([self.gen.random().hex() for i in range(4)],
447 ['0x1.ac362300d90d2p-1', '0x1.9d16f74365005p-1',
448 '0x1.1ebb4352e4c4dp-1', '0x1.1a7422abf9c11p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000449 self.gen.seed("the quick brown fox", version=2)
450 self.assertEqual([self.gen.random().hex() for i in range(4)],
Raymond Hettinger3fcf0022010-12-08 01:13:53 +0000451 ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4',
452 '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000453
Raymond Hettingerc7bab7c2016-08-31 15:01:08 -0700454 def test_bug_27706(self):
455 # Verify that version 1 seeds are unaffected by hash randomization
456
457 self.gen.seed('nofar', version=1) # hash('nofar') == 5990528763808513177
458 self.assertEqual([self.gen.random().hex() for i in range(4)],
459 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
460 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
461
462 self.gen.seed('rachel', version=1) # hash('rachel') == -9091735575445484789
463 self.assertEqual([self.gen.random().hex() for i in range(4)],
464 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
465 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
466
467 self.gen.seed('', version=1) # hash('') == 0
468 self.assertEqual([self.gen.random().hex() for i in range(4)],
469 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
470 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
471
Oren Milmand780b2d2017-09-28 10:50:01 +0300472 def test_bug_31478(self):
473 # There shouldn't be an assertion failure in _random.Random.seed() in
474 # case the argument has a bad __abs__() method.
475 class BadInt(int):
476 def __abs__(self):
477 return None
478 try:
479 self.gen.seed(BadInt())
480 except TypeError:
481 pass
482
Raymond Hettinger132a7d72017-09-17 09:04:30 -0700483 def test_bug_31482(self):
484 # Verify that version 1 seeds are unaffected by hash randomization
485 # when the seeds are expressed as bytes rather than strings.
486 # The hash(b) values listed are the Python2.7 hash() values
487 # which were used for seeding.
488
489 self.gen.seed(b'nofar', version=1) # hash('nofar') == 5990528763808513177
490 self.assertEqual([self.gen.random().hex() for i in range(4)],
491 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
492 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
493
494 self.gen.seed(b'rachel', version=1) # hash('rachel') == -9091735575445484789
495 self.assertEqual([self.gen.random().hex() for i in range(4)],
496 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
497 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
498
499 self.gen.seed(b'', version=1) # hash('') == 0
500 self.assertEqual([self.gen.random().hex() for i in range(4)],
501 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
502 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
503
504 b = b'\x00\x20\x40\x60\x80\xA0\xC0\xE0\xF0'
505 self.gen.seed(b, version=1) # hash(b) == 5015594239749365497
506 self.assertEqual([self.gen.random().hex() for i in range(4)],
507 ['0x1.52c2fde444d23p-1', '0x1.875174f0daea4p-2',
508 '0x1.9e9b2c50e5cd2p-1', '0x1.fa57768bd321cp-2'])
509
Raymond Hettinger58335872004-07-09 14:26:18 +0000510 def test_setstate_first_arg(self):
511 self.assertRaises(ValueError, self.gen.setstate, (1, None, None))
512
513 def test_setstate_middle_arg(self):
bladebryan9616a822017-04-21 23:10:46 -0700514 start_state = self.gen.getstate()
Raymond Hettinger58335872004-07-09 14:26:18 +0000515 # Wrong type, s/b tuple
516 self.assertRaises(TypeError, self.gen.setstate, (2, None, None))
517 # Wrong length, s/b 625
518 self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None))
519 # Wrong type, s/b tuple of 625 ints
520 self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None))
521 # Last element s/b an int also
522 self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None))
Serhiy Storchaka178f0b62015-07-24 09:02:53 +0300523 # Last element s/b between 0 and 624
524 with self.assertRaises((ValueError, OverflowError)):
525 self.gen.setstate((2, (1,)*624+(625,), None))
526 with self.assertRaises((ValueError, OverflowError)):
527 self.gen.setstate((2, (1,)*624+(-1,), None))
bladebryan9616a822017-04-21 23:10:46 -0700528 # Failed calls to setstate() should not have changed the state.
529 bits100 = self.gen.getrandbits(100)
530 self.gen.setstate(start_state)
531 self.assertEqual(self.gen.getrandbits(100), bits100)
Raymond Hettinger58335872004-07-09 14:26:18 +0000532
R David Murraye3e1c172013-04-02 12:47:23 -0400533 # Little trick to make "tuple(x % (2**32) for x in internalstate)"
534 # raise ValueError. I cannot think of a simple way to achieve this, so
535 # I am opting for using a generator as the middle argument of setstate
536 # which attempts to cast a NaN to integer.
537 state_values = self.gen.getstate()[1]
538 state_values = list(state_values)
539 state_values[-1] = float('nan')
540 state = (int(x) for x in state_values)
541 self.assertRaises(TypeError, self.gen.setstate, (2, state, None))
542
Raymond Hettinger40f62172002-12-29 23:03:38 +0000543 def test_referenceImplementation(self):
544 # Compare the python implementation with results from the original
545 # code. Create 2000 53-bit precision random floats. Compare only
546 # the last ten entries to show that the independent implementations
547 # are tracking. Here is the main() function needed to create the
548 # list of expected random numbers:
549 # void main(void){
550 # int i;
551 # unsigned long init[4]={61731, 24903, 614, 42143}, length=4;
552 # init_by_array(init, length);
553 # for (i=0; i<2000; i++) {
554 # printf("%.15f ", genrand_res53());
555 # if (i%5==4) printf("\n");
556 # }
557 # }
558 expected = [0.45839803073713259,
559 0.86057815201978782,
560 0.92848331726782152,
561 0.35932681119782461,
562 0.081823493762449573,
563 0.14332226470169329,
564 0.084297823823520024,
565 0.53814864671831453,
566 0.089215024911993401,
567 0.78486196105372907]
568
Guido van Rossume2a383d2007-01-15 16:59:06 +0000569 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000570 actual = self.randomlist(2000)[-10:]
571 for a, e in zip(actual, expected):
572 self.assertAlmostEqual(a,e,places=14)
573
574 def test_strong_reference_implementation(self):
575 # Like test_referenceImplementation, but checks for exact bit-level
576 # equality. This should pass on any box where C double contains
577 # at least 53 bits of precision (the underlying algorithm suffers
578 # no rounding errors -- all results are exact).
579 from math import ldexp
580
Guido van Rossume2a383d2007-01-15 16:59:06 +0000581 expected = [0x0eab3258d2231f,
582 0x1b89db315277a5,
583 0x1db622a5518016,
584 0x0b7f9af0d575bf,
585 0x029e4c4db82240,
586 0x04961892f5d673,
587 0x02b291598e4589,
588 0x11388382c15694,
589 0x02dad977c9e1fe,
590 0x191d96d4d334c6]
591 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000592 actual = self.randomlist(2000)[-10:]
593 for a, e in zip(actual, expected):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000594 self.assertEqual(int(ldexp(a, 53)), e)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000595
596 def test_long_seed(self):
597 # This is most interesting to run in debug mode, just to make sure
598 # nothing blows up. Under the covers, a dynamically resized array
599 # is allocated, consuming space proportional to the number of bits
600 # in the seed. Unfortunately, that's a quadratic-time algorithm,
601 # so don't make this horribly big.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000602 seed = (1 << (10000 * 8)) - 1 # about 10K bytes
Raymond Hettinger40f62172002-12-29 23:03:38 +0000603 self.gen.seed(seed)
604
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000605 def test_53_bits_per_float(self):
606 # This should pass whenever a C double has 53 bit precision.
607 span = 2 ** 53
608 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000609 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000610 cum |= int(self.gen.random() * span)
611 self.assertEqual(cum, span-1)
612
613 def test_bigrand(self):
614 # The randrange routine should build-up the required number of bits
615 # in stages so that all bit positions are active.
616 span = 2 ** 500
617 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000618 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000619 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000620 self.assertTrue(0 <= r < span)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000621 cum |= r
622 self.assertEqual(cum, span-1)
623
624 def test_bigrand_ranges(self):
625 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600626 start = self.gen.randrange(2 ** (i-2))
627 stop = self.gen.randrange(2 ** i)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000628 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600629 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000630 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000631
632 def test_rangelimits(self):
633 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
Raymond Hettingera690a992003-11-16 16:17:49 +0000634 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000635 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000636
Antoine Pitrou75a33782020-04-17 19:32:14 +0200637 def test_getrandbits(self):
638 super().test_getrandbits()
639
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000640 # Verify cross-platform repeatability
641 self.gen.seed(1234567)
642 self.assertEqual(self.gen.getrandbits(100),
Guido van Rossume2a383d2007-01-15 16:59:06 +0000643 97904845777343510404718956115)
Raymond Hettinger58335872004-07-09 14:26:18 +0000644
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200645 def test_randrange_uses_getrandbits(self):
646 # Verify use of getrandbits by randrange
647 # Use same seed as in the cross-platform repeatability test
Antoine Pitrou75a33782020-04-17 19:32:14 +0200648 # in test_getrandbits above.
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200649 self.gen.seed(1234567)
650 # If randrange uses getrandbits, it should pick getrandbits(100)
651 # when called with a 100-bits stop argument.
652 self.assertEqual(self.gen.randrange(2**99),
653 97904845777343510404718956115)
654
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000655 def test_randbelow_logic(self, _log=log, int=int):
656 # check bitcount transition points: 2**i and 2**(i+1)-1
657 # show that: k = int(1.001 + _log(n, 2))
658 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000659 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000660 n = 1 << i # check an exact power of two
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000661 numbits = i+1
662 k = int(1.00001 + _log(n, 2))
663 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000664 self.assertEqual(n, 2**(k-1))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000665
666 n += n - 1 # check 1 below the next power of two
667 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000668 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000669 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000670
671 n -= n >> 15 # check a little farther below the next power of two
672 k = int(1.00001 + _log(n, 2))
673 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000674 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000675
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200676 def test_randbelow_without_getrandbits(self):
R David Murraye3e1c172013-04-02 12:47:23 -0400677 # Random._randbelow() can only use random() when the built-in one
678 # has been overridden but no new getrandbits() method was supplied.
R David Murraye3e1c172013-04-02 12:47:23 -0400679 maxsize = 1<<random.BPF
680 with warnings.catch_warnings():
681 warnings.simplefilter("ignore", UserWarning)
682 # Population range too large (n >= maxsize)
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200683 self.gen._randbelow_without_getrandbits(
684 maxsize+1, maxsize=maxsize
685 )
686 self.gen._randbelow_without_getrandbits(5640, maxsize=maxsize)
Wolfgang Maier091e95e2018-04-05 17:19:44 +0200687 # issue 33203: test that _randbelow raises ValueError on
688 # n == 0 also in its getrandbits-independent branch.
689 with self.assertRaises(ValueError):
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200690 self.gen._randbelow_without_getrandbits(0, maxsize=maxsize)
691
R David Murraye3e1c172013-04-02 12:47:23 -0400692 # This might be going too far to test a single line, but because of our
693 # noble aim of achieving 100% test coverage we need to write a case in
694 # which the following line in Random._randbelow() gets executed:
695 #
696 # rem = maxsize % n
697 # limit = (maxsize - rem) / maxsize
698 # r = random()
699 # while r >= limit:
700 # r = random() # <== *This line* <==<
701 #
702 # Therefore, to guarantee that the while loop is executed at least
703 # once, we need to mock random() so that it returns a number greater
704 # than 'limit' the first time it gets called.
705
706 n = 42
707 epsilon = 0.01
708 limit = (maxsize - (maxsize % n)) / maxsize
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200709 with unittest.mock.patch.object(random.Random, 'random') as random_mock:
710 random_mock.side_effect = [limit + epsilon, limit - epsilon]
711 self.gen._randbelow_without_getrandbits(n, maxsize=maxsize)
712 self.assertEqual(random_mock.call_count, 2)
R David Murraye3e1c172013-04-02 12:47:23 -0400713
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000714 def test_randrange_bug_1590891(self):
715 start = 1000000000000
716 stop = -100000000000000000000
717 step = -200
718 x = self.gen.randrange(start, stop, step)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000719 self.assertTrue(stop < x <= start)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000720 self.assertEqual((x+stop)%step, 0)
721
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700722 def test_choices_algorithms(self):
Raymond Hettinger24e42392016-11-13 00:42:56 -0500723 # The various ways of specifying weights should produce the same results
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700724 choices = self.gen.choices
Raymond Hettinger6023d332016-11-21 15:32:08 -0800725 n = 104729
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700726
727 self.gen.seed(8675309)
728 a = self.gen.choices(range(n), k=10000)
729
730 self.gen.seed(8675309)
731 b = self.gen.choices(range(n), [1]*n, k=10000)
732 self.assertEqual(a, b)
733
734 self.gen.seed(8675309)
735 c = self.gen.choices(range(n), cum_weights=range(1, n+1), k=10000)
736 self.assertEqual(a, c)
737
penguindustin96466302019-05-06 14:57:17 -0400738 # American Roulette
Raymond Hettinger77d574d2016-10-29 17:42:36 -0700739 population = ['Red', 'Black', 'Green']
740 weights = [18, 18, 2]
741 cum_weights = [18, 36, 38]
742 expanded_population = ['Red'] * 18 + ['Black'] * 18 + ['Green'] * 2
743
744 self.gen.seed(9035768)
745 a = self.gen.choices(expanded_population, k=10000)
746
747 self.gen.seed(9035768)
748 b = self.gen.choices(population, weights, k=10000)
749 self.assertEqual(a, b)
750
751 self.gen.seed(9035768)
752 c = self.gen.choices(population, cum_weights=cum_weights, k=10000)
753 self.assertEqual(a, c)
754
Victor Stinner9f5fe792020-04-17 19:05:35 +0200755 def test_randbytes(self):
756 super().test_randbytes()
757
758 # Mersenne Twister randbytes() is deterministic
759 # and does not depend on the endian and bitness.
760 seed = 8675309
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300761 expected = b'3\xa8\xf9f\xf4\xa4\xd06\x19\x8f\x9f\x82\x02oe\xf0'
Victor Stinner9f5fe792020-04-17 19:05:35 +0200762
763 self.gen.seed(seed)
764 self.assertEqual(self.gen.randbytes(16), expected)
765
766 # randbytes(0) must not consume any entropy
767 self.gen.seed(seed)
768 self.assertEqual(self.gen.randbytes(0), b'')
769 self.assertEqual(self.gen.randbytes(16), expected)
770
771 # Four randbytes(4) calls give the same output than randbytes(16)
772 self.gen.seed(seed)
773 self.assertEqual(b''.join([self.gen.randbytes(4) for _ in range(4)]),
774 expected)
775
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300776 # Each randbytes(1), randbytes(2) or randbytes(3) call consumes
777 # 4 bytes of entropy
Victor Stinner9f5fe792020-04-17 19:05:35 +0200778 self.gen.seed(seed)
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300779 expected1 = expected[3::4]
780 self.assertEqual(b''.join(self.gen.randbytes(1) for _ in range(4)),
781 expected1)
782
783 self.gen.seed(seed)
784 expected2 = b''.join(expected[i + 2: i + 4]
Victor Stinner9f5fe792020-04-17 19:05:35 +0200785 for i in range(0, len(expected), 4))
786 self.assertEqual(b''.join(self.gen.randbytes(2) for _ in range(4)),
787 expected2)
788
789 self.gen.seed(seed)
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300790 expected3 = b''.join(expected[i + 1: i + 4]
Victor Stinner9f5fe792020-04-17 19:05:35 +0200791 for i in range(0, len(expected), 4))
792 self.assertEqual(b''.join(self.gen.randbytes(3) for _ in range(4)),
793 expected3)
794
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300795 def test_randbytes_getrandbits(self):
796 # There is a simple relation between randbytes() and getrandbits()
797 seed = 2849427419
798 gen2 = random.Random()
799 self.gen.seed(seed)
800 gen2.seed(seed)
801 for n in range(9):
802 self.assertEqual(self.gen.randbytes(n),
803 gen2.getrandbits(n * 8).to_bytes(n, 'little'))
804
Victor Stinner9f5fe792020-04-17 19:05:35 +0200805
Raymond Hettinger2d0c2562009-02-19 09:53:18 +0000806def gamma(z, sqrt2pi=(2.0*pi)**0.5):
807 # Reflection to right half of complex plane
808 if z < 0.5:
809 return pi / sin(pi*z) / gamma(1.0-z)
810 # Lanczos approximation with g=7
811 az = z + (7.0 - 0.5)
812 return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
813 0.9999999999995183,
814 676.5203681218835 / z,
815 -1259.139216722289 / (z+1.0),
816 771.3234287757674 / (z+2.0),
817 -176.6150291498386 / (z+3.0),
818 12.50734324009056 / (z+4.0),
819 -0.1385710331296526 / (z+5.0),
820 0.9934937113930748e-05 / (z+6.0),
821 0.1659470187408462e-06 / (z+7.0),
822 ])
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000823
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000824class TestDistributions(unittest.TestCase):
825 def test_zeroinputs(self):
826 # Verify that distributions can handle a series of zero inputs'
827 g = random.Random()
Guido van Rossum805365e2007-05-07 22:24:25 +0000828 x = [g.random() for i in range(50)] + [0.0]*5
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000829 g.random = x[:].pop; g.uniform(1,10)
830 g.random = x[:].pop; g.paretovariate(1.0)
831 g.random = x[:].pop; g.expovariate(1.0)
832 g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200833 g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000834 g.random = x[:].pop; g.normalvariate(0.0, 1.0)
835 g.random = x[:].pop; g.gauss(0.0, 1.0)
836 g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
837 g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
838 g.random = x[:].pop; g.gammavariate(0.01, 1.0)
839 g.random = x[:].pop; g.gammavariate(1.0, 1.0)
840 g.random = x[:].pop; g.gammavariate(200.0, 1.0)
841 g.random = x[:].pop; g.betavariate(3.0, 3.0)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000842 g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000843
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000844 def test_avg_std(self):
845 # Use integration to test distribution average and standard deviation.
846 # Only works for distributions which do not consume variates in pairs
847 g = random.Random()
848 N = 5000
Guido van Rossum805365e2007-05-07 22:24:25 +0000849 x = [i/float(N) for i in range(1,N)]
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000850 for variate, args, mu, sigmasqrd in [
851 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
Christian Heimesfe337bf2008-03-23 21:54:12 +0000852 (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 +0000853 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200854 (g.vonmisesvariate, (1.23, 0), pi, pi**2/3),
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000855 (g.paretovariate, (5.0,), 5.0/(5.0-1),
856 5.0/((5.0-1)**2*(5.0-2))),
857 (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0),
858 gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
859 g.random = x[:].pop
860 y = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000861 for i in range(len(x)):
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000862 try:
863 y.append(variate(*args))
864 except IndexError:
865 pass
866 s1 = s2 = 0
867 for e in y:
868 s1 += e
869 s2 += (e - mu) ** 2
870 N = len(y)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200871 self.assertAlmostEqual(s1/N, mu, places=2,
872 msg='%s%r' % (variate.__name__, args))
873 self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2,
874 msg='%s%r' % (variate.__name__, args))
875
876 def test_constant(self):
877 g = random.Random()
878 N = 100
879 for variate, args, expected in [
880 (g.uniform, (10.0, 10.0), 10.0),
881 (g.triangular, (10.0, 10.0), 10.0),
Raymond Hettinger978c6ab2014-05-25 17:25:27 -0700882 (g.triangular, (10.0, 10.0, 10.0), 10.0),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200883 (g.expovariate, (float('inf'),), 0.0),
884 (g.vonmisesvariate, (3.0, float('inf')), 3.0),
885 (g.gauss, (10.0, 0.0), 10.0),
886 (g.lognormvariate, (0.0, 0.0), 1.0),
887 (g.lognormvariate, (-float('inf'), 0.0), 0.0),
888 (g.normalvariate, (10.0, 0.0), 10.0),
889 (g.paretovariate, (float('inf'),), 1.0),
890 (g.weibullvariate, (10.0, float('inf')), 10.0),
891 (g.weibullvariate, (0.0, 10.0), 0.0),
892 ]:
893 for i in range(N):
894 self.assertEqual(variate(*args), expected)
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000895
Mark Dickinsonbe5f9192013-02-10 14:16:10 +0000896 def test_von_mises_range(self):
897 # Issue 17149: von mises variates were not consistently in the
898 # range [0, 2*PI].
899 g = random.Random()
900 N = 100
901 for mu in 0.0, 0.1, 3.1, 6.2:
902 for kappa in 0.0, 2.3, 500.0:
903 for _ in range(N):
904 sample = g.vonmisesvariate(mu, kappa)
905 self.assertTrue(
906 0 <= sample <= random.TWOPI,
907 msg=("vonmisesvariate({}, {}) produced a result {} out"
908 " of range [0, 2*pi]").format(mu, kappa, sample))
909
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200910 def test_von_mises_large_kappa(self):
911 # Issue #17141: vonmisesvariate() was hang for large kappas
912 random.vonmisesvariate(0, 1e15)
913 random.vonmisesvariate(0, 1e100)
914
R David Murraye3e1c172013-04-02 12:47:23 -0400915 def test_gammavariate_errors(self):
916 # Both alpha and beta must be > 0.0
917 self.assertRaises(ValueError, random.gammavariate, -1, 3)
918 self.assertRaises(ValueError, random.gammavariate, 0, 2)
919 self.assertRaises(ValueError, random.gammavariate, 2, 0)
920 self.assertRaises(ValueError, random.gammavariate, 1, -3)
921
leodema63d15222018-12-24 07:54:25 +0100922 # There are three different possibilities in the current implementation
923 # of random.gammavariate(), depending on the value of 'alpha'. What we
924 # are going to do here is to fix the values returned by random() to
925 # generate test cases that provide 100% line coverage of the method.
R David Murraye3e1c172013-04-02 12:47:23 -0400926 @unittest.mock.patch('random.Random.random')
leodema63d15222018-12-24 07:54:25 +0100927 def test_gammavariate_alpha_greater_one(self, random_mock):
R David Murraye3e1c172013-04-02 12:47:23 -0400928
leodema63d15222018-12-24 07:54:25 +0100929 # #1: alpha > 1.0.
930 # We want the first random number to be outside the
R David Murraye3e1c172013-04-02 12:47:23 -0400931 # [1e-7, .9999999] range, so that the continue statement executes
932 # once. The values of u1 and u2 will be 0.5 and 0.3, respectively.
933 random_mock.side_effect = [1e-8, 0.5, 0.3]
934 returned_value = random.gammavariate(1.1, 2.3)
935 self.assertAlmostEqual(returned_value, 2.53)
936
leodema63d15222018-12-24 07:54:25 +0100937 @unittest.mock.patch('random.Random.random')
938 def test_gammavariate_alpha_equal_one(self, random_mock):
R David Murraye3e1c172013-04-02 12:47:23 -0400939
leodema63d15222018-12-24 07:54:25 +0100940 # #2.a: alpha == 1.
941 # The execution body of the while loop executes once.
942 # Then random.random() returns 0.45,
943 # which causes while to stop looping and the algorithm to terminate.
944 random_mock.side_effect = [0.45]
945 returned_value = random.gammavariate(1.0, 3.14)
946 self.assertAlmostEqual(returned_value, 1.877208182372648)
947
948 @unittest.mock.patch('random.Random.random')
949 def test_gammavariate_alpha_equal_one_equals_expovariate(self, random_mock):
950
951 # #2.b: alpha == 1.
952 # It must be equivalent of calling expovariate(1.0 / beta).
953 beta = 3.14
954 random_mock.side_effect = [1e-8, 1e-8]
955 gammavariate_returned_value = random.gammavariate(1.0, beta)
956 expovariate_returned_value = random.expovariate(1.0 / beta)
957 self.assertAlmostEqual(gammavariate_returned_value, expovariate_returned_value)
958
959 @unittest.mock.patch('random.Random.random')
960 def test_gammavariate_alpha_between_zero_and_one(self, random_mock):
961
962 # #3: 0 < alpha < 1.
963 # This is the most complex region of code to cover,
R David Murraye3e1c172013-04-02 12:47:23 -0400964 # as there are multiple if-else statements. Let's take a look at the
965 # source code, and determine the values that we need accordingly:
966 #
967 # while 1:
968 # u = random()
969 # b = (_e + alpha)/_e
970 # p = b*u
971 # if p <= 1.0: # <=== (A)
972 # x = p ** (1.0/alpha)
973 # else: # <=== (B)
974 # x = -_log((b-p)/alpha)
975 # u1 = random()
976 # if p > 1.0: # <=== (C)
977 # if u1 <= x ** (alpha - 1.0): # <=== (D)
978 # break
979 # elif u1 <= _exp(-x): # <=== (E)
980 # break
981 # return x * beta
982 #
983 # First, we want (A) to be True. For that we need that:
984 # b*random() <= 1.0
985 # r1 = random() <= 1.0 / b
986 #
987 # We now get to the second if-else branch, and here, since p <= 1.0,
988 # (C) is False and we take the elif branch, (E). For it to be True,
989 # so that the break is executed, we need that:
990 # r2 = random() <= _exp(-x)
991 # r2 <= _exp(-(p ** (1.0/alpha)))
992 # r2 <= _exp(-((b*r1) ** (1.0/alpha)))
993
994 _e = random._e
995 _exp = random._exp
996 _log = random._log
997 alpha = 0.35
998 beta = 1.45
999 b = (_e + alpha)/_e
1000 epsilon = 0.01
1001
1002 r1 = 0.8859296441566 # 1.0 / b
1003 r2 = 0.3678794411714 # _exp(-((b*r1) ** (1.0/alpha)))
1004
1005 # These four "random" values result in the following trace:
1006 # (A) True, (E) False --> [next iteration of while]
1007 # (A) True, (E) True --> [while loop breaks]
1008 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
1009 returned_value = random.gammavariate(alpha, beta)
1010 self.assertAlmostEqual(returned_value, 1.4499999999997544)
1011
1012 # Let's now make (A) be False. If this is the case, when we get to the
1013 # second if-else 'p' is greater than 1, so (C) evaluates to True. We
1014 # now encounter a second if statement, (D), which in order to execute
1015 # must satisfy the following condition:
1016 # r2 <= x ** (alpha - 1.0)
1017 # r2 <= (-_log((b-p)/alpha)) ** (alpha - 1.0)
1018 # r2 <= (-_log((b-(b*r1))/alpha)) ** (alpha - 1.0)
1019 r1 = 0.8959296441566 # (1.0 / b) + epsilon -- so that (A) is False
1020 r2 = 0.9445400408898141
1021
1022 # And these four values result in the following trace:
1023 # (B) and (C) True, (D) False --> [next iteration of while]
1024 # (B) and (C) True, (D) True [while loop breaks]
1025 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
1026 returned_value = random.gammavariate(alpha, beta)
1027 self.assertAlmostEqual(returned_value, 1.5830349561760781)
1028
1029 @unittest.mock.patch('random.Random.gammavariate')
1030 def test_betavariate_return_zero(self, gammavariate_mock):
1031 # betavariate() returns zero when the Gamma distribution
1032 # that it uses internally returns this same value.
1033 gammavariate_mock.return_value = 0.0
1034 self.assertEqual(0.0, random.betavariate(2.71828, 3.14159))
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +02001035
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001036
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001037class TestRandomSubclassing(unittest.TestCase):
1038 def test_random_subclass_with_kwargs(self):
1039 # SF bug #1486663 -- this used to erroneously raise a TypeError
1040 class Subclass(random.Random):
1041 def __init__(self, newarg=None):
1042 random.Random.__init__(self)
1043 Subclass(newarg=1)
1044
1045 def test_subclasses_overriding_methods(self):
1046 # Subclasses with an overridden random, but only the original
1047 # getrandbits method should not rely on getrandbits in for randrange,
1048 # but should use a getrandbits-independent implementation instead.
1049
1050 # subclass providing its own random **and** getrandbits methods
1051 # like random.SystemRandom does => keep relying on getrandbits for
1052 # randrange
1053 class SubClass1(random.Random):
1054 def random(self):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001055 called.add('SubClass1.random')
1056 return random.Random.random(self)
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001057
1058 def getrandbits(self, n):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001059 called.add('SubClass1.getrandbits')
1060 return random.Random.getrandbits(self, n)
1061 called = set()
1062 SubClass1().randrange(42)
1063 self.assertEqual(called, {'SubClass1.getrandbits'})
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001064
1065 # subclass providing only random => can only use random for randrange
1066 class SubClass2(random.Random):
1067 def random(self):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001068 called.add('SubClass2.random')
1069 return random.Random.random(self)
1070 called = set()
1071 SubClass2().randrange(42)
1072 self.assertEqual(called, {'SubClass2.random'})
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001073
1074 # subclass defining getrandbits to complement its inherited random
1075 # => can now rely on getrandbits for randrange again
1076 class SubClass3(SubClass2):
1077 def getrandbits(self, n):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001078 called.add('SubClass3.getrandbits')
1079 return random.Random.getrandbits(self, n)
1080 called = set()
1081 SubClass3().randrange(42)
1082 self.assertEqual(called, {'SubClass3.getrandbits'})
1083
1084 # subclass providing only random and inherited getrandbits
1085 # => random takes precedence
1086 class SubClass4(SubClass3):
1087 def random(self):
1088 called.add('SubClass4.random')
1089 return random.Random.random(self)
1090 called = set()
1091 SubClass4().randrange(42)
1092 self.assertEqual(called, {'SubClass4.random'})
1093
1094 # Following subclasses don't define random or getrandbits directly,
1095 # but inherit them from classes which are not subclasses of Random
1096 class Mixin1:
1097 def random(self):
1098 called.add('Mixin1.random')
1099 return random.Random.random(self)
1100 class Mixin2:
1101 def getrandbits(self, n):
1102 called.add('Mixin2.getrandbits')
1103 return random.Random.getrandbits(self, n)
1104
1105 class SubClass5(Mixin1, random.Random):
1106 pass
1107 called = set()
1108 SubClass5().randrange(42)
1109 self.assertEqual(called, {'Mixin1.random'})
1110
1111 class SubClass6(Mixin2, random.Random):
1112 pass
1113 called = set()
1114 SubClass6().randrange(42)
1115 self.assertEqual(called, {'Mixin2.getrandbits'})
1116
1117 class SubClass7(Mixin1, Mixin2, random.Random):
1118 pass
1119 called = set()
1120 SubClass7().randrange(42)
1121 self.assertEqual(called, {'Mixin1.random'})
1122
1123 class SubClass8(Mixin2, Mixin1, random.Random):
1124 pass
1125 called = set()
1126 SubClass8().randrange(42)
1127 self.assertEqual(called, {'Mixin2.getrandbits'})
1128
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001129
Raymond Hettinger40f62172002-12-29 23:03:38 +00001130class TestModule(unittest.TestCase):
1131 def testMagicConstants(self):
1132 self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141)
1133 self.assertAlmostEqual(random.TWOPI, 6.28318530718)
1134 self.assertAlmostEqual(random.LOG4, 1.38629436111989)
1135 self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627)
1136
1137 def test__all__(self):
1138 # tests validity but not completeness of the __all__ list
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001139 self.assertTrue(set(random.__all__) <= set(dir(random)))
Raymond Hettinger40f62172002-12-29 23:03:38 +00001140
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001141 @unittest.skipUnless(hasattr(os, "fork"), "fork() required")
1142 def test_after_fork(self):
1143 # Test the global Random instance gets reseeded in child
1144 r, w = os.pipe()
Victor Stinnerda5e9302017-08-09 17:59:05 +02001145 pid = os.fork()
1146 if pid == 0:
1147 # child process
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001148 try:
1149 val = random.getrandbits(128)
1150 with open(w, "w") as f:
1151 f.write(str(val))
1152 finally:
1153 os._exit(0)
1154 else:
Victor Stinnerda5e9302017-08-09 17:59:05 +02001155 # parent process
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001156 os.close(w)
1157 val = random.getrandbits(128)
1158 with open(r, "r") as f:
1159 child_val = eval(f.read())
1160 self.assertNotEqual(val, child_val)
1161
Victor Stinner278c1e12020-03-31 20:08:12 +02001162 support.wait_process(pid, exitcode=0)
Victor Stinnerda5e9302017-08-09 17:59:05 +02001163
Thomas Woutersb2137042007-02-01 18:02:27 +00001164
Raymond Hettinger40f62172002-12-29 23:03:38 +00001165if __name__ == "__main__":
Ezio Melotti3e4a98b2013-04-19 05:45:27 +03001166 unittest.main()