blob: 2c8c8e885452ad1edddfa8bea2eabcb2855c4979 [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),
45 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
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300294try:
295 random.SystemRandom().random()
296except NotImplementedError:
297 SystemRandom_available = False
298else:
299 SystemRandom_available = True
300
301@unittest.skipUnless(SystemRandom_available, "random.SystemRandom not available")
302class SystemRandom_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000303 gen = random.SystemRandom()
Raymond Hettinger356a4592004-08-30 06:14:31 +0000304
305 def test_autoseed(self):
306 # Doesn't need to do anything except not fail
307 self.gen.seed()
308
309 def test_saverestore(self):
310 self.assertRaises(NotImplementedError, self.gen.getstate)
311 self.assertRaises(NotImplementedError, self.gen.setstate, None)
312
313 def test_seedargs(self):
314 # Doesn't need to do anything except not fail
315 self.gen.seed(100)
316
Raymond Hettinger356a4592004-08-30 06:14:31 +0000317 def test_gauss(self):
318 self.gen.gauss_next = None
319 self.gen.seed(100)
320 self.assertEqual(self.gen.gauss_next, None)
321
322 def test_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200323 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
324 self.assertRaises(NotImplementedError, pickle.dumps, self.gen, proto)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000325
326 def test_53_bits_per_float(self):
327 # This should pass whenever a C double has 53 bit precision.
328 span = 2 ** 53
329 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000330 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000331 cum |= int(self.gen.random() * span)
332 self.assertEqual(cum, span-1)
333
334 def test_bigrand(self):
335 # The randrange routine should build-up the required number of bits
336 # in stages so that all bit positions are active.
337 span = 2 ** 500
338 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000339 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000340 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000341 self.assertTrue(0 <= r < span)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000342 cum |= r
343 self.assertEqual(cum, span-1)
344
345 def test_bigrand_ranges(self):
346 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600347 start = self.gen.randrange(2 ** (i-2))
348 stop = self.gen.randrange(2 ** i)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000349 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600350 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000351 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000352
353 def test_rangelimits(self):
354 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
355 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000356 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000357
R David Murraye3e1c172013-04-02 12:47:23 -0400358 def test_randrange_nonunit_step(self):
359 rint = self.gen.randrange(0, 10, 2)
360 self.assertIn(rint, (0, 2, 4, 6, 8))
361 rint = self.gen.randrange(0, 2, 2)
362 self.assertEqual(rint, 0)
363
364 def test_randrange_errors(self):
365 raises = partial(self.assertRaises, ValueError, self.gen.randrange)
366 # Empty range
367 raises(3, 3)
368 raises(-721)
369 raises(0, 100, -12)
370 # Non-integer start/stop
371 raises(3.14159)
372 raises(0, 2.71828)
373 # Zero and non-integer step
374 raises(0, 42, 0)
375 raises(0, 42, 3.14159)
376
Raymond Hettinger356a4592004-08-30 06:14:31 +0000377 def test_genrandbits(self):
378 # Verify ranges
Guido van Rossum805365e2007-05-07 22:24:25 +0000379 for k in range(1, 1000):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000380 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000381
382 # Verify all bits active
383 getbits = self.gen.getrandbits
384 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
385 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000386 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000387 cum |= getbits(span)
388 self.assertEqual(cum, 2**span-1)
389
390 # Verify argument checking
391 self.assertRaises(TypeError, self.gen.getrandbits)
392 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
393 self.assertRaises(ValueError, self.gen.getrandbits, 0)
394 self.assertRaises(ValueError, self.gen.getrandbits, -1)
395 self.assertRaises(TypeError, self.gen.getrandbits, 10.1)
396
397 def test_randbelow_logic(self, _log=log, int=int):
398 # check bitcount transition points: 2**i and 2**(i+1)-1
399 # show that: k = int(1.001 + _log(n, 2))
400 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000401 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000402 n = 1 << i # check an exact power of two
Raymond Hettinger356a4592004-08-30 06:14:31 +0000403 numbits = i+1
404 k = int(1.00001 + _log(n, 2))
405 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000406 self.assertEqual(n, 2**(k-1))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000407
408 n += n - 1 # check 1 below the next power of two
409 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000410 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000411 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000412
413 n -= n >> 15 # check a little farther below the next power of two
414 k = int(1.00001 + _log(n, 2))
415 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000416 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger356a4592004-08-30 06:14:31 +0000417
418
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300419class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger40f62172002-12-29 23:03:38 +0000420 gen = random.Random()
421
Raymond Hettingerf763a722010-09-07 00:38:15 +0000422 def test_guaranteed_stable(self):
423 # These sequences are guaranteed to stay the same across versions of python
424 self.gen.seed(3456147, version=1)
425 self.assertEqual([self.gen.random().hex() for i in range(4)],
426 ['0x1.ac362300d90d2p-1', '0x1.9d16f74365005p-1',
427 '0x1.1ebb4352e4c4dp-1', '0x1.1a7422abf9c11p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000428 self.gen.seed("the quick brown fox", version=2)
429 self.assertEqual([self.gen.random().hex() for i in range(4)],
Raymond Hettinger3fcf0022010-12-08 01:13:53 +0000430 ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4',
431 '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000432
Raymond Hettingerc7bab7c2016-08-31 15:01:08 -0700433 def test_bug_27706(self):
434 # Verify that version 1 seeds are unaffected by hash randomization
435
436 self.gen.seed('nofar', version=1) # hash('nofar') == 5990528763808513177
437 self.assertEqual([self.gen.random().hex() for i in range(4)],
438 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
439 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
440
441 self.gen.seed('rachel', version=1) # hash('rachel') == -9091735575445484789
442 self.assertEqual([self.gen.random().hex() for i in range(4)],
443 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
444 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
445
446 self.gen.seed('', version=1) # hash('') == 0
447 self.assertEqual([self.gen.random().hex() for i in range(4)],
448 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
449 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
450
Oren Milmand780b2d2017-09-28 10:50:01 +0300451 def test_bug_31478(self):
452 # There shouldn't be an assertion failure in _random.Random.seed() in
453 # case the argument has a bad __abs__() method.
454 class BadInt(int):
455 def __abs__(self):
456 return None
457 try:
458 self.gen.seed(BadInt())
459 except TypeError:
460 pass
461
Raymond Hettinger132a7d72017-09-17 09:04:30 -0700462 def test_bug_31482(self):
463 # Verify that version 1 seeds are unaffected by hash randomization
464 # when the seeds are expressed as bytes rather than strings.
465 # The hash(b) values listed are the Python2.7 hash() values
466 # which were used for seeding.
467
468 self.gen.seed(b'nofar', version=1) # hash('nofar') == 5990528763808513177
469 self.assertEqual([self.gen.random().hex() for i in range(4)],
470 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
471 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
472
473 self.gen.seed(b'rachel', version=1) # hash('rachel') == -9091735575445484789
474 self.assertEqual([self.gen.random().hex() for i in range(4)],
475 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
476 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
477
478 self.gen.seed(b'', version=1) # hash('') == 0
479 self.assertEqual([self.gen.random().hex() for i in range(4)],
480 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
481 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
482
483 b = b'\x00\x20\x40\x60\x80\xA0\xC0\xE0\xF0'
484 self.gen.seed(b, version=1) # hash(b) == 5015594239749365497
485 self.assertEqual([self.gen.random().hex() for i in range(4)],
486 ['0x1.52c2fde444d23p-1', '0x1.875174f0daea4p-2',
487 '0x1.9e9b2c50e5cd2p-1', '0x1.fa57768bd321cp-2'])
488
Raymond Hettinger58335872004-07-09 14:26:18 +0000489 def test_setstate_first_arg(self):
490 self.assertRaises(ValueError, self.gen.setstate, (1, None, None))
491
492 def test_setstate_middle_arg(self):
bladebryan9616a822017-04-21 23:10:46 -0700493 start_state = self.gen.getstate()
Raymond Hettinger58335872004-07-09 14:26:18 +0000494 # Wrong type, s/b tuple
495 self.assertRaises(TypeError, self.gen.setstate, (2, None, None))
496 # Wrong length, s/b 625
497 self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None))
498 # Wrong type, s/b tuple of 625 ints
499 self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None))
500 # Last element s/b an int also
501 self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None))
Serhiy Storchaka178f0b62015-07-24 09:02:53 +0300502 # Last element s/b between 0 and 624
503 with self.assertRaises((ValueError, OverflowError)):
504 self.gen.setstate((2, (1,)*624+(625,), None))
505 with self.assertRaises((ValueError, OverflowError)):
506 self.gen.setstate((2, (1,)*624+(-1,), None))
bladebryan9616a822017-04-21 23:10:46 -0700507 # Failed calls to setstate() should not have changed the state.
508 bits100 = self.gen.getrandbits(100)
509 self.gen.setstate(start_state)
510 self.assertEqual(self.gen.getrandbits(100), bits100)
Raymond Hettinger58335872004-07-09 14:26:18 +0000511
R David Murraye3e1c172013-04-02 12:47:23 -0400512 # Little trick to make "tuple(x % (2**32) for x in internalstate)"
513 # raise ValueError. I cannot think of a simple way to achieve this, so
514 # I am opting for using a generator as the middle argument of setstate
515 # which attempts to cast a NaN to integer.
516 state_values = self.gen.getstate()[1]
517 state_values = list(state_values)
518 state_values[-1] = float('nan')
519 state = (int(x) for x in state_values)
520 self.assertRaises(TypeError, self.gen.setstate, (2, state, None))
521
Raymond Hettinger40f62172002-12-29 23:03:38 +0000522 def test_referenceImplementation(self):
523 # Compare the python implementation with results from the original
524 # code. Create 2000 53-bit precision random floats. Compare only
525 # the last ten entries to show that the independent implementations
526 # are tracking. Here is the main() function needed to create the
527 # list of expected random numbers:
528 # void main(void){
529 # int i;
530 # unsigned long init[4]={61731, 24903, 614, 42143}, length=4;
531 # init_by_array(init, length);
532 # for (i=0; i<2000; i++) {
533 # printf("%.15f ", genrand_res53());
534 # if (i%5==4) printf("\n");
535 # }
536 # }
537 expected = [0.45839803073713259,
538 0.86057815201978782,
539 0.92848331726782152,
540 0.35932681119782461,
541 0.081823493762449573,
542 0.14332226470169329,
543 0.084297823823520024,
544 0.53814864671831453,
545 0.089215024911993401,
546 0.78486196105372907]
547
Guido van Rossume2a383d2007-01-15 16:59:06 +0000548 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000549 actual = self.randomlist(2000)[-10:]
550 for a, e in zip(actual, expected):
551 self.assertAlmostEqual(a,e,places=14)
552
553 def test_strong_reference_implementation(self):
554 # Like test_referenceImplementation, but checks for exact bit-level
555 # equality. This should pass on any box where C double contains
556 # at least 53 bits of precision (the underlying algorithm suffers
557 # no rounding errors -- all results are exact).
558 from math import ldexp
559
Guido van Rossume2a383d2007-01-15 16:59:06 +0000560 expected = [0x0eab3258d2231f,
561 0x1b89db315277a5,
562 0x1db622a5518016,
563 0x0b7f9af0d575bf,
564 0x029e4c4db82240,
565 0x04961892f5d673,
566 0x02b291598e4589,
567 0x11388382c15694,
568 0x02dad977c9e1fe,
569 0x191d96d4d334c6]
570 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000571 actual = self.randomlist(2000)[-10:]
572 for a, e in zip(actual, expected):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000573 self.assertEqual(int(ldexp(a, 53)), e)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000574
575 def test_long_seed(self):
576 # This is most interesting to run in debug mode, just to make sure
577 # nothing blows up. Under the covers, a dynamically resized array
578 # is allocated, consuming space proportional to the number of bits
579 # in the seed. Unfortunately, that's a quadratic-time algorithm,
580 # so don't make this horribly big.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000581 seed = (1 << (10000 * 8)) - 1 # about 10K bytes
Raymond Hettinger40f62172002-12-29 23:03:38 +0000582 self.gen.seed(seed)
583
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000584 def test_53_bits_per_float(self):
585 # This should pass whenever a C double has 53 bit precision.
586 span = 2 ** 53
587 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000588 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000589 cum |= int(self.gen.random() * span)
590 self.assertEqual(cum, span-1)
591
592 def test_bigrand(self):
593 # The randrange routine should build-up the required number of bits
594 # in stages so that all bit positions are active.
595 span = 2 ** 500
596 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000597 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000598 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000599 self.assertTrue(0 <= r < span)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000600 cum |= r
601 self.assertEqual(cum, span-1)
602
603 def test_bigrand_ranges(self):
604 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600605 start = self.gen.randrange(2 ** (i-2))
606 stop = self.gen.randrange(2 ** i)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000607 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600608 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000609 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000610
611 def test_rangelimits(self):
612 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
Raymond Hettingera690a992003-11-16 16:17:49 +0000613 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000614 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000615
616 def test_genrandbits(self):
617 # Verify cross-platform repeatability
618 self.gen.seed(1234567)
619 self.assertEqual(self.gen.getrandbits(100),
Guido van Rossume2a383d2007-01-15 16:59:06 +0000620 97904845777343510404718956115)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000621 # Verify ranges
Guido van Rossum805365e2007-05-07 22:24:25 +0000622 for k in range(1, 1000):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000623 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000624
625 # Verify all bits active
626 getbits = self.gen.getrandbits
627 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
628 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000629 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000630 cum |= getbits(span)
631 self.assertEqual(cum, 2**span-1)
632
Raymond Hettinger58335872004-07-09 14:26:18 +0000633 # Verify argument checking
634 self.assertRaises(TypeError, self.gen.getrandbits)
635 self.assertRaises(TypeError, self.gen.getrandbits, 'a')
636 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
637 self.assertRaises(ValueError, self.gen.getrandbits, 0)
638 self.assertRaises(ValueError, self.gen.getrandbits, -1)
639
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200640 def test_randrange_uses_getrandbits(self):
641 # Verify use of getrandbits by randrange
642 # Use same seed as in the cross-platform repeatability test
643 # in test_genrandbits above.
644 self.gen.seed(1234567)
645 # If randrange uses getrandbits, it should pick getrandbits(100)
646 # when called with a 100-bits stop argument.
647 self.assertEqual(self.gen.randrange(2**99),
648 97904845777343510404718956115)
649
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000650 def test_randbelow_logic(self, _log=log, int=int):
651 # check bitcount transition points: 2**i and 2**(i+1)-1
652 # show that: k = int(1.001 + _log(n, 2))
653 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000654 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000655 n = 1 << i # check an exact power of two
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000656 numbits = i+1
657 k = int(1.00001 + _log(n, 2))
658 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000659 self.assertEqual(n, 2**(k-1))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000660
661 n += n - 1 # check 1 below the next power of two
662 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000663 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000664 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000665
666 n -= n >> 15 # check a little farther below the next power of two
667 k = int(1.00001 + _log(n, 2))
668 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000669 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000670
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200671 def test_randbelow_without_getrandbits(self):
R David Murraye3e1c172013-04-02 12:47:23 -0400672 # Random._randbelow() can only use random() when the built-in one
673 # has been overridden but no new getrandbits() method was supplied.
R David Murraye3e1c172013-04-02 12:47:23 -0400674 maxsize = 1<<random.BPF
675 with warnings.catch_warnings():
676 warnings.simplefilter("ignore", UserWarning)
677 # Population range too large (n >= maxsize)
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200678 self.gen._randbelow_without_getrandbits(
679 maxsize+1, maxsize=maxsize
680 )
681 self.gen._randbelow_without_getrandbits(5640, maxsize=maxsize)
Wolfgang Maier091e95e2018-04-05 17:19:44 +0200682 # issue 33203: test that _randbelow raises ValueError on
683 # n == 0 also in its getrandbits-independent branch.
684 with self.assertRaises(ValueError):
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200685 self.gen._randbelow_without_getrandbits(0, maxsize=maxsize)
686
R David Murraye3e1c172013-04-02 12:47:23 -0400687 # This might be going too far to test a single line, but because of our
688 # noble aim of achieving 100% test coverage we need to write a case in
689 # which the following line in Random._randbelow() gets executed:
690 #
691 # rem = maxsize % n
692 # limit = (maxsize - rem) / maxsize
693 # r = random()
694 # while r >= limit:
695 # r = random() # <== *This line* <==<
696 #
697 # Therefore, to guarantee that the while loop is executed at least
698 # once, we need to mock random() so that it returns a number greater
699 # than 'limit' the first time it gets called.
700
701 n = 42
702 epsilon = 0.01
703 limit = (maxsize - (maxsize % n)) / maxsize
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200704 with unittest.mock.patch.object(random.Random, 'random') as random_mock:
705 random_mock.side_effect = [limit + epsilon, limit - epsilon]
706 self.gen._randbelow_without_getrandbits(n, maxsize=maxsize)
707 self.assertEqual(random_mock.call_count, 2)
R David Murraye3e1c172013-04-02 12:47:23 -0400708
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000709 def test_randrange_bug_1590891(self):
710 start = 1000000000000
711 stop = -100000000000000000000
712 step = -200
713 x = self.gen.randrange(start, stop, step)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000714 self.assertTrue(stop < x <= start)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000715 self.assertEqual((x+stop)%step, 0)
716
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700717 def test_choices_algorithms(self):
Raymond Hettinger24e42392016-11-13 00:42:56 -0500718 # The various ways of specifying weights should produce the same results
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700719 choices = self.gen.choices
Raymond Hettinger6023d332016-11-21 15:32:08 -0800720 n = 104729
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700721
722 self.gen.seed(8675309)
723 a = self.gen.choices(range(n), k=10000)
724
725 self.gen.seed(8675309)
726 b = self.gen.choices(range(n), [1]*n, k=10000)
727 self.assertEqual(a, b)
728
729 self.gen.seed(8675309)
730 c = self.gen.choices(range(n), cum_weights=range(1, n+1), k=10000)
731 self.assertEqual(a, c)
732
penguindustin96466302019-05-06 14:57:17 -0400733 # American Roulette
Raymond Hettinger77d574d2016-10-29 17:42:36 -0700734 population = ['Red', 'Black', 'Green']
735 weights = [18, 18, 2]
736 cum_weights = [18, 36, 38]
737 expanded_population = ['Red'] * 18 + ['Black'] * 18 + ['Green'] * 2
738
739 self.gen.seed(9035768)
740 a = self.gen.choices(expanded_population, k=10000)
741
742 self.gen.seed(9035768)
743 b = self.gen.choices(population, weights, k=10000)
744 self.assertEqual(a, b)
745
746 self.gen.seed(9035768)
747 c = self.gen.choices(population, cum_weights=cum_weights, k=10000)
748 self.assertEqual(a, c)
749
Raymond Hettinger2d0c2562009-02-19 09:53:18 +0000750def gamma(z, sqrt2pi=(2.0*pi)**0.5):
751 # Reflection to right half of complex plane
752 if z < 0.5:
753 return pi / sin(pi*z) / gamma(1.0-z)
754 # Lanczos approximation with g=7
755 az = z + (7.0 - 0.5)
756 return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
757 0.9999999999995183,
758 676.5203681218835 / z,
759 -1259.139216722289 / (z+1.0),
760 771.3234287757674 / (z+2.0),
761 -176.6150291498386 / (z+3.0),
762 12.50734324009056 / (z+4.0),
763 -0.1385710331296526 / (z+5.0),
764 0.9934937113930748e-05 / (z+6.0),
765 0.1659470187408462e-06 / (z+7.0),
766 ])
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000767
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000768class TestDistributions(unittest.TestCase):
769 def test_zeroinputs(self):
770 # Verify that distributions can handle a series of zero inputs'
771 g = random.Random()
Guido van Rossum805365e2007-05-07 22:24:25 +0000772 x = [g.random() for i in range(50)] + [0.0]*5
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000773 g.random = x[:].pop; g.uniform(1,10)
774 g.random = x[:].pop; g.paretovariate(1.0)
775 g.random = x[:].pop; g.expovariate(1.0)
776 g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200777 g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000778 g.random = x[:].pop; g.normalvariate(0.0, 1.0)
779 g.random = x[:].pop; g.gauss(0.0, 1.0)
780 g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
781 g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
782 g.random = x[:].pop; g.gammavariate(0.01, 1.0)
783 g.random = x[:].pop; g.gammavariate(1.0, 1.0)
784 g.random = x[:].pop; g.gammavariate(200.0, 1.0)
785 g.random = x[:].pop; g.betavariate(3.0, 3.0)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000786 g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000787
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000788 def test_avg_std(self):
789 # Use integration to test distribution average and standard deviation.
790 # Only works for distributions which do not consume variates in pairs
791 g = random.Random()
792 N = 5000
Guido van Rossum805365e2007-05-07 22:24:25 +0000793 x = [i/float(N) for i in range(1,N)]
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000794 for variate, args, mu, sigmasqrd in [
795 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
Christian Heimesfe337bf2008-03-23 21:54:12 +0000796 (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 +0000797 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200798 (g.vonmisesvariate, (1.23, 0), pi, pi**2/3),
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000799 (g.paretovariate, (5.0,), 5.0/(5.0-1),
800 5.0/((5.0-1)**2*(5.0-2))),
801 (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0),
802 gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
803 g.random = x[:].pop
804 y = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000805 for i in range(len(x)):
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000806 try:
807 y.append(variate(*args))
808 except IndexError:
809 pass
810 s1 = s2 = 0
811 for e in y:
812 s1 += e
813 s2 += (e - mu) ** 2
814 N = len(y)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200815 self.assertAlmostEqual(s1/N, mu, places=2,
816 msg='%s%r' % (variate.__name__, args))
817 self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2,
818 msg='%s%r' % (variate.__name__, args))
819
820 def test_constant(self):
821 g = random.Random()
822 N = 100
823 for variate, args, expected in [
824 (g.uniform, (10.0, 10.0), 10.0),
825 (g.triangular, (10.0, 10.0), 10.0),
Raymond Hettinger978c6ab2014-05-25 17:25:27 -0700826 (g.triangular, (10.0, 10.0, 10.0), 10.0),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200827 (g.expovariate, (float('inf'),), 0.0),
828 (g.vonmisesvariate, (3.0, float('inf')), 3.0),
829 (g.gauss, (10.0, 0.0), 10.0),
830 (g.lognormvariate, (0.0, 0.0), 1.0),
831 (g.lognormvariate, (-float('inf'), 0.0), 0.0),
832 (g.normalvariate, (10.0, 0.0), 10.0),
833 (g.paretovariate, (float('inf'),), 1.0),
834 (g.weibullvariate, (10.0, float('inf')), 10.0),
835 (g.weibullvariate, (0.0, 10.0), 0.0),
836 ]:
837 for i in range(N):
838 self.assertEqual(variate(*args), expected)
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000839
Mark Dickinsonbe5f9192013-02-10 14:16:10 +0000840 def test_von_mises_range(self):
841 # Issue 17149: von mises variates were not consistently in the
842 # range [0, 2*PI].
843 g = random.Random()
844 N = 100
845 for mu in 0.0, 0.1, 3.1, 6.2:
846 for kappa in 0.0, 2.3, 500.0:
847 for _ in range(N):
848 sample = g.vonmisesvariate(mu, kappa)
849 self.assertTrue(
850 0 <= sample <= random.TWOPI,
851 msg=("vonmisesvariate({}, {}) produced a result {} out"
852 " of range [0, 2*pi]").format(mu, kappa, sample))
853
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200854 def test_von_mises_large_kappa(self):
855 # Issue #17141: vonmisesvariate() was hang for large kappas
856 random.vonmisesvariate(0, 1e15)
857 random.vonmisesvariate(0, 1e100)
858
R David Murraye3e1c172013-04-02 12:47:23 -0400859 def test_gammavariate_errors(self):
860 # Both alpha and beta must be > 0.0
861 self.assertRaises(ValueError, random.gammavariate, -1, 3)
862 self.assertRaises(ValueError, random.gammavariate, 0, 2)
863 self.assertRaises(ValueError, random.gammavariate, 2, 0)
864 self.assertRaises(ValueError, random.gammavariate, 1, -3)
865
leodema63d15222018-12-24 07:54:25 +0100866 # There are three different possibilities in the current implementation
867 # of random.gammavariate(), depending on the value of 'alpha'. What we
868 # are going to do here is to fix the values returned by random() to
869 # generate test cases that provide 100% line coverage of the method.
R David Murraye3e1c172013-04-02 12:47:23 -0400870 @unittest.mock.patch('random.Random.random')
leodema63d15222018-12-24 07:54:25 +0100871 def test_gammavariate_alpha_greater_one(self, random_mock):
R David Murraye3e1c172013-04-02 12:47:23 -0400872
leodema63d15222018-12-24 07:54:25 +0100873 # #1: alpha > 1.0.
874 # We want the first random number to be outside the
R David Murraye3e1c172013-04-02 12:47:23 -0400875 # [1e-7, .9999999] range, so that the continue statement executes
876 # once. The values of u1 and u2 will be 0.5 and 0.3, respectively.
877 random_mock.side_effect = [1e-8, 0.5, 0.3]
878 returned_value = random.gammavariate(1.1, 2.3)
879 self.assertAlmostEqual(returned_value, 2.53)
880
leodema63d15222018-12-24 07:54:25 +0100881 @unittest.mock.patch('random.Random.random')
882 def test_gammavariate_alpha_equal_one(self, random_mock):
R David Murraye3e1c172013-04-02 12:47:23 -0400883
leodema63d15222018-12-24 07:54:25 +0100884 # #2.a: alpha == 1.
885 # The execution body of the while loop executes once.
886 # Then random.random() returns 0.45,
887 # which causes while to stop looping and the algorithm to terminate.
888 random_mock.side_effect = [0.45]
889 returned_value = random.gammavariate(1.0, 3.14)
890 self.assertAlmostEqual(returned_value, 1.877208182372648)
891
892 @unittest.mock.patch('random.Random.random')
893 def test_gammavariate_alpha_equal_one_equals_expovariate(self, random_mock):
894
895 # #2.b: alpha == 1.
896 # It must be equivalent of calling expovariate(1.0 / beta).
897 beta = 3.14
898 random_mock.side_effect = [1e-8, 1e-8]
899 gammavariate_returned_value = random.gammavariate(1.0, beta)
900 expovariate_returned_value = random.expovariate(1.0 / beta)
901 self.assertAlmostEqual(gammavariate_returned_value, expovariate_returned_value)
902
903 @unittest.mock.patch('random.Random.random')
904 def test_gammavariate_alpha_between_zero_and_one(self, random_mock):
905
906 # #3: 0 < alpha < 1.
907 # This is the most complex region of code to cover,
R David Murraye3e1c172013-04-02 12:47:23 -0400908 # as there are multiple if-else statements. Let's take a look at the
909 # source code, and determine the values that we need accordingly:
910 #
911 # while 1:
912 # u = random()
913 # b = (_e + alpha)/_e
914 # p = b*u
915 # if p <= 1.0: # <=== (A)
916 # x = p ** (1.0/alpha)
917 # else: # <=== (B)
918 # x = -_log((b-p)/alpha)
919 # u1 = random()
920 # if p > 1.0: # <=== (C)
921 # if u1 <= x ** (alpha - 1.0): # <=== (D)
922 # break
923 # elif u1 <= _exp(-x): # <=== (E)
924 # break
925 # return x * beta
926 #
927 # First, we want (A) to be True. For that we need that:
928 # b*random() <= 1.0
929 # r1 = random() <= 1.0 / b
930 #
931 # We now get to the second if-else branch, and here, since p <= 1.0,
932 # (C) is False and we take the elif branch, (E). For it to be True,
933 # so that the break is executed, we need that:
934 # r2 = random() <= _exp(-x)
935 # r2 <= _exp(-(p ** (1.0/alpha)))
936 # r2 <= _exp(-((b*r1) ** (1.0/alpha)))
937
938 _e = random._e
939 _exp = random._exp
940 _log = random._log
941 alpha = 0.35
942 beta = 1.45
943 b = (_e + alpha)/_e
944 epsilon = 0.01
945
946 r1 = 0.8859296441566 # 1.0 / b
947 r2 = 0.3678794411714 # _exp(-((b*r1) ** (1.0/alpha)))
948
949 # These four "random" values result in the following trace:
950 # (A) True, (E) False --> [next iteration of while]
951 # (A) True, (E) True --> [while loop breaks]
952 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
953 returned_value = random.gammavariate(alpha, beta)
954 self.assertAlmostEqual(returned_value, 1.4499999999997544)
955
956 # Let's now make (A) be False. If this is the case, when we get to the
957 # second if-else 'p' is greater than 1, so (C) evaluates to True. We
958 # now encounter a second if statement, (D), which in order to execute
959 # must satisfy the following condition:
960 # r2 <= x ** (alpha - 1.0)
961 # r2 <= (-_log((b-p)/alpha)) ** (alpha - 1.0)
962 # r2 <= (-_log((b-(b*r1))/alpha)) ** (alpha - 1.0)
963 r1 = 0.8959296441566 # (1.0 / b) + epsilon -- so that (A) is False
964 r2 = 0.9445400408898141
965
966 # And these four values result in the following trace:
967 # (B) and (C) True, (D) False --> [next iteration of while]
968 # (B) and (C) True, (D) True [while loop breaks]
969 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
970 returned_value = random.gammavariate(alpha, beta)
971 self.assertAlmostEqual(returned_value, 1.5830349561760781)
972
973 @unittest.mock.patch('random.Random.gammavariate')
974 def test_betavariate_return_zero(self, gammavariate_mock):
975 # betavariate() returns zero when the Gamma distribution
976 # that it uses internally returns this same value.
977 gammavariate_mock.return_value = 0.0
978 self.assertEqual(0.0, random.betavariate(2.71828, 3.14159))
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200979
Serhiy Storchakaec1622d2018-05-08 15:45:15 +0300980
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200981class TestRandomSubclassing(unittest.TestCase):
982 def test_random_subclass_with_kwargs(self):
983 # SF bug #1486663 -- this used to erroneously raise a TypeError
984 class Subclass(random.Random):
985 def __init__(self, newarg=None):
986 random.Random.__init__(self)
987 Subclass(newarg=1)
988
989 def test_subclasses_overriding_methods(self):
990 # Subclasses with an overridden random, but only the original
991 # getrandbits method should not rely on getrandbits in for randrange,
992 # but should use a getrandbits-independent implementation instead.
993
994 # subclass providing its own random **and** getrandbits methods
995 # like random.SystemRandom does => keep relying on getrandbits for
996 # randrange
997 class SubClass1(random.Random):
998 def random(self):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +0300999 called.add('SubClass1.random')
1000 return random.Random.random(self)
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001001
1002 def getrandbits(self, n):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001003 called.add('SubClass1.getrandbits')
1004 return random.Random.getrandbits(self, n)
1005 called = set()
1006 SubClass1().randrange(42)
1007 self.assertEqual(called, {'SubClass1.getrandbits'})
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001008
1009 # subclass providing only random => can only use random for randrange
1010 class SubClass2(random.Random):
1011 def random(self):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001012 called.add('SubClass2.random')
1013 return random.Random.random(self)
1014 called = set()
1015 SubClass2().randrange(42)
1016 self.assertEqual(called, {'SubClass2.random'})
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001017
1018 # subclass defining getrandbits to complement its inherited random
1019 # => can now rely on getrandbits for randrange again
1020 class SubClass3(SubClass2):
1021 def getrandbits(self, n):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001022 called.add('SubClass3.getrandbits')
1023 return random.Random.getrandbits(self, n)
1024 called = set()
1025 SubClass3().randrange(42)
1026 self.assertEqual(called, {'SubClass3.getrandbits'})
1027
1028 # subclass providing only random and inherited getrandbits
1029 # => random takes precedence
1030 class SubClass4(SubClass3):
1031 def random(self):
1032 called.add('SubClass4.random')
1033 return random.Random.random(self)
1034 called = set()
1035 SubClass4().randrange(42)
1036 self.assertEqual(called, {'SubClass4.random'})
1037
1038 # Following subclasses don't define random or getrandbits directly,
1039 # but inherit them from classes which are not subclasses of Random
1040 class Mixin1:
1041 def random(self):
1042 called.add('Mixin1.random')
1043 return random.Random.random(self)
1044 class Mixin2:
1045 def getrandbits(self, n):
1046 called.add('Mixin2.getrandbits')
1047 return random.Random.getrandbits(self, n)
1048
1049 class SubClass5(Mixin1, random.Random):
1050 pass
1051 called = set()
1052 SubClass5().randrange(42)
1053 self.assertEqual(called, {'Mixin1.random'})
1054
1055 class SubClass6(Mixin2, random.Random):
1056 pass
1057 called = set()
1058 SubClass6().randrange(42)
1059 self.assertEqual(called, {'Mixin2.getrandbits'})
1060
1061 class SubClass7(Mixin1, Mixin2, random.Random):
1062 pass
1063 called = set()
1064 SubClass7().randrange(42)
1065 self.assertEqual(called, {'Mixin1.random'})
1066
1067 class SubClass8(Mixin2, Mixin1, random.Random):
1068 pass
1069 called = set()
1070 SubClass8().randrange(42)
1071 self.assertEqual(called, {'Mixin2.getrandbits'})
1072
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001073
Raymond Hettinger40f62172002-12-29 23:03:38 +00001074class TestModule(unittest.TestCase):
1075 def testMagicConstants(self):
1076 self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141)
1077 self.assertAlmostEqual(random.TWOPI, 6.28318530718)
1078 self.assertAlmostEqual(random.LOG4, 1.38629436111989)
1079 self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627)
1080
1081 def test__all__(self):
1082 # tests validity but not completeness of the __all__ list
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001083 self.assertTrue(set(random.__all__) <= set(dir(random)))
Raymond Hettinger40f62172002-12-29 23:03:38 +00001084
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001085 @unittest.skipUnless(hasattr(os, "fork"), "fork() required")
1086 def test_after_fork(self):
1087 # Test the global Random instance gets reseeded in child
1088 r, w = os.pipe()
Victor Stinnerda5e9302017-08-09 17:59:05 +02001089 pid = os.fork()
1090 if pid == 0:
1091 # child process
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001092 try:
1093 val = random.getrandbits(128)
1094 with open(w, "w") as f:
1095 f.write(str(val))
1096 finally:
1097 os._exit(0)
1098 else:
Victor Stinnerda5e9302017-08-09 17:59:05 +02001099 # parent process
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001100 os.close(w)
1101 val = random.getrandbits(128)
1102 with open(r, "r") as f:
1103 child_val = eval(f.read())
1104 self.assertNotEqual(val, child_val)
1105
Victor Stinnerda5e9302017-08-09 17:59:05 +02001106 pid, status = os.waitpid(pid, 0)
1107 self.assertEqual(status, 0)
1108
Thomas Woutersb2137042007-02-01 18:02:27 +00001109
Raymond Hettinger40f62172002-12-29 23:03:38 +00001110if __name__ == "__main__":
Ezio Melotti3e4a98b2013-04-19 05:45:27 +03001111 unittest.main()