blob: f709e52ecb80533338003608ab477cf4c4d4a8ca [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
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000266 def test_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200267 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
268 state = pickle.dumps(self.gen, proto)
269 origseq = [self.gen.random() for i in range(10)]
270 newgen = pickle.loads(state)
271 restoredseq = [newgen.random() for i in range(10)]
272 self.assertEqual(origseq, restoredseq)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000273
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000274 def test_bug_1727780(self):
275 # verify that version-2-pickles can be loaded
276 # fine, whether they are created on 32-bit or 64-bit
277 # platforms, and that version-3-pickles load fine.
278 files = [("randv2_32.pck", 780),
279 ("randv2_64.pck", 866),
280 ("randv3.pck", 343)]
281 for file, value in files:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +0200282 with open(support.findfile(file),"rb") as f:
283 r = pickle.load(f)
Raymond Hettinger05156612010-09-07 04:44:52 +0000284 self.assertEqual(int(r.random()*1000), value)
285
286 def test_bug_9025(self):
287 # Had problem with an uneven distribution in int(n*random())
288 # Verify the fix by checking that distributions fall within expectations.
289 n = 100000
290 randrange = self.gen.randrange
291 k = sum(randrange(6755399441055744) % 3 == 2 for i in range(n))
292 self.assertTrue(0.30 < k/n < .37, (k/n))
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000293
Victor Stinner9f5fe792020-04-17 19:05:35 +0200294 def test_randbytes(self):
295 # Verify ranges
296 for n in range(1, 10):
297 data = self.gen.randbytes(n)
298 self.assertEqual(type(data), bytes)
299 self.assertEqual(len(data), n)
300
301 self.assertEqual(self.gen.randbytes(0), b'')
302
303 # Verify argument checking
304 self.assertRaises(TypeError, self.gen.randbytes)
305 self.assertRaises(TypeError, self.gen.randbytes, 1, 2)
306 self.assertRaises(ValueError, self.gen.randbytes, -1)
307 self.assertRaises(TypeError, self.gen.randbytes, 1.0)
308
309
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300310try:
311 random.SystemRandom().random()
312except NotImplementedError:
313 SystemRandom_available = False
314else:
315 SystemRandom_available = True
316
317@unittest.skipUnless(SystemRandom_available, "random.SystemRandom not available")
318class SystemRandom_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000319 gen = random.SystemRandom()
Raymond Hettinger356a4592004-08-30 06:14:31 +0000320
321 def test_autoseed(self):
322 # Doesn't need to do anything except not fail
323 self.gen.seed()
324
325 def test_saverestore(self):
326 self.assertRaises(NotImplementedError, self.gen.getstate)
327 self.assertRaises(NotImplementedError, self.gen.setstate, None)
328
329 def test_seedargs(self):
330 # Doesn't need to do anything except not fail
331 self.gen.seed(100)
332
Raymond Hettinger356a4592004-08-30 06:14:31 +0000333 def test_gauss(self):
334 self.gen.gauss_next = None
335 self.gen.seed(100)
336 self.assertEqual(self.gen.gauss_next, None)
337
338 def test_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200339 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
340 self.assertRaises(NotImplementedError, pickle.dumps, self.gen, proto)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000341
342 def test_53_bits_per_float(self):
343 # This should pass whenever a C double has 53 bit precision.
344 span = 2 ** 53
345 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000346 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000347 cum |= int(self.gen.random() * span)
348 self.assertEqual(cum, span-1)
349
350 def test_bigrand(self):
351 # The randrange routine should build-up the required number of bits
352 # in stages so that all bit positions are active.
353 span = 2 ** 500
354 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000355 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000356 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000357 self.assertTrue(0 <= r < span)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000358 cum |= r
359 self.assertEqual(cum, span-1)
360
361 def test_bigrand_ranges(self):
362 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600363 start = self.gen.randrange(2 ** (i-2))
364 stop = self.gen.randrange(2 ** i)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000365 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600366 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000367 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000368
369 def test_rangelimits(self):
370 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
371 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000372 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000373
R David Murraye3e1c172013-04-02 12:47:23 -0400374 def test_randrange_nonunit_step(self):
375 rint = self.gen.randrange(0, 10, 2)
376 self.assertIn(rint, (0, 2, 4, 6, 8))
377 rint = self.gen.randrange(0, 2, 2)
378 self.assertEqual(rint, 0)
379
380 def test_randrange_errors(self):
381 raises = partial(self.assertRaises, ValueError, self.gen.randrange)
382 # Empty range
383 raises(3, 3)
384 raises(-721)
385 raises(0, 100, -12)
386 # Non-integer start/stop
387 raises(3.14159)
388 raises(0, 2.71828)
389 # Zero and non-integer step
390 raises(0, 42, 0)
391 raises(0, 42, 3.14159)
392
Raymond Hettinger356a4592004-08-30 06:14:31 +0000393 def test_genrandbits(self):
394 # Verify ranges
Guido van Rossum805365e2007-05-07 22:24:25 +0000395 for k in range(1, 1000):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000396 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000397
398 # Verify all bits active
399 getbits = self.gen.getrandbits
400 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
401 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000402 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000403 cum |= getbits(span)
404 self.assertEqual(cum, 2**span-1)
405
406 # Verify argument checking
407 self.assertRaises(TypeError, self.gen.getrandbits)
408 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
409 self.assertRaises(ValueError, self.gen.getrandbits, 0)
410 self.assertRaises(ValueError, self.gen.getrandbits, -1)
411 self.assertRaises(TypeError, self.gen.getrandbits, 10.1)
412
413 def test_randbelow_logic(self, _log=log, int=int):
414 # check bitcount transition points: 2**i and 2**(i+1)-1
415 # show that: k = int(1.001 + _log(n, 2))
416 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000417 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000418 n = 1 << i # check an exact power of two
Raymond Hettinger356a4592004-08-30 06:14:31 +0000419 numbits = i+1
420 k = int(1.00001 + _log(n, 2))
421 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000422 self.assertEqual(n, 2**(k-1))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000423
424 n += n - 1 # check 1 below the next power of two
425 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000426 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000427 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000428
429 n -= n >> 15 # check a little farther below the next power of two
430 k = int(1.00001 + _log(n, 2))
431 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000432 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger356a4592004-08-30 06:14:31 +0000433
434
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300435class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger40f62172002-12-29 23:03:38 +0000436 gen = random.Random()
437
Raymond Hettingerf763a722010-09-07 00:38:15 +0000438 def test_guaranteed_stable(self):
439 # These sequences are guaranteed to stay the same across versions of python
440 self.gen.seed(3456147, version=1)
441 self.assertEqual([self.gen.random().hex() for i in range(4)],
442 ['0x1.ac362300d90d2p-1', '0x1.9d16f74365005p-1',
443 '0x1.1ebb4352e4c4dp-1', '0x1.1a7422abf9c11p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000444 self.gen.seed("the quick brown fox", version=2)
445 self.assertEqual([self.gen.random().hex() for i in range(4)],
Raymond Hettinger3fcf0022010-12-08 01:13:53 +0000446 ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4',
447 '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000448
Raymond Hettingerc7bab7c2016-08-31 15:01:08 -0700449 def test_bug_27706(self):
450 # Verify that version 1 seeds are unaffected by hash randomization
451
452 self.gen.seed('nofar', version=1) # hash('nofar') == 5990528763808513177
453 self.assertEqual([self.gen.random().hex() for i in range(4)],
454 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
455 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
456
457 self.gen.seed('rachel', version=1) # hash('rachel') == -9091735575445484789
458 self.assertEqual([self.gen.random().hex() for i in range(4)],
459 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
460 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
461
462 self.gen.seed('', version=1) # hash('') == 0
463 self.assertEqual([self.gen.random().hex() for i in range(4)],
464 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
465 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
466
Oren Milmand780b2d2017-09-28 10:50:01 +0300467 def test_bug_31478(self):
468 # There shouldn't be an assertion failure in _random.Random.seed() in
469 # case the argument has a bad __abs__() method.
470 class BadInt(int):
471 def __abs__(self):
472 return None
473 try:
474 self.gen.seed(BadInt())
475 except TypeError:
476 pass
477
Raymond Hettinger132a7d72017-09-17 09:04:30 -0700478 def test_bug_31482(self):
479 # Verify that version 1 seeds are unaffected by hash randomization
480 # when the seeds are expressed as bytes rather than strings.
481 # The hash(b) values listed are the Python2.7 hash() values
482 # which were used for seeding.
483
484 self.gen.seed(b'nofar', version=1) # hash('nofar') == 5990528763808513177
485 self.assertEqual([self.gen.random().hex() for i in range(4)],
486 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
487 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
488
489 self.gen.seed(b'rachel', version=1) # hash('rachel') == -9091735575445484789
490 self.assertEqual([self.gen.random().hex() for i in range(4)],
491 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
492 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
493
494 self.gen.seed(b'', version=1) # hash('') == 0
495 self.assertEqual([self.gen.random().hex() for i in range(4)],
496 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
497 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
498
499 b = b'\x00\x20\x40\x60\x80\xA0\xC0\xE0\xF0'
500 self.gen.seed(b, version=1) # hash(b) == 5015594239749365497
501 self.assertEqual([self.gen.random().hex() for i in range(4)],
502 ['0x1.52c2fde444d23p-1', '0x1.875174f0daea4p-2',
503 '0x1.9e9b2c50e5cd2p-1', '0x1.fa57768bd321cp-2'])
504
Raymond Hettinger58335872004-07-09 14:26:18 +0000505 def test_setstate_first_arg(self):
506 self.assertRaises(ValueError, self.gen.setstate, (1, None, None))
507
508 def test_setstate_middle_arg(self):
bladebryan9616a822017-04-21 23:10:46 -0700509 start_state = self.gen.getstate()
Raymond Hettinger58335872004-07-09 14:26:18 +0000510 # Wrong type, s/b tuple
511 self.assertRaises(TypeError, self.gen.setstate, (2, None, None))
512 # Wrong length, s/b 625
513 self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None))
514 # Wrong type, s/b tuple of 625 ints
515 self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None))
516 # Last element s/b an int also
517 self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None))
Serhiy Storchaka178f0b62015-07-24 09:02:53 +0300518 # Last element s/b between 0 and 624
519 with self.assertRaises((ValueError, OverflowError)):
520 self.gen.setstate((2, (1,)*624+(625,), None))
521 with self.assertRaises((ValueError, OverflowError)):
522 self.gen.setstate((2, (1,)*624+(-1,), None))
bladebryan9616a822017-04-21 23:10:46 -0700523 # Failed calls to setstate() should not have changed the state.
524 bits100 = self.gen.getrandbits(100)
525 self.gen.setstate(start_state)
526 self.assertEqual(self.gen.getrandbits(100), bits100)
Raymond Hettinger58335872004-07-09 14:26:18 +0000527
R David Murraye3e1c172013-04-02 12:47:23 -0400528 # Little trick to make "tuple(x % (2**32) for x in internalstate)"
529 # raise ValueError. I cannot think of a simple way to achieve this, so
530 # I am opting for using a generator as the middle argument of setstate
531 # which attempts to cast a NaN to integer.
532 state_values = self.gen.getstate()[1]
533 state_values = list(state_values)
534 state_values[-1] = float('nan')
535 state = (int(x) for x in state_values)
536 self.assertRaises(TypeError, self.gen.setstate, (2, state, None))
537
Raymond Hettinger40f62172002-12-29 23:03:38 +0000538 def test_referenceImplementation(self):
539 # Compare the python implementation with results from the original
540 # code. Create 2000 53-bit precision random floats. Compare only
541 # the last ten entries to show that the independent implementations
542 # are tracking. Here is the main() function needed to create the
543 # list of expected random numbers:
544 # void main(void){
545 # int i;
546 # unsigned long init[4]={61731, 24903, 614, 42143}, length=4;
547 # init_by_array(init, length);
548 # for (i=0; i<2000; i++) {
549 # printf("%.15f ", genrand_res53());
550 # if (i%5==4) printf("\n");
551 # }
552 # }
553 expected = [0.45839803073713259,
554 0.86057815201978782,
555 0.92848331726782152,
556 0.35932681119782461,
557 0.081823493762449573,
558 0.14332226470169329,
559 0.084297823823520024,
560 0.53814864671831453,
561 0.089215024911993401,
562 0.78486196105372907]
563
Guido van Rossume2a383d2007-01-15 16:59:06 +0000564 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000565 actual = self.randomlist(2000)[-10:]
566 for a, e in zip(actual, expected):
567 self.assertAlmostEqual(a,e,places=14)
568
569 def test_strong_reference_implementation(self):
570 # Like test_referenceImplementation, but checks for exact bit-level
571 # equality. This should pass on any box where C double contains
572 # at least 53 bits of precision (the underlying algorithm suffers
573 # no rounding errors -- all results are exact).
574 from math import ldexp
575
Guido van Rossume2a383d2007-01-15 16:59:06 +0000576 expected = [0x0eab3258d2231f,
577 0x1b89db315277a5,
578 0x1db622a5518016,
579 0x0b7f9af0d575bf,
580 0x029e4c4db82240,
581 0x04961892f5d673,
582 0x02b291598e4589,
583 0x11388382c15694,
584 0x02dad977c9e1fe,
585 0x191d96d4d334c6]
586 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000587 actual = self.randomlist(2000)[-10:]
588 for a, e in zip(actual, expected):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000589 self.assertEqual(int(ldexp(a, 53)), e)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000590
591 def test_long_seed(self):
592 # This is most interesting to run in debug mode, just to make sure
593 # nothing blows up. Under the covers, a dynamically resized array
594 # is allocated, consuming space proportional to the number of bits
595 # in the seed. Unfortunately, that's a quadratic-time algorithm,
596 # so don't make this horribly big.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000597 seed = (1 << (10000 * 8)) - 1 # about 10K bytes
Raymond Hettinger40f62172002-12-29 23:03:38 +0000598 self.gen.seed(seed)
599
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000600 def test_53_bits_per_float(self):
601 # This should pass whenever a C double has 53 bit precision.
602 span = 2 ** 53
603 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000604 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000605 cum |= int(self.gen.random() * span)
606 self.assertEqual(cum, span-1)
607
608 def test_bigrand(self):
609 # The randrange routine should build-up the required number of bits
610 # in stages so that all bit positions are active.
611 span = 2 ** 500
612 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000613 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000614 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000615 self.assertTrue(0 <= r < span)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000616 cum |= r
617 self.assertEqual(cum, span-1)
618
619 def test_bigrand_ranges(self):
620 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600621 start = self.gen.randrange(2 ** (i-2))
622 stop = self.gen.randrange(2 ** i)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000623 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600624 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000625 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000626
627 def test_rangelimits(self):
628 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
Raymond Hettingera690a992003-11-16 16:17:49 +0000629 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000630 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000631
632 def test_genrandbits(self):
633 # Verify cross-platform repeatability
634 self.gen.seed(1234567)
635 self.assertEqual(self.gen.getrandbits(100),
Guido van Rossume2a383d2007-01-15 16:59:06 +0000636 97904845777343510404718956115)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000637 # Verify ranges
Guido van Rossum805365e2007-05-07 22:24:25 +0000638 for k in range(1, 1000):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000639 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000640
641 # Verify all bits active
642 getbits = self.gen.getrandbits
643 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
644 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000645 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000646 cum |= getbits(span)
647 self.assertEqual(cum, 2**span-1)
648
Raymond Hettinger58335872004-07-09 14:26:18 +0000649 # Verify argument checking
650 self.assertRaises(TypeError, self.gen.getrandbits)
651 self.assertRaises(TypeError, self.gen.getrandbits, 'a')
652 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
653 self.assertRaises(ValueError, self.gen.getrandbits, 0)
654 self.assertRaises(ValueError, self.gen.getrandbits, -1)
655
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200656 def test_randrange_uses_getrandbits(self):
657 # Verify use of getrandbits by randrange
658 # Use same seed as in the cross-platform repeatability test
659 # in test_genrandbits above.
660 self.gen.seed(1234567)
661 # If randrange uses getrandbits, it should pick getrandbits(100)
662 # when called with a 100-bits stop argument.
663 self.assertEqual(self.gen.randrange(2**99),
664 97904845777343510404718956115)
665
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000666 def test_randbelow_logic(self, _log=log, int=int):
667 # check bitcount transition points: 2**i and 2**(i+1)-1
668 # show that: k = int(1.001 + _log(n, 2))
669 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000670 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000671 n = 1 << i # check an exact power of two
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000672 numbits = i+1
673 k = int(1.00001 + _log(n, 2))
674 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000675 self.assertEqual(n, 2**(k-1))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000676
677 n += n - 1 # check 1 below the next power of two
678 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000679 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000680 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000681
682 n -= n >> 15 # check a little farther below the next power of two
683 k = int(1.00001 + _log(n, 2))
684 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000685 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000686
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200687 def test_randbelow_without_getrandbits(self):
R David Murraye3e1c172013-04-02 12:47:23 -0400688 # Random._randbelow() can only use random() when the built-in one
689 # has been overridden but no new getrandbits() method was supplied.
R David Murraye3e1c172013-04-02 12:47:23 -0400690 maxsize = 1<<random.BPF
691 with warnings.catch_warnings():
692 warnings.simplefilter("ignore", UserWarning)
693 # Population range too large (n >= maxsize)
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200694 self.gen._randbelow_without_getrandbits(
695 maxsize+1, maxsize=maxsize
696 )
697 self.gen._randbelow_without_getrandbits(5640, maxsize=maxsize)
Wolfgang Maier091e95e2018-04-05 17:19:44 +0200698 # issue 33203: test that _randbelow raises ValueError on
699 # n == 0 also in its getrandbits-independent branch.
700 with self.assertRaises(ValueError):
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200701 self.gen._randbelow_without_getrandbits(0, maxsize=maxsize)
702
R David Murraye3e1c172013-04-02 12:47:23 -0400703 # This might be going too far to test a single line, but because of our
704 # noble aim of achieving 100% test coverage we need to write a case in
705 # which the following line in Random._randbelow() gets executed:
706 #
707 # rem = maxsize % n
708 # limit = (maxsize - rem) / maxsize
709 # r = random()
710 # while r >= limit:
711 # r = random() # <== *This line* <==<
712 #
713 # Therefore, to guarantee that the while loop is executed at least
714 # once, we need to mock random() so that it returns a number greater
715 # than 'limit' the first time it gets called.
716
717 n = 42
718 epsilon = 0.01
719 limit = (maxsize - (maxsize % n)) / maxsize
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200720 with unittest.mock.patch.object(random.Random, 'random') as random_mock:
721 random_mock.side_effect = [limit + epsilon, limit - epsilon]
722 self.gen._randbelow_without_getrandbits(n, maxsize=maxsize)
723 self.assertEqual(random_mock.call_count, 2)
R David Murraye3e1c172013-04-02 12:47:23 -0400724
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000725 def test_randrange_bug_1590891(self):
726 start = 1000000000000
727 stop = -100000000000000000000
728 step = -200
729 x = self.gen.randrange(start, stop, step)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000730 self.assertTrue(stop < x <= start)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000731 self.assertEqual((x+stop)%step, 0)
732
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700733 def test_choices_algorithms(self):
Raymond Hettinger24e42392016-11-13 00:42:56 -0500734 # The various ways of specifying weights should produce the same results
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700735 choices = self.gen.choices
Raymond Hettinger6023d332016-11-21 15:32:08 -0800736 n = 104729
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700737
738 self.gen.seed(8675309)
739 a = self.gen.choices(range(n), k=10000)
740
741 self.gen.seed(8675309)
742 b = self.gen.choices(range(n), [1]*n, k=10000)
743 self.assertEqual(a, b)
744
745 self.gen.seed(8675309)
746 c = self.gen.choices(range(n), cum_weights=range(1, n+1), k=10000)
747 self.assertEqual(a, c)
748
penguindustin96466302019-05-06 14:57:17 -0400749 # American Roulette
Raymond Hettinger77d574d2016-10-29 17:42:36 -0700750 population = ['Red', 'Black', 'Green']
751 weights = [18, 18, 2]
752 cum_weights = [18, 36, 38]
753 expanded_population = ['Red'] * 18 + ['Black'] * 18 + ['Green'] * 2
754
755 self.gen.seed(9035768)
756 a = self.gen.choices(expanded_population, k=10000)
757
758 self.gen.seed(9035768)
759 b = self.gen.choices(population, weights, k=10000)
760 self.assertEqual(a, b)
761
762 self.gen.seed(9035768)
763 c = self.gen.choices(population, cum_weights=cum_weights, k=10000)
764 self.assertEqual(a, c)
765
Victor Stinner9f5fe792020-04-17 19:05:35 +0200766 def test_randbytes(self):
767 super().test_randbytes()
768
769 # Mersenne Twister randbytes() is deterministic
770 # and does not depend on the endian and bitness.
771 seed = 8675309
772 expected = b'f\xf9\xa836\xd0\xa4\xf4\x82\x9f\x8f\x19\xf0eo\x02'
773
774 self.gen.seed(seed)
775 self.assertEqual(self.gen.randbytes(16), expected)
776
777 # randbytes(0) must not consume any entropy
778 self.gen.seed(seed)
779 self.assertEqual(self.gen.randbytes(0), b'')
780 self.assertEqual(self.gen.randbytes(16), expected)
781
782 # Four randbytes(4) calls give the same output than randbytes(16)
783 self.gen.seed(seed)
784 self.assertEqual(b''.join([self.gen.randbytes(4) for _ in range(4)]),
785 expected)
786
787 # Each randbytes(2) or randbytes(3) call consumes 4 bytes of entropy
788 self.gen.seed(seed)
789 expected2 = b''.join(expected[i:i + 2]
790 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)
795 expected3 = b''.join(expected[i:i + 3]
796 for i in range(0, len(expected), 4))
797 self.assertEqual(b''.join(self.gen.randbytes(3) for _ in range(4)),
798 expected3)
799
800
Raymond Hettinger2d0c2562009-02-19 09:53:18 +0000801def gamma(z, sqrt2pi=(2.0*pi)**0.5):
802 # Reflection to right half of complex plane
803 if z < 0.5:
804 return pi / sin(pi*z) / gamma(1.0-z)
805 # Lanczos approximation with g=7
806 az = z + (7.0 - 0.5)
807 return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
808 0.9999999999995183,
809 676.5203681218835 / z,
810 -1259.139216722289 / (z+1.0),
811 771.3234287757674 / (z+2.0),
812 -176.6150291498386 / (z+3.0),
813 12.50734324009056 / (z+4.0),
814 -0.1385710331296526 / (z+5.0),
815 0.9934937113930748e-05 / (z+6.0),
816 0.1659470187408462e-06 / (z+7.0),
817 ])
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000818
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000819class TestDistributions(unittest.TestCase):
820 def test_zeroinputs(self):
821 # Verify that distributions can handle a series of zero inputs'
822 g = random.Random()
Guido van Rossum805365e2007-05-07 22:24:25 +0000823 x = [g.random() for i in range(50)] + [0.0]*5
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000824 g.random = x[:].pop; g.uniform(1,10)
825 g.random = x[:].pop; g.paretovariate(1.0)
826 g.random = x[:].pop; g.expovariate(1.0)
827 g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200828 g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000829 g.random = x[:].pop; g.normalvariate(0.0, 1.0)
830 g.random = x[:].pop; g.gauss(0.0, 1.0)
831 g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
832 g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
833 g.random = x[:].pop; g.gammavariate(0.01, 1.0)
834 g.random = x[:].pop; g.gammavariate(1.0, 1.0)
835 g.random = x[:].pop; g.gammavariate(200.0, 1.0)
836 g.random = x[:].pop; g.betavariate(3.0, 3.0)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000837 g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000838
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000839 def test_avg_std(self):
840 # Use integration to test distribution average and standard deviation.
841 # Only works for distributions which do not consume variates in pairs
842 g = random.Random()
843 N = 5000
Guido van Rossum805365e2007-05-07 22:24:25 +0000844 x = [i/float(N) for i in range(1,N)]
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000845 for variate, args, mu, sigmasqrd in [
846 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
Christian Heimesfe337bf2008-03-23 21:54:12 +0000847 (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 +0000848 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200849 (g.vonmisesvariate, (1.23, 0), pi, pi**2/3),
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000850 (g.paretovariate, (5.0,), 5.0/(5.0-1),
851 5.0/((5.0-1)**2*(5.0-2))),
852 (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0),
853 gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
854 g.random = x[:].pop
855 y = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000856 for i in range(len(x)):
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000857 try:
858 y.append(variate(*args))
859 except IndexError:
860 pass
861 s1 = s2 = 0
862 for e in y:
863 s1 += e
864 s2 += (e - mu) ** 2
865 N = len(y)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200866 self.assertAlmostEqual(s1/N, mu, places=2,
867 msg='%s%r' % (variate.__name__, args))
868 self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2,
869 msg='%s%r' % (variate.__name__, args))
870
871 def test_constant(self):
872 g = random.Random()
873 N = 100
874 for variate, args, expected in [
875 (g.uniform, (10.0, 10.0), 10.0),
876 (g.triangular, (10.0, 10.0), 10.0),
Raymond Hettinger978c6ab2014-05-25 17:25:27 -0700877 (g.triangular, (10.0, 10.0, 10.0), 10.0),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200878 (g.expovariate, (float('inf'),), 0.0),
879 (g.vonmisesvariate, (3.0, float('inf')), 3.0),
880 (g.gauss, (10.0, 0.0), 10.0),
881 (g.lognormvariate, (0.0, 0.0), 1.0),
882 (g.lognormvariate, (-float('inf'), 0.0), 0.0),
883 (g.normalvariate, (10.0, 0.0), 10.0),
884 (g.paretovariate, (float('inf'),), 1.0),
885 (g.weibullvariate, (10.0, float('inf')), 10.0),
886 (g.weibullvariate, (0.0, 10.0), 0.0),
887 ]:
888 for i in range(N):
889 self.assertEqual(variate(*args), expected)
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000890
Mark Dickinsonbe5f9192013-02-10 14:16:10 +0000891 def test_von_mises_range(self):
892 # Issue 17149: von mises variates were not consistently in the
893 # range [0, 2*PI].
894 g = random.Random()
895 N = 100
896 for mu in 0.0, 0.1, 3.1, 6.2:
897 for kappa in 0.0, 2.3, 500.0:
898 for _ in range(N):
899 sample = g.vonmisesvariate(mu, kappa)
900 self.assertTrue(
901 0 <= sample <= random.TWOPI,
902 msg=("vonmisesvariate({}, {}) produced a result {} out"
903 " of range [0, 2*pi]").format(mu, kappa, sample))
904
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200905 def test_von_mises_large_kappa(self):
906 # Issue #17141: vonmisesvariate() was hang for large kappas
907 random.vonmisesvariate(0, 1e15)
908 random.vonmisesvariate(0, 1e100)
909
R David Murraye3e1c172013-04-02 12:47:23 -0400910 def test_gammavariate_errors(self):
911 # Both alpha and beta must be > 0.0
912 self.assertRaises(ValueError, random.gammavariate, -1, 3)
913 self.assertRaises(ValueError, random.gammavariate, 0, 2)
914 self.assertRaises(ValueError, random.gammavariate, 2, 0)
915 self.assertRaises(ValueError, random.gammavariate, 1, -3)
916
leodema63d15222018-12-24 07:54:25 +0100917 # There are three different possibilities in the current implementation
918 # of random.gammavariate(), depending on the value of 'alpha'. What we
919 # are going to do here is to fix the values returned by random() to
920 # generate test cases that provide 100% line coverage of the method.
R David Murraye3e1c172013-04-02 12:47:23 -0400921 @unittest.mock.patch('random.Random.random')
leodema63d15222018-12-24 07:54:25 +0100922 def test_gammavariate_alpha_greater_one(self, random_mock):
R David Murraye3e1c172013-04-02 12:47:23 -0400923
leodema63d15222018-12-24 07:54:25 +0100924 # #1: alpha > 1.0.
925 # We want the first random number to be outside the
R David Murraye3e1c172013-04-02 12:47:23 -0400926 # [1e-7, .9999999] range, so that the continue statement executes
927 # once. The values of u1 and u2 will be 0.5 and 0.3, respectively.
928 random_mock.side_effect = [1e-8, 0.5, 0.3]
929 returned_value = random.gammavariate(1.1, 2.3)
930 self.assertAlmostEqual(returned_value, 2.53)
931
leodema63d15222018-12-24 07:54:25 +0100932 @unittest.mock.patch('random.Random.random')
933 def test_gammavariate_alpha_equal_one(self, random_mock):
R David Murraye3e1c172013-04-02 12:47:23 -0400934
leodema63d15222018-12-24 07:54:25 +0100935 # #2.a: alpha == 1.
936 # The execution body of the while loop executes once.
937 # Then random.random() returns 0.45,
938 # which causes while to stop looping and the algorithm to terminate.
939 random_mock.side_effect = [0.45]
940 returned_value = random.gammavariate(1.0, 3.14)
941 self.assertAlmostEqual(returned_value, 1.877208182372648)
942
943 @unittest.mock.patch('random.Random.random')
944 def test_gammavariate_alpha_equal_one_equals_expovariate(self, random_mock):
945
946 # #2.b: alpha == 1.
947 # It must be equivalent of calling expovariate(1.0 / beta).
948 beta = 3.14
949 random_mock.side_effect = [1e-8, 1e-8]
950 gammavariate_returned_value = random.gammavariate(1.0, beta)
951 expovariate_returned_value = random.expovariate(1.0 / beta)
952 self.assertAlmostEqual(gammavariate_returned_value, expovariate_returned_value)
953
954 @unittest.mock.patch('random.Random.random')
955 def test_gammavariate_alpha_between_zero_and_one(self, random_mock):
956
957 # #3: 0 < alpha < 1.
958 # This is the most complex region of code to cover,
R David Murraye3e1c172013-04-02 12:47:23 -0400959 # as there are multiple if-else statements. Let's take a look at the
960 # source code, and determine the values that we need accordingly:
961 #
962 # while 1:
963 # u = random()
964 # b = (_e + alpha)/_e
965 # p = b*u
966 # if p <= 1.0: # <=== (A)
967 # x = p ** (1.0/alpha)
968 # else: # <=== (B)
969 # x = -_log((b-p)/alpha)
970 # u1 = random()
971 # if p > 1.0: # <=== (C)
972 # if u1 <= x ** (alpha - 1.0): # <=== (D)
973 # break
974 # elif u1 <= _exp(-x): # <=== (E)
975 # break
976 # return x * beta
977 #
978 # First, we want (A) to be True. For that we need that:
979 # b*random() <= 1.0
980 # r1 = random() <= 1.0 / b
981 #
982 # We now get to the second if-else branch, and here, since p <= 1.0,
983 # (C) is False and we take the elif branch, (E). For it to be True,
984 # so that the break is executed, we need that:
985 # r2 = random() <= _exp(-x)
986 # r2 <= _exp(-(p ** (1.0/alpha)))
987 # r2 <= _exp(-((b*r1) ** (1.0/alpha)))
988
989 _e = random._e
990 _exp = random._exp
991 _log = random._log
992 alpha = 0.35
993 beta = 1.45
994 b = (_e + alpha)/_e
995 epsilon = 0.01
996
997 r1 = 0.8859296441566 # 1.0 / b
998 r2 = 0.3678794411714 # _exp(-((b*r1) ** (1.0/alpha)))
999
1000 # These four "random" values result in the following trace:
1001 # (A) True, (E) False --> [next iteration of while]
1002 # (A) True, (E) True --> [while loop breaks]
1003 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
1004 returned_value = random.gammavariate(alpha, beta)
1005 self.assertAlmostEqual(returned_value, 1.4499999999997544)
1006
1007 # Let's now make (A) be False. If this is the case, when we get to the
1008 # second if-else 'p' is greater than 1, so (C) evaluates to True. We
1009 # now encounter a second if statement, (D), which in order to execute
1010 # must satisfy the following condition:
1011 # r2 <= x ** (alpha - 1.0)
1012 # r2 <= (-_log((b-p)/alpha)) ** (alpha - 1.0)
1013 # r2 <= (-_log((b-(b*r1))/alpha)) ** (alpha - 1.0)
1014 r1 = 0.8959296441566 # (1.0 / b) + epsilon -- so that (A) is False
1015 r2 = 0.9445400408898141
1016
1017 # And these four values result in the following trace:
1018 # (B) and (C) True, (D) False --> [next iteration of while]
1019 # (B) and (C) True, (D) True [while loop breaks]
1020 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
1021 returned_value = random.gammavariate(alpha, beta)
1022 self.assertAlmostEqual(returned_value, 1.5830349561760781)
1023
1024 @unittest.mock.patch('random.Random.gammavariate')
1025 def test_betavariate_return_zero(self, gammavariate_mock):
1026 # betavariate() returns zero when the Gamma distribution
1027 # that it uses internally returns this same value.
1028 gammavariate_mock.return_value = 0.0
1029 self.assertEqual(0.0, random.betavariate(2.71828, 3.14159))
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +02001030
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001031
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001032class TestRandomSubclassing(unittest.TestCase):
1033 def test_random_subclass_with_kwargs(self):
1034 # SF bug #1486663 -- this used to erroneously raise a TypeError
1035 class Subclass(random.Random):
1036 def __init__(self, newarg=None):
1037 random.Random.__init__(self)
1038 Subclass(newarg=1)
1039
1040 def test_subclasses_overriding_methods(self):
1041 # Subclasses with an overridden random, but only the original
1042 # getrandbits method should not rely on getrandbits in for randrange,
1043 # but should use a getrandbits-independent implementation instead.
1044
1045 # subclass providing its own random **and** getrandbits methods
1046 # like random.SystemRandom does => keep relying on getrandbits for
1047 # randrange
1048 class SubClass1(random.Random):
1049 def random(self):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001050 called.add('SubClass1.random')
1051 return random.Random.random(self)
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001052
1053 def getrandbits(self, n):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001054 called.add('SubClass1.getrandbits')
1055 return random.Random.getrandbits(self, n)
1056 called = set()
1057 SubClass1().randrange(42)
1058 self.assertEqual(called, {'SubClass1.getrandbits'})
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001059
1060 # subclass providing only random => can only use random for randrange
1061 class SubClass2(random.Random):
1062 def random(self):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001063 called.add('SubClass2.random')
1064 return random.Random.random(self)
1065 called = set()
1066 SubClass2().randrange(42)
1067 self.assertEqual(called, {'SubClass2.random'})
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001068
1069 # subclass defining getrandbits to complement its inherited random
1070 # => can now rely on getrandbits for randrange again
1071 class SubClass3(SubClass2):
1072 def getrandbits(self, n):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001073 called.add('SubClass3.getrandbits')
1074 return random.Random.getrandbits(self, n)
1075 called = set()
1076 SubClass3().randrange(42)
1077 self.assertEqual(called, {'SubClass3.getrandbits'})
1078
1079 # subclass providing only random and inherited getrandbits
1080 # => random takes precedence
1081 class SubClass4(SubClass3):
1082 def random(self):
1083 called.add('SubClass4.random')
1084 return random.Random.random(self)
1085 called = set()
1086 SubClass4().randrange(42)
1087 self.assertEqual(called, {'SubClass4.random'})
1088
1089 # Following subclasses don't define random or getrandbits directly,
1090 # but inherit them from classes which are not subclasses of Random
1091 class Mixin1:
1092 def random(self):
1093 called.add('Mixin1.random')
1094 return random.Random.random(self)
1095 class Mixin2:
1096 def getrandbits(self, n):
1097 called.add('Mixin2.getrandbits')
1098 return random.Random.getrandbits(self, n)
1099
1100 class SubClass5(Mixin1, random.Random):
1101 pass
1102 called = set()
1103 SubClass5().randrange(42)
1104 self.assertEqual(called, {'Mixin1.random'})
1105
1106 class SubClass6(Mixin2, random.Random):
1107 pass
1108 called = set()
1109 SubClass6().randrange(42)
1110 self.assertEqual(called, {'Mixin2.getrandbits'})
1111
1112 class SubClass7(Mixin1, Mixin2, random.Random):
1113 pass
1114 called = set()
1115 SubClass7().randrange(42)
1116 self.assertEqual(called, {'Mixin1.random'})
1117
1118 class SubClass8(Mixin2, Mixin1, random.Random):
1119 pass
1120 called = set()
1121 SubClass8().randrange(42)
1122 self.assertEqual(called, {'Mixin2.getrandbits'})
1123
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001124
Raymond Hettinger40f62172002-12-29 23:03:38 +00001125class TestModule(unittest.TestCase):
1126 def testMagicConstants(self):
1127 self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141)
1128 self.assertAlmostEqual(random.TWOPI, 6.28318530718)
1129 self.assertAlmostEqual(random.LOG4, 1.38629436111989)
1130 self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627)
1131
1132 def test__all__(self):
1133 # tests validity but not completeness of the __all__ list
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001134 self.assertTrue(set(random.__all__) <= set(dir(random)))
Raymond Hettinger40f62172002-12-29 23:03:38 +00001135
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001136 @unittest.skipUnless(hasattr(os, "fork"), "fork() required")
1137 def test_after_fork(self):
1138 # Test the global Random instance gets reseeded in child
1139 r, w = os.pipe()
Victor Stinnerda5e9302017-08-09 17:59:05 +02001140 pid = os.fork()
1141 if pid == 0:
1142 # child process
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001143 try:
1144 val = random.getrandbits(128)
1145 with open(w, "w") as f:
1146 f.write(str(val))
1147 finally:
1148 os._exit(0)
1149 else:
Victor Stinnerda5e9302017-08-09 17:59:05 +02001150 # parent process
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001151 os.close(w)
1152 val = random.getrandbits(128)
1153 with open(r, "r") as f:
1154 child_val = eval(f.read())
1155 self.assertNotEqual(val, child_val)
1156
Victor Stinner278c1e12020-03-31 20:08:12 +02001157 support.wait_process(pid, exitcode=0)
Victor Stinnerda5e9302017-08-09 17:59:05 +02001158
Thomas Woutersb2137042007-02-01 18:02:27 +00001159
Raymond Hettinger40f62172002-12-29 23:03:38 +00001160if __name__ == "__main__":
Ezio Melotti3e4a98b2013-04-19 05:45:27 +03001161 unittest.main()