blob: bb95ca0884a516313c1b5f5e73ad43fa000095ff [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')
Raymond Hettinger190fac92020-05-02 16:45:32 -0700106 with self.assertWarns(DeprecationWarning):
107 shuffle(seq, mock_random)
csabellaf111fd22017-05-11 11:19:35 -0400108 mock_random.assert_called_with()
Antoine Pitrou5e394332012-11-04 02:10:33 +0100109
Raymond Hettingerdc4872e2010-09-07 10:06:56 +0000110 def test_choice(self):
111 choice = self.gen.choice
112 with self.assertRaises(IndexError):
113 choice([])
114 self.assertEqual(choice([50]), 50)
115 self.assertIn(choice([25, 75]), [25, 75])
116
Raymond Hettinger40f62172002-12-29 23:03:38 +0000117 def test_sample(self):
118 # For the entire allowable range of 0 <= k <= N, validate that
119 # the sample is of the correct length and contains only unique items
120 N = 100
Guido van Rossum805365e2007-05-07 22:24:25 +0000121 population = range(N)
122 for k in range(N+1):
Raymond Hettinger40f62172002-12-29 23:03:38 +0000123 s = self.gen.sample(population, k)
124 self.assertEqual(len(s), k)
Raymond Hettingera690a992003-11-16 16:17:49 +0000125 uniq = set(s)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000126 self.assertEqual(len(uniq), k)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000127 self.assertTrue(uniq <= set(population))
Raymond Hettinger8ec78812003-01-04 05:55:11 +0000128 self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0
R David Murraye3e1c172013-04-02 12:47:23 -0400129 # Exception raised if size of sample exceeds that of population
130 self.assertRaises(ValueError, self.gen.sample, population, N+1)
Raymond Hettingerbf871262016-11-21 14:34:33 -0800131 self.assertRaises(ValueError, self.gen.sample, [], -1)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000132
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000133 def test_sample_distribution(self):
134 # For the entire allowable range of 0 <= k <= N, validate that
135 # sample generates all possible permutations
136 n = 5
137 pop = range(n)
138 trials = 10000 # large num prevents false negatives without slowing normal case
Guido van Rossum805365e2007-05-07 22:24:25 +0000139 for k in range(n):
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +0000140 expected = factorial(n) // factorial(n-k)
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000141 perms = {}
Guido van Rossum805365e2007-05-07 22:24:25 +0000142 for i in range(trials):
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000143 perms[tuple(self.gen.sample(pop, k))] = None
144 if len(perms) == expected:
145 break
146 else:
147 self.fail()
148
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000149 def test_sample_inputs(self):
150 # SF bug #801342 -- population can be any iterable defining __len__()
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 Hettinger4fe00202020-04-19 00:36:42 -0700159 def test_sample_on_sets(self):
160 with self.assertWarns(DeprecationWarning):
161 population = {10, 20, 30, 40, 50, 60, 70}
162 self.gen.sample(population, k=5)
163
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700164 def test_choices(self):
165 choices = self.gen.choices
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700166 data = ['red', 'green', 'blue', 'yellow']
167 str_data = 'abcd'
168 range_data = range(4)
169 set_data = set(range(4))
170
171 # basic functionality
172 for sample in [
Raymond Hettinger9016f282016-09-26 21:45:57 -0700173 choices(data, k=5),
174 choices(data, range(4), k=5),
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700175 choices(k=5, population=data, weights=range(4)),
176 choices(k=5, population=data, cum_weights=range(4)),
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700177 ]:
178 self.assertEqual(len(sample), 5)
179 self.assertEqual(type(sample), list)
180 self.assertTrue(set(sample) <= set(data))
181
182 # test argument handling
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700183 with self.assertRaises(TypeError): # missing arguments
184 choices(2)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700185
Raymond Hettinger9016f282016-09-26 21:45:57 -0700186 self.assertEqual(choices(data, k=0), []) # k == 0
187 self.assertEqual(choices(data, k=-1), []) # negative k behaves like ``[0] * -1``
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700188 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700189 choices(data, k=2.5) # k is a float
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700190
Raymond Hettinger9016f282016-09-26 21:45:57 -0700191 self.assertTrue(set(choices(str_data, k=5)) <= set(str_data)) # population is a string sequence
192 self.assertTrue(set(choices(range_data, k=5)) <= set(range_data)) # population is a range
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700193 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700194 choices(set_data, k=2) # population is not a sequence
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700195
Raymond Hettinger9016f282016-09-26 21:45:57 -0700196 self.assertTrue(set(choices(data, None, k=5)) <= set(data)) # weights is None
197 self.assertTrue(set(choices(data, weights=None, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700198 with self.assertRaises(ValueError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700199 choices(data, [1,2], k=5) # len(weights) != len(population)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700200 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700201 choices(data, 10, k=5) # non-iterable weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700202 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700203 choices(data, [None]*4, k=5) # non-numeric weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700204 for weights in [
205 [15, 10, 25, 30], # integer weights
206 [15.1, 10.2, 25.2, 30.3], # float weights
207 [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional weights
208 [True, False, True, False] # booleans (include / exclude)
209 ]:
Raymond Hettinger9016f282016-09-26 21:45:57 -0700210 self.assertTrue(set(choices(data, weights, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700211
212 with self.assertRaises(ValueError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700213 choices(data, cum_weights=[1,2], k=5) # len(weights) != len(population)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700214 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700215 choices(data, cum_weights=10, k=5) # non-iterable cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700216 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700217 choices(data, cum_weights=[None]*4, k=5) # non-numeric cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700218 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700219 choices(data, range(4), cum_weights=range(4), k=5) # both weights and cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700220 for weights in [
221 [15, 10, 25, 30], # integer cum_weights
222 [15.1, 10.2, 25.2, 30.3], # float cum_weights
223 [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional cum_weights
224 ]:
Raymond Hettinger9016f282016-09-26 21:45:57 -0700225 self.assertTrue(set(choices(data, cum_weights=weights, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700226
Raymond Hettinger7b166522016-10-14 01:19:38 -0400227 # Test weight focused on a single element of the population
228 self.assertEqual(choices('abcd', [1, 0, 0, 0]), ['a'])
229 self.assertEqual(choices('abcd', [0, 1, 0, 0]), ['b'])
230 self.assertEqual(choices('abcd', [0, 0, 1, 0]), ['c'])
231 self.assertEqual(choices('abcd', [0, 0, 0, 1]), ['d'])
232
233 # Test consistency with random.choice() for empty population
234 with self.assertRaises(IndexError):
235 choices([], k=1)
236 with self.assertRaises(IndexError):
237 choices([], weights=[], k=1)
238 with self.assertRaises(IndexError):
239 choices([], cum_weights=[], k=5)
240
Raymond Hettingerddf71712018-06-27 01:08:31 -0700241 def test_choices_subnormal(self):
Min ho Kim96e12d52019-07-22 06:12:33 +1000242 # Subnormal weights would occasionally trigger an IndexError
Raymond Hettingerddf71712018-06-27 01:08:31 -0700243 # in choices() when the value returned by random() was large
244 # enough to make `random() * total` round up to the total.
245 # See https://bugs.python.org/msg275594 for more detail.
246 choices = self.gen.choices
247 choices(population=[1, 2], weights=[1e-323, 1e-323], k=5000)
248
Raymond Hettinger041d8b42019-11-23 02:22:13 -0800249 def test_choices_with_all_zero_weights(self):
250 # See issue #38881
251 with self.assertRaises(ValueError):
252 self.gen.choices('AB', [0.0, 0.0])
253
Raymond Hettinger40f62172002-12-29 23:03:38 +0000254 def test_gauss(self):
255 # Ensure that the seed() method initializes all the hidden state. In
256 # particular, through 2.2.1 it failed to reset a piece of state used
257 # by (and only by) the .gauss() method.
258
259 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
260 self.gen.seed(seed)
261 x1 = self.gen.random()
262 y1 = self.gen.gauss(0, 1)
263
264 self.gen.seed(seed)
265 x2 = self.gen.random()
266 y2 = self.gen.gauss(0, 1)
267
268 self.assertEqual(x1, x2)
269 self.assertEqual(y1, y2)
270
Antoine Pitrou75a33782020-04-17 19:32:14 +0200271 def test_getrandbits(self):
272 # Verify ranges
273 for k in range(1, 1000):
274 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
275 self.assertEqual(self.gen.getrandbits(0), 0)
276
277 # Verify all bits active
278 getbits = self.gen.getrandbits
279 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
280 all_bits = 2**span-1
281 cum = 0
282 cpl_cum = 0
283 for i in range(100):
284 v = getbits(span)
285 cum |= v
286 cpl_cum |= all_bits ^ v
287 self.assertEqual(cum, all_bits)
288 self.assertEqual(cpl_cum, all_bits)
289
290 # Verify argument checking
291 self.assertRaises(TypeError, self.gen.getrandbits)
292 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
293 self.assertRaises(ValueError, self.gen.getrandbits, -1)
294 self.assertRaises(TypeError, self.gen.getrandbits, 10.1)
295
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000296 def test_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200297 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
298 state = pickle.dumps(self.gen, proto)
299 origseq = [self.gen.random() for i in range(10)]
300 newgen = pickle.loads(state)
301 restoredseq = [newgen.random() for i in range(10)]
302 self.assertEqual(origseq, restoredseq)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000303
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000304 def test_bug_1727780(self):
305 # verify that version-2-pickles can be loaded
306 # fine, whether they are created on 32-bit or 64-bit
307 # platforms, and that version-3-pickles load fine.
308 files = [("randv2_32.pck", 780),
309 ("randv2_64.pck", 866),
310 ("randv3.pck", 343)]
311 for file, value in files:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +0200312 with open(support.findfile(file),"rb") as f:
313 r = pickle.load(f)
Raymond Hettinger05156612010-09-07 04:44:52 +0000314 self.assertEqual(int(r.random()*1000), value)
315
316 def test_bug_9025(self):
317 # Had problem with an uneven distribution in int(n*random())
318 # Verify the fix by checking that distributions fall within expectations.
319 n = 100000
320 randrange = self.gen.randrange
321 k = sum(randrange(6755399441055744) % 3 == 2 for i in range(n))
322 self.assertTrue(0.30 < k/n < .37, (k/n))
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000323
Victor Stinner9f5fe792020-04-17 19:05:35 +0200324 def test_randbytes(self):
325 # Verify ranges
326 for n in range(1, 10):
327 data = self.gen.randbytes(n)
328 self.assertEqual(type(data), bytes)
329 self.assertEqual(len(data), n)
330
331 self.assertEqual(self.gen.randbytes(0), b'')
332
333 # Verify argument checking
334 self.assertRaises(TypeError, self.gen.randbytes)
335 self.assertRaises(TypeError, self.gen.randbytes, 1, 2)
336 self.assertRaises(ValueError, self.gen.randbytes, -1)
337 self.assertRaises(TypeError, self.gen.randbytes, 1.0)
338
339
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300340try:
341 random.SystemRandom().random()
342except NotImplementedError:
343 SystemRandom_available = False
344else:
345 SystemRandom_available = True
346
347@unittest.skipUnless(SystemRandom_available, "random.SystemRandom not available")
348class SystemRandom_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000349 gen = random.SystemRandom()
Raymond Hettinger356a4592004-08-30 06:14:31 +0000350
351 def test_autoseed(self):
352 # Doesn't need to do anything except not fail
353 self.gen.seed()
354
355 def test_saverestore(self):
356 self.assertRaises(NotImplementedError, self.gen.getstate)
357 self.assertRaises(NotImplementedError, self.gen.setstate, None)
358
359 def test_seedargs(self):
360 # Doesn't need to do anything except not fail
361 self.gen.seed(100)
362
Raymond Hettinger356a4592004-08-30 06:14:31 +0000363 def test_gauss(self):
364 self.gen.gauss_next = None
365 self.gen.seed(100)
366 self.assertEqual(self.gen.gauss_next, None)
367
368 def test_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200369 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
370 self.assertRaises(NotImplementedError, pickle.dumps, self.gen, proto)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000371
372 def test_53_bits_per_float(self):
373 # This should pass whenever a C double has 53 bit precision.
374 span = 2 ** 53
375 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000376 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000377 cum |= int(self.gen.random() * span)
378 self.assertEqual(cum, span-1)
379
380 def test_bigrand(self):
381 # The randrange routine should build-up the required number of bits
382 # in stages so that all bit positions are active.
383 span = 2 ** 500
384 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000385 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000386 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000387 self.assertTrue(0 <= r < span)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000388 cum |= r
389 self.assertEqual(cum, span-1)
390
391 def test_bigrand_ranges(self):
392 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600393 start = self.gen.randrange(2 ** (i-2))
394 stop = self.gen.randrange(2 ** i)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000395 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600396 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000397 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000398
399 def test_rangelimits(self):
400 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
401 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000402 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000403
R David Murraye3e1c172013-04-02 12:47:23 -0400404 def test_randrange_nonunit_step(self):
405 rint = self.gen.randrange(0, 10, 2)
406 self.assertIn(rint, (0, 2, 4, 6, 8))
407 rint = self.gen.randrange(0, 2, 2)
408 self.assertEqual(rint, 0)
409
410 def test_randrange_errors(self):
411 raises = partial(self.assertRaises, ValueError, self.gen.randrange)
412 # Empty range
413 raises(3, 3)
414 raises(-721)
415 raises(0, 100, -12)
416 # Non-integer start/stop
417 raises(3.14159)
418 raises(0, 2.71828)
419 # Zero and non-integer step
420 raises(0, 42, 0)
421 raises(0, 42, 3.14159)
422
Raymond Hettinger356a4592004-08-30 06:14:31 +0000423 def test_randbelow_logic(self, _log=log, int=int):
424 # check bitcount transition points: 2**i and 2**(i+1)-1
425 # show that: k = int(1.001 + _log(n, 2))
426 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000427 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000428 n = 1 << i # check an exact power of two
Raymond Hettinger356a4592004-08-30 06:14:31 +0000429 numbits = i+1
430 k = int(1.00001 + _log(n, 2))
431 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000432 self.assertEqual(n, 2**(k-1))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000433
434 n += n - 1 # check 1 below the next power of two
435 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000436 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000437 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000438
439 n -= n >> 15 # check a little farther below the next power of two
440 k = int(1.00001 + _log(n, 2))
441 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000442 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger356a4592004-08-30 06:14:31 +0000443
444
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300445class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger40f62172002-12-29 23:03:38 +0000446 gen = random.Random()
447
Raymond Hettingerf763a722010-09-07 00:38:15 +0000448 def test_guaranteed_stable(self):
449 # These sequences are guaranteed to stay the same across versions of python
450 self.gen.seed(3456147, version=1)
451 self.assertEqual([self.gen.random().hex() for i in range(4)],
452 ['0x1.ac362300d90d2p-1', '0x1.9d16f74365005p-1',
453 '0x1.1ebb4352e4c4dp-1', '0x1.1a7422abf9c11p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000454 self.gen.seed("the quick brown fox", version=2)
455 self.assertEqual([self.gen.random().hex() for i in range(4)],
Raymond Hettinger3fcf0022010-12-08 01:13:53 +0000456 ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4',
457 '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000458
Raymond Hettingerc7bab7c2016-08-31 15:01:08 -0700459 def test_bug_27706(self):
460 # Verify that version 1 seeds are unaffected by hash randomization
461
462 self.gen.seed('nofar', version=1) # hash('nofar') == 5990528763808513177
463 self.assertEqual([self.gen.random().hex() for i in range(4)],
464 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
465 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
466
467 self.gen.seed('rachel', version=1) # hash('rachel') == -9091735575445484789
468 self.assertEqual([self.gen.random().hex() for i in range(4)],
469 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
470 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
471
472 self.gen.seed('', version=1) # hash('') == 0
473 self.assertEqual([self.gen.random().hex() for i in range(4)],
474 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
475 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
476
Oren Milmand780b2d2017-09-28 10:50:01 +0300477 def test_bug_31478(self):
478 # There shouldn't be an assertion failure in _random.Random.seed() in
479 # case the argument has a bad __abs__() method.
480 class BadInt(int):
481 def __abs__(self):
482 return None
483 try:
484 self.gen.seed(BadInt())
485 except TypeError:
486 pass
487
Raymond Hettinger132a7d72017-09-17 09:04:30 -0700488 def test_bug_31482(self):
489 # Verify that version 1 seeds are unaffected by hash randomization
490 # when the seeds are expressed as bytes rather than strings.
491 # The hash(b) values listed are the Python2.7 hash() values
492 # which were used for seeding.
493
494 self.gen.seed(b'nofar', version=1) # hash('nofar') == 5990528763808513177
495 self.assertEqual([self.gen.random().hex() for i in range(4)],
496 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
497 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
498
499 self.gen.seed(b'rachel', version=1) # hash('rachel') == -9091735575445484789
500 self.assertEqual([self.gen.random().hex() for i in range(4)],
501 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
502 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
503
504 self.gen.seed(b'', version=1) # hash('') == 0
505 self.assertEqual([self.gen.random().hex() for i in range(4)],
506 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
507 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
508
509 b = b'\x00\x20\x40\x60\x80\xA0\xC0\xE0\xF0'
510 self.gen.seed(b, version=1) # hash(b) == 5015594239749365497
511 self.assertEqual([self.gen.random().hex() for i in range(4)],
512 ['0x1.52c2fde444d23p-1', '0x1.875174f0daea4p-2',
513 '0x1.9e9b2c50e5cd2p-1', '0x1.fa57768bd321cp-2'])
514
Raymond Hettinger58335872004-07-09 14:26:18 +0000515 def test_setstate_first_arg(self):
516 self.assertRaises(ValueError, self.gen.setstate, (1, None, None))
517
518 def test_setstate_middle_arg(self):
bladebryan9616a822017-04-21 23:10:46 -0700519 start_state = self.gen.getstate()
Raymond Hettinger58335872004-07-09 14:26:18 +0000520 # Wrong type, s/b tuple
521 self.assertRaises(TypeError, self.gen.setstate, (2, None, None))
522 # Wrong length, s/b 625
523 self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None))
524 # Wrong type, s/b tuple of 625 ints
525 self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None))
526 # Last element s/b an int also
527 self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None))
Serhiy Storchaka178f0b62015-07-24 09:02:53 +0300528 # Last element s/b between 0 and 624
529 with self.assertRaises((ValueError, OverflowError)):
530 self.gen.setstate((2, (1,)*624+(625,), None))
531 with self.assertRaises((ValueError, OverflowError)):
532 self.gen.setstate((2, (1,)*624+(-1,), None))
bladebryan9616a822017-04-21 23:10:46 -0700533 # Failed calls to setstate() should not have changed the state.
534 bits100 = self.gen.getrandbits(100)
535 self.gen.setstate(start_state)
536 self.assertEqual(self.gen.getrandbits(100), bits100)
Raymond Hettinger58335872004-07-09 14:26:18 +0000537
R David Murraye3e1c172013-04-02 12:47:23 -0400538 # Little trick to make "tuple(x % (2**32) for x in internalstate)"
539 # raise ValueError. I cannot think of a simple way to achieve this, so
540 # I am opting for using a generator as the middle argument of setstate
541 # which attempts to cast a NaN to integer.
542 state_values = self.gen.getstate()[1]
543 state_values = list(state_values)
544 state_values[-1] = float('nan')
545 state = (int(x) for x in state_values)
546 self.assertRaises(TypeError, self.gen.setstate, (2, state, None))
547
Raymond Hettinger40f62172002-12-29 23:03:38 +0000548 def test_referenceImplementation(self):
549 # Compare the python implementation with results from the original
550 # code. Create 2000 53-bit precision random floats. Compare only
551 # the last ten entries to show that the independent implementations
552 # are tracking. Here is the main() function needed to create the
553 # list of expected random numbers:
554 # void main(void){
555 # int i;
556 # unsigned long init[4]={61731, 24903, 614, 42143}, length=4;
557 # init_by_array(init, length);
558 # for (i=0; i<2000; i++) {
559 # printf("%.15f ", genrand_res53());
560 # if (i%5==4) printf("\n");
561 # }
562 # }
563 expected = [0.45839803073713259,
564 0.86057815201978782,
565 0.92848331726782152,
566 0.35932681119782461,
567 0.081823493762449573,
568 0.14332226470169329,
569 0.084297823823520024,
570 0.53814864671831453,
571 0.089215024911993401,
572 0.78486196105372907]
573
Guido van Rossume2a383d2007-01-15 16:59:06 +0000574 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000575 actual = self.randomlist(2000)[-10:]
576 for a, e in zip(actual, expected):
577 self.assertAlmostEqual(a,e,places=14)
578
579 def test_strong_reference_implementation(self):
580 # Like test_referenceImplementation, but checks for exact bit-level
581 # equality. This should pass on any box where C double contains
582 # at least 53 bits of precision (the underlying algorithm suffers
583 # no rounding errors -- all results are exact).
584 from math import ldexp
585
Guido van Rossume2a383d2007-01-15 16:59:06 +0000586 expected = [0x0eab3258d2231f,
587 0x1b89db315277a5,
588 0x1db622a5518016,
589 0x0b7f9af0d575bf,
590 0x029e4c4db82240,
591 0x04961892f5d673,
592 0x02b291598e4589,
593 0x11388382c15694,
594 0x02dad977c9e1fe,
595 0x191d96d4d334c6]
596 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000597 actual = self.randomlist(2000)[-10:]
598 for a, e in zip(actual, expected):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000599 self.assertEqual(int(ldexp(a, 53)), e)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000600
601 def test_long_seed(self):
602 # This is most interesting to run in debug mode, just to make sure
603 # nothing blows up. Under the covers, a dynamically resized array
604 # is allocated, consuming space proportional to the number of bits
605 # in the seed. Unfortunately, that's a quadratic-time algorithm,
606 # so don't make this horribly big.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000607 seed = (1 << (10000 * 8)) - 1 # about 10K bytes
Raymond Hettinger40f62172002-12-29 23:03:38 +0000608 self.gen.seed(seed)
609
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000610 def test_53_bits_per_float(self):
611 # This should pass whenever a C double has 53 bit precision.
612 span = 2 ** 53
613 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000614 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000615 cum |= int(self.gen.random() * span)
616 self.assertEqual(cum, span-1)
617
618 def test_bigrand(self):
619 # The randrange routine should build-up the required number of bits
620 # in stages so that all bit positions are active.
621 span = 2 ** 500
622 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000623 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000624 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000625 self.assertTrue(0 <= r < span)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000626 cum |= r
627 self.assertEqual(cum, span-1)
628
629 def test_bigrand_ranges(self):
630 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600631 start = self.gen.randrange(2 ** (i-2))
632 stop = self.gen.randrange(2 ** i)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000633 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600634 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000635 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000636
637 def test_rangelimits(self):
638 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
Raymond Hettingera690a992003-11-16 16:17:49 +0000639 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000640 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000641
Antoine Pitrou75a33782020-04-17 19:32:14 +0200642 def test_getrandbits(self):
643 super().test_getrandbits()
644
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000645 # Verify cross-platform repeatability
646 self.gen.seed(1234567)
647 self.assertEqual(self.gen.getrandbits(100),
Guido van Rossume2a383d2007-01-15 16:59:06 +0000648 97904845777343510404718956115)
Raymond Hettinger58335872004-07-09 14:26:18 +0000649
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200650 def test_randrange_uses_getrandbits(self):
651 # Verify use of getrandbits by randrange
652 # Use same seed as in the cross-platform repeatability test
Antoine Pitrou75a33782020-04-17 19:32:14 +0200653 # in test_getrandbits above.
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200654 self.gen.seed(1234567)
655 # If randrange uses getrandbits, it should pick getrandbits(100)
656 # when called with a 100-bits stop argument.
657 self.assertEqual(self.gen.randrange(2**99),
658 97904845777343510404718956115)
659
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000660 def test_randbelow_logic(self, _log=log, int=int):
661 # check bitcount transition points: 2**i and 2**(i+1)-1
662 # show that: k = int(1.001 + _log(n, 2))
663 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000664 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000665 n = 1 << i # check an exact power of two
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000666 numbits = i+1
667 k = int(1.00001 + _log(n, 2))
668 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000669 self.assertEqual(n, 2**(k-1))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000670
671 n += n - 1 # check 1 below the next power of two
672 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000673 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000674 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000675
676 n -= n >> 15 # check a little farther below the next power of two
677 k = int(1.00001 + _log(n, 2))
678 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000679 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000680
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200681 def test_randbelow_without_getrandbits(self):
R David Murraye3e1c172013-04-02 12:47:23 -0400682 # Random._randbelow() can only use random() when the built-in one
683 # has been overridden but no new getrandbits() method was supplied.
R David Murraye3e1c172013-04-02 12:47:23 -0400684 maxsize = 1<<random.BPF
685 with warnings.catch_warnings():
686 warnings.simplefilter("ignore", UserWarning)
687 # Population range too large (n >= maxsize)
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200688 self.gen._randbelow_without_getrandbits(
689 maxsize+1, maxsize=maxsize
690 )
691 self.gen._randbelow_without_getrandbits(5640, maxsize=maxsize)
Raymond Hettinger4168f1e2020-05-01 10:34:19 -0700692 # issue 33203: test that _randbelow returns zero on
Wolfgang Maier091e95e2018-04-05 17:19:44 +0200693 # n == 0 also in its getrandbits-independent branch.
Raymond Hettinger4168f1e2020-05-01 10:34:19 -0700694 x = self.gen._randbelow_without_getrandbits(0, maxsize=maxsize)
695 self.assertEqual(x, 0)
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200696
R David Murraye3e1c172013-04-02 12:47:23 -0400697 # This might be going too far to test a single line, but because of our
698 # noble aim of achieving 100% test coverage we need to write a case in
699 # which the following line in Random._randbelow() gets executed:
700 #
701 # rem = maxsize % n
702 # limit = (maxsize - rem) / maxsize
703 # r = random()
704 # while r >= limit:
705 # r = random() # <== *This line* <==<
706 #
707 # Therefore, to guarantee that the while loop is executed at least
708 # once, we need to mock random() so that it returns a number greater
709 # than 'limit' the first time it gets called.
710
711 n = 42
712 epsilon = 0.01
713 limit = (maxsize - (maxsize % n)) / maxsize
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200714 with unittest.mock.patch.object(random.Random, 'random') as random_mock:
715 random_mock.side_effect = [limit + epsilon, limit - epsilon]
716 self.gen._randbelow_without_getrandbits(n, maxsize=maxsize)
717 self.assertEqual(random_mock.call_count, 2)
R David Murraye3e1c172013-04-02 12:47:23 -0400718
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000719 def test_randrange_bug_1590891(self):
720 start = 1000000000000
721 stop = -100000000000000000000
722 step = -200
723 x = self.gen.randrange(start, stop, step)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000724 self.assertTrue(stop < x <= start)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000725 self.assertEqual((x+stop)%step, 0)
726
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700727 def test_choices_algorithms(self):
Raymond Hettinger24e42392016-11-13 00:42:56 -0500728 # The various ways of specifying weights should produce the same results
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700729 choices = self.gen.choices
Raymond Hettinger6023d332016-11-21 15:32:08 -0800730 n = 104729
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700731
732 self.gen.seed(8675309)
733 a = self.gen.choices(range(n), k=10000)
734
735 self.gen.seed(8675309)
736 b = self.gen.choices(range(n), [1]*n, k=10000)
737 self.assertEqual(a, b)
738
739 self.gen.seed(8675309)
740 c = self.gen.choices(range(n), cum_weights=range(1, n+1), k=10000)
741 self.assertEqual(a, c)
742
penguindustin96466302019-05-06 14:57:17 -0400743 # American Roulette
Raymond Hettinger77d574d2016-10-29 17:42:36 -0700744 population = ['Red', 'Black', 'Green']
745 weights = [18, 18, 2]
746 cum_weights = [18, 36, 38]
747 expanded_population = ['Red'] * 18 + ['Black'] * 18 + ['Green'] * 2
748
749 self.gen.seed(9035768)
750 a = self.gen.choices(expanded_population, k=10000)
751
752 self.gen.seed(9035768)
753 b = self.gen.choices(population, weights, k=10000)
754 self.assertEqual(a, b)
755
756 self.gen.seed(9035768)
757 c = self.gen.choices(population, cum_weights=cum_weights, k=10000)
758 self.assertEqual(a, c)
759
Victor Stinner9f5fe792020-04-17 19:05:35 +0200760 def test_randbytes(self):
761 super().test_randbytes()
762
763 # Mersenne Twister randbytes() is deterministic
764 # and does not depend on the endian and bitness.
765 seed = 8675309
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300766 expected = b'3\xa8\xf9f\xf4\xa4\xd06\x19\x8f\x9f\x82\x02oe\xf0'
Victor Stinner9f5fe792020-04-17 19:05:35 +0200767
768 self.gen.seed(seed)
769 self.assertEqual(self.gen.randbytes(16), expected)
770
771 # randbytes(0) must not consume any entropy
772 self.gen.seed(seed)
773 self.assertEqual(self.gen.randbytes(0), b'')
774 self.assertEqual(self.gen.randbytes(16), expected)
775
776 # Four randbytes(4) calls give the same output than randbytes(16)
777 self.gen.seed(seed)
778 self.assertEqual(b''.join([self.gen.randbytes(4) for _ in range(4)]),
779 expected)
780
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300781 # Each randbytes(1), randbytes(2) or randbytes(3) call consumes
782 # 4 bytes of entropy
Victor Stinner9f5fe792020-04-17 19:05:35 +0200783 self.gen.seed(seed)
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300784 expected1 = expected[3::4]
785 self.assertEqual(b''.join(self.gen.randbytes(1) for _ in range(4)),
786 expected1)
787
788 self.gen.seed(seed)
789 expected2 = b''.join(expected[i + 2: i + 4]
Victor Stinner9f5fe792020-04-17 19:05:35 +0200790 for i in range(0, len(expected), 4))
791 self.assertEqual(b''.join(self.gen.randbytes(2) for _ in range(4)),
792 expected2)
793
794 self.gen.seed(seed)
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300795 expected3 = b''.join(expected[i + 1: i + 4]
Victor Stinner9f5fe792020-04-17 19:05:35 +0200796 for i in range(0, len(expected), 4))
797 self.assertEqual(b''.join(self.gen.randbytes(3) for _ in range(4)),
798 expected3)
799
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300800 def test_randbytes_getrandbits(self):
801 # There is a simple relation between randbytes() and getrandbits()
802 seed = 2849427419
803 gen2 = random.Random()
804 self.gen.seed(seed)
805 gen2.seed(seed)
806 for n in range(9):
807 self.assertEqual(self.gen.randbytes(n),
808 gen2.getrandbits(n * 8).to_bytes(n, 'little'))
809
Victor Stinner9f5fe792020-04-17 19:05:35 +0200810
Raymond Hettinger2d0c2562009-02-19 09:53:18 +0000811def gamma(z, sqrt2pi=(2.0*pi)**0.5):
812 # Reflection to right half of complex plane
813 if z < 0.5:
814 return pi / sin(pi*z) / gamma(1.0-z)
815 # Lanczos approximation with g=7
816 az = z + (7.0 - 0.5)
817 return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
818 0.9999999999995183,
819 676.5203681218835 / z,
820 -1259.139216722289 / (z+1.0),
821 771.3234287757674 / (z+2.0),
822 -176.6150291498386 / (z+3.0),
823 12.50734324009056 / (z+4.0),
824 -0.1385710331296526 / (z+5.0),
825 0.9934937113930748e-05 / (z+6.0),
826 0.1659470187408462e-06 / (z+7.0),
827 ])
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000828
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000829class TestDistributions(unittest.TestCase):
830 def test_zeroinputs(self):
831 # Verify that distributions can handle a series of zero inputs'
832 g = random.Random()
Guido van Rossum805365e2007-05-07 22:24:25 +0000833 x = [g.random() for i in range(50)] + [0.0]*5
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000834 g.random = x[:].pop; g.uniform(1,10)
835 g.random = x[:].pop; g.paretovariate(1.0)
836 g.random = x[:].pop; g.expovariate(1.0)
837 g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200838 g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000839 g.random = x[:].pop; g.normalvariate(0.0, 1.0)
840 g.random = x[:].pop; g.gauss(0.0, 1.0)
841 g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
842 g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
843 g.random = x[:].pop; g.gammavariate(0.01, 1.0)
844 g.random = x[:].pop; g.gammavariate(1.0, 1.0)
845 g.random = x[:].pop; g.gammavariate(200.0, 1.0)
846 g.random = x[:].pop; g.betavariate(3.0, 3.0)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000847 g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000848
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000849 def test_avg_std(self):
850 # Use integration to test distribution average and standard deviation.
851 # Only works for distributions which do not consume variates in pairs
852 g = random.Random()
853 N = 5000
Guido van Rossum805365e2007-05-07 22:24:25 +0000854 x = [i/float(N) for i in range(1,N)]
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000855 for variate, args, mu, sigmasqrd in [
856 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
Christian Heimesfe337bf2008-03-23 21:54:12 +0000857 (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 +0000858 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200859 (g.vonmisesvariate, (1.23, 0), pi, pi**2/3),
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000860 (g.paretovariate, (5.0,), 5.0/(5.0-1),
861 5.0/((5.0-1)**2*(5.0-2))),
862 (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0),
863 gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
864 g.random = x[:].pop
865 y = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000866 for i in range(len(x)):
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000867 try:
868 y.append(variate(*args))
869 except IndexError:
870 pass
871 s1 = s2 = 0
872 for e in y:
873 s1 += e
874 s2 += (e - mu) ** 2
875 N = len(y)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200876 self.assertAlmostEqual(s1/N, mu, places=2,
877 msg='%s%r' % (variate.__name__, args))
878 self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2,
879 msg='%s%r' % (variate.__name__, args))
880
881 def test_constant(self):
882 g = random.Random()
883 N = 100
884 for variate, args, expected in [
885 (g.uniform, (10.0, 10.0), 10.0),
886 (g.triangular, (10.0, 10.0), 10.0),
Raymond Hettinger978c6ab2014-05-25 17:25:27 -0700887 (g.triangular, (10.0, 10.0, 10.0), 10.0),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200888 (g.expovariate, (float('inf'),), 0.0),
889 (g.vonmisesvariate, (3.0, float('inf')), 3.0),
890 (g.gauss, (10.0, 0.0), 10.0),
891 (g.lognormvariate, (0.0, 0.0), 1.0),
892 (g.lognormvariate, (-float('inf'), 0.0), 0.0),
893 (g.normalvariate, (10.0, 0.0), 10.0),
894 (g.paretovariate, (float('inf'),), 1.0),
895 (g.weibullvariate, (10.0, float('inf')), 10.0),
896 (g.weibullvariate, (0.0, 10.0), 0.0),
897 ]:
898 for i in range(N):
899 self.assertEqual(variate(*args), expected)
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000900
Mark Dickinsonbe5f9192013-02-10 14:16:10 +0000901 def test_von_mises_range(self):
902 # Issue 17149: von mises variates were not consistently in the
903 # range [0, 2*PI].
904 g = random.Random()
905 N = 100
906 for mu in 0.0, 0.1, 3.1, 6.2:
907 for kappa in 0.0, 2.3, 500.0:
908 for _ in range(N):
909 sample = g.vonmisesvariate(mu, kappa)
910 self.assertTrue(
911 0 <= sample <= random.TWOPI,
912 msg=("vonmisesvariate({}, {}) produced a result {} out"
913 " of range [0, 2*pi]").format(mu, kappa, sample))
914
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200915 def test_von_mises_large_kappa(self):
916 # Issue #17141: vonmisesvariate() was hang for large kappas
917 random.vonmisesvariate(0, 1e15)
918 random.vonmisesvariate(0, 1e100)
919
R David Murraye3e1c172013-04-02 12:47:23 -0400920 def test_gammavariate_errors(self):
921 # Both alpha and beta must be > 0.0
922 self.assertRaises(ValueError, random.gammavariate, -1, 3)
923 self.assertRaises(ValueError, random.gammavariate, 0, 2)
924 self.assertRaises(ValueError, random.gammavariate, 2, 0)
925 self.assertRaises(ValueError, random.gammavariate, 1, -3)
926
leodema63d15222018-12-24 07:54:25 +0100927 # There are three different possibilities in the current implementation
928 # of random.gammavariate(), depending on the value of 'alpha'. What we
929 # are going to do here is to fix the values returned by random() to
930 # generate test cases that provide 100% line coverage of the method.
R David Murraye3e1c172013-04-02 12:47:23 -0400931 @unittest.mock.patch('random.Random.random')
leodema63d15222018-12-24 07:54:25 +0100932 def test_gammavariate_alpha_greater_one(self, random_mock):
R David Murraye3e1c172013-04-02 12:47:23 -0400933
leodema63d15222018-12-24 07:54:25 +0100934 # #1: alpha > 1.0.
935 # We want the first random number to be outside the
R David Murraye3e1c172013-04-02 12:47:23 -0400936 # [1e-7, .9999999] range, so that the continue statement executes
937 # once. The values of u1 and u2 will be 0.5 and 0.3, respectively.
938 random_mock.side_effect = [1e-8, 0.5, 0.3]
939 returned_value = random.gammavariate(1.1, 2.3)
940 self.assertAlmostEqual(returned_value, 2.53)
941
leodema63d15222018-12-24 07:54:25 +0100942 @unittest.mock.patch('random.Random.random')
943 def test_gammavariate_alpha_equal_one(self, random_mock):
R David Murraye3e1c172013-04-02 12:47:23 -0400944
leodema63d15222018-12-24 07:54:25 +0100945 # #2.a: alpha == 1.
946 # The execution body of the while loop executes once.
947 # Then random.random() returns 0.45,
948 # which causes while to stop looping and the algorithm to terminate.
949 random_mock.side_effect = [0.45]
950 returned_value = random.gammavariate(1.0, 3.14)
951 self.assertAlmostEqual(returned_value, 1.877208182372648)
952
953 @unittest.mock.patch('random.Random.random')
954 def test_gammavariate_alpha_equal_one_equals_expovariate(self, random_mock):
955
956 # #2.b: alpha == 1.
957 # It must be equivalent of calling expovariate(1.0 / beta).
958 beta = 3.14
959 random_mock.side_effect = [1e-8, 1e-8]
960 gammavariate_returned_value = random.gammavariate(1.0, beta)
961 expovariate_returned_value = random.expovariate(1.0 / beta)
962 self.assertAlmostEqual(gammavariate_returned_value, expovariate_returned_value)
963
964 @unittest.mock.patch('random.Random.random')
965 def test_gammavariate_alpha_between_zero_and_one(self, random_mock):
966
967 # #3: 0 < alpha < 1.
968 # This is the most complex region of code to cover,
R David Murraye3e1c172013-04-02 12:47:23 -0400969 # as there are multiple if-else statements. Let's take a look at the
970 # source code, and determine the values that we need accordingly:
971 #
972 # while 1:
973 # u = random()
974 # b = (_e + alpha)/_e
975 # p = b*u
976 # if p <= 1.0: # <=== (A)
977 # x = p ** (1.0/alpha)
978 # else: # <=== (B)
979 # x = -_log((b-p)/alpha)
980 # u1 = random()
981 # if p > 1.0: # <=== (C)
982 # if u1 <= x ** (alpha - 1.0): # <=== (D)
983 # break
984 # elif u1 <= _exp(-x): # <=== (E)
985 # break
986 # return x * beta
987 #
988 # First, we want (A) to be True. For that we need that:
989 # b*random() <= 1.0
990 # r1 = random() <= 1.0 / b
991 #
992 # We now get to the second if-else branch, and here, since p <= 1.0,
993 # (C) is False and we take the elif branch, (E). For it to be True,
994 # so that the break is executed, we need that:
995 # r2 = random() <= _exp(-x)
996 # r2 <= _exp(-(p ** (1.0/alpha)))
997 # r2 <= _exp(-((b*r1) ** (1.0/alpha)))
998
999 _e = random._e
1000 _exp = random._exp
1001 _log = random._log
1002 alpha = 0.35
1003 beta = 1.45
1004 b = (_e + alpha)/_e
1005 epsilon = 0.01
1006
1007 r1 = 0.8859296441566 # 1.0 / b
1008 r2 = 0.3678794411714 # _exp(-((b*r1) ** (1.0/alpha)))
1009
1010 # These four "random" values result in the following trace:
1011 # (A) True, (E) False --> [next iteration of while]
1012 # (A) True, (E) True --> [while loop breaks]
1013 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
1014 returned_value = random.gammavariate(alpha, beta)
1015 self.assertAlmostEqual(returned_value, 1.4499999999997544)
1016
1017 # Let's now make (A) be False. If this is the case, when we get to the
1018 # second if-else 'p' is greater than 1, so (C) evaluates to True. We
1019 # now encounter a second if statement, (D), which in order to execute
1020 # must satisfy the following condition:
1021 # r2 <= x ** (alpha - 1.0)
1022 # r2 <= (-_log((b-p)/alpha)) ** (alpha - 1.0)
1023 # r2 <= (-_log((b-(b*r1))/alpha)) ** (alpha - 1.0)
1024 r1 = 0.8959296441566 # (1.0 / b) + epsilon -- so that (A) is False
1025 r2 = 0.9445400408898141
1026
1027 # And these four values result in the following trace:
1028 # (B) and (C) True, (D) False --> [next iteration of while]
1029 # (B) and (C) True, (D) True [while loop breaks]
1030 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
1031 returned_value = random.gammavariate(alpha, beta)
1032 self.assertAlmostEqual(returned_value, 1.5830349561760781)
1033
1034 @unittest.mock.patch('random.Random.gammavariate')
1035 def test_betavariate_return_zero(self, gammavariate_mock):
1036 # betavariate() returns zero when the Gamma distribution
1037 # that it uses internally returns this same value.
1038 gammavariate_mock.return_value = 0.0
1039 self.assertEqual(0.0, random.betavariate(2.71828, 3.14159))
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +02001040
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001041
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001042class TestRandomSubclassing(unittest.TestCase):
1043 def test_random_subclass_with_kwargs(self):
1044 # SF bug #1486663 -- this used to erroneously raise a TypeError
1045 class Subclass(random.Random):
1046 def __init__(self, newarg=None):
1047 random.Random.__init__(self)
1048 Subclass(newarg=1)
1049
1050 def test_subclasses_overriding_methods(self):
1051 # Subclasses with an overridden random, but only the original
1052 # getrandbits method should not rely on getrandbits in for randrange,
1053 # but should use a getrandbits-independent implementation instead.
1054
1055 # subclass providing its own random **and** getrandbits methods
1056 # like random.SystemRandom does => keep relying on getrandbits for
1057 # randrange
1058 class SubClass1(random.Random):
1059 def random(self):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001060 called.add('SubClass1.random')
1061 return random.Random.random(self)
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001062
1063 def getrandbits(self, n):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001064 called.add('SubClass1.getrandbits')
1065 return random.Random.getrandbits(self, n)
1066 called = set()
1067 SubClass1().randrange(42)
1068 self.assertEqual(called, {'SubClass1.getrandbits'})
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001069
1070 # subclass providing only random => can only use random for randrange
1071 class SubClass2(random.Random):
1072 def random(self):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001073 called.add('SubClass2.random')
1074 return random.Random.random(self)
1075 called = set()
1076 SubClass2().randrange(42)
1077 self.assertEqual(called, {'SubClass2.random'})
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001078
1079 # subclass defining getrandbits to complement its inherited random
1080 # => can now rely on getrandbits for randrange again
1081 class SubClass3(SubClass2):
1082 def getrandbits(self, n):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001083 called.add('SubClass3.getrandbits')
1084 return random.Random.getrandbits(self, n)
1085 called = set()
1086 SubClass3().randrange(42)
1087 self.assertEqual(called, {'SubClass3.getrandbits'})
1088
1089 # subclass providing only random and inherited getrandbits
1090 # => random takes precedence
1091 class SubClass4(SubClass3):
1092 def random(self):
1093 called.add('SubClass4.random')
1094 return random.Random.random(self)
1095 called = set()
1096 SubClass4().randrange(42)
1097 self.assertEqual(called, {'SubClass4.random'})
1098
1099 # Following subclasses don't define random or getrandbits directly,
1100 # but inherit them from classes which are not subclasses of Random
1101 class Mixin1:
1102 def random(self):
1103 called.add('Mixin1.random')
1104 return random.Random.random(self)
1105 class Mixin2:
1106 def getrandbits(self, n):
1107 called.add('Mixin2.getrandbits')
1108 return random.Random.getrandbits(self, n)
1109
1110 class SubClass5(Mixin1, random.Random):
1111 pass
1112 called = set()
1113 SubClass5().randrange(42)
1114 self.assertEqual(called, {'Mixin1.random'})
1115
1116 class SubClass6(Mixin2, random.Random):
1117 pass
1118 called = set()
1119 SubClass6().randrange(42)
1120 self.assertEqual(called, {'Mixin2.getrandbits'})
1121
1122 class SubClass7(Mixin1, Mixin2, random.Random):
1123 pass
1124 called = set()
1125 SubClass7().randrange(42)
1126 self.assertEqual(called, {'Mixin1.random'})
1127
1128 class SubClass8(Mixin2, Mixin1, random.Random):
1129 pass
1130 called = set()
1131 SubClass8().randrange(42)
1132 self.assertEqual(called, {'Mixin2.getrandbits'})
1133
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001134
Raymond Hettinger40f62172002-12-29 23:03:38 +00001135class TestModule(unittest.TestCase):
1136 def testMagicConstants(self):
1137 self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141)
1138 self.assertAlmostEqual(random.TWOPI, 6.28318530718)
1139 self.assertAlmostEqual(random.LOG4, 1.38629436111989)
1140 self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627)
1141
1142 def test__all__(self):
1143 # tests validity but not completeness of the __all__ list
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001144 self.assertTrue(set(random.__all__) <= set(dir(random)))
Raymond Hettinger40f62172002-12-29 23:03:38 +00001145
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001146 @unittest.skipUnless(hasattr(os, "fork"), "fork() required")
1147 def test_after_fork(self):
1148 # Test the global Random instance gets reseeded in child
1149 r, w = os.pipe()
Victor Stinnerda5e9302017-08-09 17:59:05 +02001150 pid = os.fork()
1151 if pid == 0:
1152 # child process
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001153 try:
1154 val = random.getrandbits(128)
1155 with open(w, "w") as f:
1156 f.write(str(val))
1157 finally:
1158 os._exit(0)
1159 else:
Victor Stinnerda5e9302017-08-09 17:59:05 +02001160 # parent process
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001161 os.close(w)
1162 val = random.getrandbits(128)
1163 with open(r, "r") as f:
1164 child_val = eval(f.read())
1165 self.assertNotEqual(val, child_val)
1166
Victor Stinner278c1e12020-03-31 20:08:12 +02001167 support.wait_process(pid, exitcode=0)
Victor Stinnerda5e9302017-08-09 17:59:05 +02001168
Thomas Woutersb2137042007-02-01 18:02:27 +00001169
Raymond Hettinger40f62172002-12-29 23:03:38 +00001170if __name__ == "__main__":
Ezio Melotti3e4a98b2013-04-19 05:45:27 +03001171 unittest.main()