blob: b35cb39e751b35f4817c8f0f5d1b8123352c7d52 [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
Guido van Rossume2a383d2007-01-15 16:59:06 +000044 for arg in [None, 0, 0, 1, 1, -1, -1, 10**20, -(10**20),
Mark Dickinson95aeae02012-06-24 11:05:30 +010045 3.14, 1+2j, 'a', tuple('abc'), MySeed()]:
Raymond Hettinger40f62172002-12-29 23:03:38 +000046 self.gen.seed(arg)
Guido van Rossum805365e2007-05-07 22:24:25 +000047 for arg in [list(range(3)), dict(one=1)]:
Raymond Hettinger40f62172002-12-29 23:03:38 +000048 self.assertRaises(TypeError, self.gen.seed, arg)
Raymond Hettingerf763a722010-09-07 00:38:15 +000049 self.assertRaises(TypeError, self.gen.seed, 1, 2, 3, 4)
Raymond Hettinger58335872004-07-09 14:26:18 +000050 self.assertRaises(TypeError, type(self.gen), [])
Raymond Hettinger40f62172002-12-29 23:03:38 +000051
R David Murraye3e1c172013-04-02 12:47:23 -040052 @unittest.mock.patch('random._urandom') # os.urandom
53 def test_seed_when_randomness_source_not_found(self, urandom_mock):
54 # Random.seed() uses time.time() when an operating system specific
csabellaf111fd22017-05-11 11:19:35 -040055 # randomness source is not found. To test this on machines where it
R David Murraye3e1c172013-04-02 12:47:23 -040056 # exists, run the above test, test_seedargs(), again after mocking
57 # os.urandom() so that it raises the exception expected when the
58 # randomness source is not available.
59 urandom_mock.side_effect = NotImplementedError
60 self.test_seedargs()
61
Antoine Pitrou5e394332012-11-04 02:10:33 +010062 def test_shuffle(self):
63 shuffle = self.gen.shuffle
64 lst = []
65 shuffle(lst)
66 self.assertEqual(lst, [])
67 lst = [37]
68 shuffle(lst)
69 self.assertEqual(lst, [37])
70 seqs = [list(range(n)) for n in range(10)]
71 shuffled_seqs = [list(range(n)) for n in range(10)]
72 for shuffled_seq in shuffled_seqs:
73 shuffle(shuffled_seq)
74 for (seq, shuffled_seq) in zip(seqs, shuffled_seqs):
75 self.assertEqual(len(seq), len(shuffled_seq))
76 self.assertEqual(set(seq), set(shuffled_seq))
Antoine Pitrou5e394332012-11-04 02:10:33 +010077 # The above tests all would pass if the shuffle was a
78 # no-op. The following non-deterministic test covers that. It
79 # asserts that the shuffled sequence of 1000 distinct elements
80 # must be different from the original one. Although there is
81 # mathematically a non-zero probability that this could
82 # actually happen in a genuinely random shuffle, it is
83 # completely negligible, given that the number of possible
84 # permutations of 1000 objects is 1000! (factorial of 1000),
85 # which is considerably larger than the number of atoms in the
86 # universe...
87 lst = list(range(1000))
88 shuffled_lst = list(range(1000))
89 shuffle(shuffled_lst)
90 self.assertTrue(lst != shuffled_lst)
91 shuffle(lst)
92 self.assertTrue(lst != shuffled_lst)
csabellaf111fd22017-05-11 11:19:35 -040093 self.assertRaises(TypeError, shuffle, (1, 2, 3))
94
95 def test_shuffle_random_argument(self):
96 # Test random argument to shuffle.
97 shuffle = self.gen.shuffle
98 mock_random = unittest.mock.Mock(return_value=0.5)
99 seq = bytearray(b'abcdefghijk')
100 shuffle(seq, mock_random)
101 mock_random.assert_called_with()
Antoine Pitrou5e394332012-11-04 02:10:33 +0100102
Raymond Hettingerdc4872e2010-09-07 10:06:56 +0000103 def test_choice(self):
104 choice = self.gen.choice
105 with self.assertRaises(IndexError):
106 choice([])
107 self.assertEqual(choice([50]), 50)
108 self.assertIn(choice([25, 75]), [25, 75])
109
Raymond Hettinger40f62172002-12-29 23:03:38 +0000110 def test_sample(self):
111 # For the entire allowable range of 0 <= k <= N, validate that
112 # the sample is of the correct length and contains only unique items
113 N = 100
Guido van Rossum805365e2007-05-07 22:24:25 +0000114 population = range(N)
115 for k in range(N+1):
Raymond Hettinger40f62172002-12-29 23:03:38 +0000116 s = self.gen.sample(population, k)
117 self.assertEqual(len(s), k)
Raymond Hettingera690a992003-11-16 16:17:49 +0000118 uniq = set(s)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000119 self.assertEqual(len(uniq), k)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000120 self.assertTrue(uniq <= set(population))
Raymond Hettinger8ec78812003-01-04 05:55:11 +0000121 self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0
R David Murraye3e1c172013-04-02 12:47:23 -0400122 # Exception raised if size of sample exceeds that of population
123 self.assertRaises(ValueError, self.gen.sample, population, N+1)
Raymond Hettingerbf871262016-11-21 14:34:33 -0800124 self.assertRaises(ValueError, self.gen.sample, [], -1)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000125
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000126 def test_sample_distribution(self):
127 # For the entire allowable range of 0 <= k <= N, validate that
128 # sample generates all possible permutations
129 n = 5
130 pop = range(n)
131 trials = 10000 # large num prevents false negatives without slowing normal case
Guido van Rossum805365e2007-05-07 22:24:25 +0000132 for k in range(n):
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +0000133 expected = factorial(n) // factorial(n-k)
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000134 perms = {}
Guido van Rossum805365e2007-05-07 22:24:25 +0000135 for i in range(trials):
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000136 perms[tuple(self.gen.sample(pop, k))] = None
137 if len(perms) == expected:
138 break
139 else:
140 self.fail()
141
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000142 def test_sample_inputs(self):
143 # SF bug #801342 -- population can be any iterable defining __len__()
Raymond Hettingera690a992003-11-16 16:17:49 +0000144 self.gen.sample(set(range(20)), 2)
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000145 self.gen.sample(range(20), 2)
Guido van Rossum805365e2007-05-07 22:24:25 +0000146 self.gen.sample(range(20), 2)
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000147 self.gen.sample(str('abcdefghijklmnopqrst'), 2)
148 self.gen.sample(tuple('abcdefghijklmnopqrst'), 2)
149
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000150 def test_sample_on_dicts(self):
Raymond Hettinger1acde192008-01-14 01:00:53 +0000151 self.assertRaises(TypeError, self.gen.sample, dict.fromkeys('abcdef'), 2)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000152
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700153 def test_choices(self):
154 choices = self.gen.choices
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700155 data = ['red', 'green', 'blue', 'yellow']
156 str_data = 'abcd'
157 range_data = range(4)
158 set_data = set(range(4))
159
160 # basic functionality
161 for sample in [
Raymond Hettinger9016f282016-09-26 21:45:57 -0700162 choices(data, k=5),
163 choices(data, range(4), k=5),
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700164 choices(k=5, population=data, weights=range(4)),
165 choices(k=5, population=data, cum_weights=range(4)),
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700166 ]:
167 self.assertEqual(len(sample), 5)
168 self.assertEqual(type(sample), list)
169 self.assertTrue(set(sample) <= set(data))
170
171 # test argument handling
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700172 with self.assertRaises(TypeError): # missing arguments
173 choices(2)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700174
Raymond Hettinger9016f282016-09-26 21:45:57 -0700175 self.assertEqual(choices(data, k=0), []) # k == 0
176 self.assertEqual(choices(data, k=-1), []) # negative k behaves like ``[0] * -1``
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700177 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700178 choices(data, k=2.5) # k is a float
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700179
Raymond Hettinger9016f282016-09-26 21:45:57 -0700180 self.assertTrue(set(choices(str_data, k=5)) <= set(str_data)) # population is a string sequence
181 self.assertTrue(set(choices(range_data, k=5)) <= set(range_data)) # population is a range
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700182 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700183 choices(set_data, k=2) # population is not a sequence
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700184
Raymond Hettinger9016f282016-09-26 21:45:57 -0700185 self.assertTrue(set(choices(data, None, k=5)) <= set(data)) # weights is None
186 self.assertTrue(set(choices(data, weights=None, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700187 with self.assertRaises(ValueError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700188 choices(data, [1,2], k=5) # len(weights) != len(population)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700189 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700190 choices(data, 10, k=5) # non-iterable weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700191 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700192 choices(data, [None]*4, k=5) # non-numeric weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700193 for weights in [
194 [15, 10, 25, 30], # integer weights
195 [15.1, 10.2, 25.2, 30.3], # float weights
196 [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional weights
197 [True, False, True, False] # booleans (include / exclude)
198 ]:
Raymond Hettinger9016f282016-09-26 21:45:57 -0700199 self.assertTrue(set(choices(data, weights, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700200
201 with self.assertRaises(ValueError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700202 choices(data, cum_weights=[1,2], k=5) # len(weights) != len(population)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700203 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700204 choices(data, cum_weights=10, k=5) # non-iterable cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700205 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700206 choices(data, cum_weights=[None]*4, k=5) # non-numeric cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700207 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700208 choices(data, range(4), cum_weights=range(4), k=5) # both weights and cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700209 for weights in [
210 [15, 10, 25, 30], # integer cum_weights
211 [15.1, 10.2, 25.2, 30.3], # float cum_weights
212 [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional cum_weights
213 ]:
Raymond Hettinger9016f282016-09-26 21:45:57 -0700214 self.assertTrue(set(choices(data, cum_weights=weights, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700215
Raymond Hettinger7b166522016-10-14 01:19:38 -0400216 # Test weight focused on a single element of the population
217 self.assertEqual(choices('abcd', [1, 0, 0, 0]), ['a'])
218 self.assertEqual(choices('abcd', [0, 1, 0, 0]), ['b'])
219 self.assertEqual(choices('abcd', [0, 0, 1, 0]), ['c'])
220 self.assertEqual(choices('abcd', [0, 0, 0, 1]), ['d'])
221
222 # Test consistency with random.choice() for empty population
223 with self.assertRaises(IndexError):
224 choices([], k=1)
225 with self.assertRaises(IndexError):
226 choices([], weights=[], k=1)
227 with self.assertRaises(IndexError):
228 choices([], cum_weights=[], k=5)
229
Raymond Hettingerddf71712018-06-27 01:08:31 -0700230 def test_choices_subnormal(self):
231 # Subnormal weights would occassionally trigger an IndexError
232 # in choices() when the value returned by random() was large
233 # enough to make `random() * total` round up to the total.
234 # See https://bugs.python.org/msg275594 for more detail.
235 choices = self.gen.choices
236 choices(population=[1, 2], weights=[1e-323, 1e-323], k=5000)
237
Raymond Hettinger40f62172002-12-29 23:03:38 +0000238 def test_gauss(self):
239 # Ensure that the seed() method initializes all the hidden state. In
240 # particular, through 2.2.1 it failed to reset a piece of state used
241 # by (and only by) the .gauss() method.
242
243 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
244 self.gen.seed(seed)
245 x1 = self.gen.random()
246 y1 = self.gen.gauss(0, 1)
247
248 self.gen.seed(seed)
249 x2 = self.gen.random()
250 y2 = self.gen.gauss(0, 1)
251
252 self.assertEqual(x1, x2)
253 self.assertEqual(y1, y2)
254
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000255 def test_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200256 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
257 state = pickle.dumps(self.gen, proto)
258 origseq = [self.gen.random() for i in range(10)]
259 newgen = pickle.loads(state)
260 restoredseq = [newgen.random() for i in range(10)]
261 self.assertEqual(origseq, restoredseq)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000262
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000263 def test_bug_1727780(self):
264 # verify that version-2-pickles can be loaded
265 # fine, whether they are created on 32-bit or 64-bit
266 # platforms, and that version-3-pickles load fine.
267 files = [("randv2_32.pck", 780),
268 ("randv2_64.pck", 866),
269 ("randv3.pck", 343)]
270 for file, value in files:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000271 f = open(support.findfile(file),"rb")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000272 r = pickle.load(f)
273 f.close()
Raymond Hettinger05156612010-09-07 04:44:52 +0000274 self.assertEqual(int(r.random()*1000), value)
275
276 def test_bug_9025(self):
277 # Had problem with an uneven distribution in int(n*random())
278 # Verify the fix by checking that distributions fall within expectations.
279 n = 100000
280 randrange = self.gen.randrange
281 k = sum(randrange(6755399441055744) % 3 == 2 for i in range(n))
282 self.assertTrue(0.30 < k/n < .37, (k/n))
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000283
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300284try:
285 random.SystemRandom().random()
286except NotImplementedError:
287 SystemRandom_available = False
288else:
289 SystemRandom_available = True
290
291@unittest.skipUnless(SystemRandom_available, "random.SystemRandom not available")
292class SystemRandom_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000293 gen = random.SystemRandom()
Raymond Hettinger356a4592004-08-30 06:14:31 +0000294
295 def test_autoseed(self):
296 # Doesn't need to do anything except not fail
297 self.gen.seed()
298
299 def test_saverestore(self):
300 self.assertRaises(NotImplementedError, self.gen.getstate)
301 self.assertRaises(NotImplementedError, self.gen.setstate, None)
302
303 def test_seedargs(self):
304 # Doesn't need to do anything except not fail
305 self.gen.seed(100)
306
Raymond Hettinger356a4592004-08-30 06:14:31 +0000307 def test_gauss(self):
308 self.gen.gauss_next = None
309 self.gen.seed(100)
310 self.assertEqual(self.gen.gauss_next, None)
311
312 def test_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200313 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
314 self.assertRaises(NotImplementedError, pickle.dumps, self.gen, proto)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000315
316 def test_53_bits_per_float(self):
317 # This should pass whenever a C double has 53 bit precision.
318 span = 2 ** 53
319 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000320 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000321 cum |= int(self.gen.random() * span)
322 self.assertEqual(cum, span-1)
323
324 def test_bigrand(self):
325 # The randrange routine should build-up the required number of bits
326 # in stages so that all bit positions are active.
327 span = 2 ** 500
328 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000329 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000330 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000331 self.assertTrue(0 <= r < span)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000332 cum |= r
333 self.assertEqual(cum, span-1)
334
335 def test_bigrand_ranges(self):
336 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600337 start = self.gen.randrange(2 ** (i-2))
338 stop = self.gen.randrange(2 ** i)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000339 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600340 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000341 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000342
343 def test_rangelimits(self):
344 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
345 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000346 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000347
R David Murraye3e1c172013-04-02 12:47:23 -0400348 def test_randrange_nonunit_step(self):
349 rint = self.gen.randrange(0, 10, 2)
350 self.assertIn(rint, (0, 2, 4, 6, 8))
351 rint = self.gen.randrange(0, 2, 2)
352 self.assertEqual(rint, 0)
353
354 def test_randrange_errors(self):
355 raises = partial(self.assertRaises, ValueError, self.gen.randrange)
356 # Empty range
357 raises(3, 3)
358 raises(-721)
359 raises(0, 100, -12)
360 # Non-integer start/stop
361 raises(3.14159)
362 raises(0, 2.71828)
363 # Zero and non-integer step
364 raises(0, 42, 0)
365 raises(0, 42, 3.14159)
366
Raymond Hettinger356a4592004-08-30 06:14:31 +0000367 def test_genrandbits(self):
368 # Verify ranges
Guido van Rossum805365e2007-05-07 22:24:25 +0000369 for k in range(1, 1000):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000370 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000371
372 # Verify all bits active
373 getbits = self.gen.getrandbits
374 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
375 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000376 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000377 cum |= getbits(span)
378 self.assertEqual(cum, 2**span-1)
379
380 # Verify argument checking
381 self.assertRaises(TypeError, self.gen.getrandbits)
382 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
383 self.assertRaises(ValueError, self.gen.getrandbits, 0)
384 self.assertRaises(ValueError, self.gen.getrandbits, -1)
385 self.assertRaises(TypeError, self.gen.getrandbits, 10.1)
386
387 def test_randbelow_logic(self, _log=log, int=int):
388 # check bitcount transition points: 2**i and 2**(i+1)-1
389 # show that: k = int(1.001 + _log(n, 2))
390 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000391 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000392 n = 1 << i # check an exact power of two
Raymond Hettinger356a4592004-08-30 06:14:31 +0000393 numbits = i+1
394 k = int(1.00001 + _log(n, 2))
395 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000396 self.assertEqual(n, 2**(k-1))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000397
398 n += n - 1 # check 1 below the next power of two
399 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000400 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000401 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000402
403 n -= n >> 15 # check a little farther below the next power of two
404 k = int(1.00001 + _log(n, 2))
405 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000406 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger356a4592004-08-30 06:14:31 +0000407
408
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300409class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger40f62172002-12-29 23:03:38 +0000410 gen = random.Random()
411
Raymond Hettingerf763a722010-09-07 00:38:15 +0000412 def test_guaranteed_stable(self):
413 # These sequences are guaranteed to stay the same across versions of python
414 self.gen.seed(3456147, version=1)
415 self.assertEqual([self.gen.random().hex() for i in range(4)],
416 ['0x1.ac362300d90d2p-1', '0x1.9d16f74365005p-1',
417 '0x1.1ebb4352e4c4dp-1', '0x1.1a7422abf9c11p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000418 self.gen.seed("the quick brown fox", version=2)
419 self.assertEqual([self.gen.random().hex() for i in range(4)],
Raymond Hettinger3fcf0022010-12-08 01:13:53 +0000420 ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4',
421 '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000422
Raymond Hettingerc7bab7c2016-08-31 15:01:08 -0700423 def test_bug_27706(self):
424 # Verify that version 1 seeds are unaffected by hash randomization
425
426 self.gen.seed('nofar', version=1) # hash('nofar') == 5990528763808513177
427 self.assertEqual([self.gen.random().hex() for i in range(4)],
428 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
429 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
430
431 self.gen.seed('rachel', version=1) # hash('rachel') == -9091735575445484789
432 self.assertEqual([self.gen.random().hex() for i in range(4)],
433 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
434 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
435
436 self.gen.seed('', version=1) # hash('') == 0
437 self.assertEqual([self.gen.random().hex() for i in range(4)],
438 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
439 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
440
Oren Milmand780b2d2017-09-28 10:50:01 +0300441 def test_bug_31478(self):
442 # There shouldn't be an assertion failure in _random.Random.seed() in
443 # case the argument has a bad __abs__() method.
444 class BadInt(int):
445 def __abs__(self):
446 return None
447 try:
448 self.gen.seed(BadInt())
449 except TypeError:
450 pass
451
Raymond Hettinger132a7d72017-09-17 09:04:30 -0700452 def test_bug_31482(self):
453 # Verify that version 1 seeds are unaffected by hash randomization
454 # when the seeds are expressed as bytes rather than strings.
455 # The hash(b) values listed are the Python2.7 hash() values
456 # which were used for seeding.
457
458 self.gen.seed(b'nofar', version=1) # hash('nofar') == 5990528763808513177
459 self.assertEqual([self.gen.random().hex() for i in range(4)],
460 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
461 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
462
463 self.gen.seed(b'rachel', version=1) # hash('rachel') == -9091735575445484789
464 self.assertEqual([self.gen.random().hex() for i in range(4)],
465 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
466 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
467
468 self.gen.seed(b'', version=1) # hash('') == 0
469 self.assertEqual([self.gen.random().hex() for i in range(4)],
470 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
471 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
472
473 b = b'\x00\x20\x40\x60\x80\xA0\xC0\xE0\xF0'
474 self.gen.seed(b, version=1) # hash(b) == 5015594239749365497
475 self.assertEqual([self.gen.random().hex() for i in range(4)],
476 ['0x1.52c2fde444d23p-1', '0x1.875174f0daea4p-2',
477 '0x1.9e9b2c50e5cd2p-1', '0x1.fa57768bd321cp-2'])
478
Raymond Hettinger58335872004-07-09 14:26:18 +0000479 def test_setstate_first_arg(self):
480 self.assertRaises(ValueError, self.gen.setstate, (1, None, None))
481
482 def test_setstate_middle_arg(self):
bladebryan9616a822017-04-21 23:10:46 -0700483 start_state = self.gen.getstate()
Raymond Hettinger58335872004-07-09 14:26:18 +0000484 # Wrong type, s/b tuple
485 self.assertRaises(TypeError, self.gen.setstate, (2, None, None))
486 # Wrong length, s/b 625
487 self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None))
488 # Wrong type, s/b tuple of 625 ints
489 self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None))
490 # Last element s/b an int also
491 self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None))
Serhiy Storchaka178f0b62015-07-24 09:02:53 +0300492 # Last element s/b between 0 and 624
493 with self.assertRaises((ValueError, OverflowError)):
494 self.gen.setstate((2, (1,)*624+(625,), None))
495 with self.assertRaises((ValueError, OverflowError)):
496 self.gen.setstate((2, (1,)*624+(-1,), None))
bladebryan9616a822017-04-21 23:10:46 -0700497 # Failed calls to setstate() should not have changed the state.
498 bits100 = self.gen.getrandbits(100)
499 self.gen.setstate(start_state)
500 self.assertEqual(self.gen.getrandbits(100), bits100)
Raymond Hettinger58335872004-07-09 14:26:18 +0000501
R David Murraye3e1c172013-04-02 12:47:23 -0400502 # Little trick to make "tuple(x % (2**32) for x in internalstate)"
503 # raise ValueError. I cannot think of a simple way to achieve this, so
504 # I am opting for using a generator as the middle argument of setstate
505 # which attempts to cast a NaN to integer.
506 state_values = self.gen.getstate()[1]
507 state_values = list(state_values)
508 state_values[-1] = float('nan')
509 state = (int(x) for x in state_values)
510 self.assertRaises(TypeError, self.gen.setstate, (2, state, None))
511
Raymond Hettinger40f62172002-12-29 23:03:38 +0000512 def test_referenceImplementation(self):
513 # Compare the python implementation with results from the original
514 # code. Create 2000 53-bit precision random floats. Compare only
515 # the last ten entries to show that the independent implementations
516 # are tracking. Here is the main() function needed to create the
517 # list of expected random numbers:
518 # void main(void){
519 # int i;
520 # unsigned long init[4]={61731, 24903, 614, 42143}, length=4;
521 # init_by_array(init, length);
522 # for (i=0; i<2000; i++) {
523 # printf("%.15f ", genrand_res53());
524 # if (i%5==4) printf("\n");
525 # }
526 # }
527 expected = [0.45839803073713259,
528 0.86057815201978782,
529 0.92848331726782152,
530 0.35932681119782461,
531 0.081823493762449573,
532 0.14332226470169329,
533 0.084297823823520024,
534 0.53814864671831453,
535 0.089215024911993401,
536 0.78486196105372907]
537
Guido van Rossume2a383d2007-01-15 16:59:06 +0000538 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000539 actual = self.randomlist(2000)[-10:]
540 for a, e in zip(actual, expected):
541 self.assertAlmostEqual(a,e,places=14)
542
543 def test_strong_reference_implementation(self):
544 # Like test_referenceImplementation, but checks for exact bit-level
545 # equality. This should pass on any box where C double contains
546 # at least 53 bits of precision (the underlying algorithm suffers
547 # no rounding errors -- all results are exact).
548 from math import ldexp
549
Guido van Rossume2a383d2007-01-15 16:59:06 +0000550 expected = [0x0eab3258d2231f,
551 0x1b89db315277a5,
552 0x1db622a5518016,
553 0x0b7f9af0d575bf,
554 0x029e4c4db82240,
555 0x04961892f5d673,
556 0x02b291598e4589,
557 0x11388382c15694,
558 0x02dad977c9e1fe,
559 0x191d96d4d334c6]
560 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000561 actual = self.randomlist(2000)[-10:]
562 for a, e in zip(actual, expected):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000563 self.assertEqual(int(ldexp(a, 53)), e)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000564
565 def test_long_seed(self):
566 # This is most interesting to run in debug mode, just to make sure
567 # nothing blows up. Under the covers, a dynamically resized array
568 # is allocated, consuming space proportional to the number of bits
569 # in the seed. Unfortunately, that's a quadratic-time algorithm,
570 # so don't make this horribly big.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000571 seed = (1 << (10000 * 8)) - 1 # about 10K bytes
Raymond Hettinger40f62172002-12-29 23:03:38 +0000572 self.gen.seed(seed)
573
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000574 def test_53_bits_per_float(self):
575 # This should pass whenever a C double has 53 bit precision.
576 span = 2 ** 53
577 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000578 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000579 cum |= int(self.gen.random() * span)
580 self.assertEqual(cum, span-1)
581
582 def test_bigrand(self):
583 # The randrange routine should build-up the required number of bits
584 # in stages so that all bit positions are active.
585 span = 2 ** 500
586 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000587 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000588 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000589 self.assertTrue(0 <= r < span)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000590 cum |= r
591 self.assertEqual(cum, span-1)
592
593 def test_bigrand_ranges(self):
594 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600595 start = self.gen.randrange(2 ** (i-2))
596 stop = self.gen.randrange(2 ** i)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000597 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600598 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000599 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000600
601 def test_rangelimits(self):
602 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
Raymond Hettingera690a992003-11-16 16:17:49 +0000603 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000604 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000605
606 def test_genrandbits(self):
607 # Verify cross-platform repeatability
608 self.gen.seed(1234567)
609 self.assertEqual(self.gen.getrandbits(100),
Guido van Rossume2a383d2007-01-15 16:59:06 +0000610 97904845777343510404718956115)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000611 # Verify ranges
Guido van Rossum805365e2007-05-07 22:24:25 +0000612 for k in range(1, 1000):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000613 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000614
615 # Verify all bits active
616 getbits = self.gen.getrandbits
617 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
618 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000619 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000620 cum |= getbits(span)
621 self.assertEqual(cum, 2**span-1)
622
Raymond Hettinger58335872004-07-09 14:26:18 +0000623 # Verify argument checking
624 self.assertRaises(TypeError, self.gen.getrandbits)
625 self.assertRaises(TypeError, self.gen.getrandbits, 'a')
626 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
627 self.assertRaises(ValueError, self.gen.getrandbits, 0)
628 self.assertRaises(ValueError, self.gen.getrandbits, -1)
629
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200630 def test_randrange_uses_getrandbits(self):
631 # Verify use of getrandbits by randrange
632 # Use same seed as in the cross-platform repeatability test
633 # in test_genrandbits above.
634 self.gen.seed(1234567)
635 # If randrange uses getrandbits, it should pick getrandbits(100)
636 # when called with a 100-bits stop argument.
637 self.assertEqual(self.gen.randrange(2**99),
638 97904845777343510404718956115)
639
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000640 def test_randbelow_logic(self, _log=log, int=int):
641 # check bitcount transition points: 2**i and 2**(i+1)-1
642 # show that: k = int(1.001 + _log(n, 2))
643 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000644 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000645 n = 1 << i # check an exact power of two
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000646 numbits = i+1
647 k = int(1.00001 + _log(n, 2))
648 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000649 self.assertEqual(n, 2**(k-1))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000650
651 n += n - 1 # check 1 below the next power of two
652 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000653 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000654 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000655
656 n -= n >> 15 # check a little farther below the next power of two
657 k = int(1.00001 + _log(n, 2))
658 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000659 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000660
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200661 def test_randbelow_without_getrandbits(self):
R David Murraye3e1c172013-04-02 12:47:23 -0400662 # Random._randbelow() can only use random() when the built-in one
663 # has been overridden but no new getrandbits() method was supplied.
R David Murraye3e1c172013-04-02 12:47:23 -0400664 maxsize = 1<<random.BPF
665 with warnings.catch_warnings():
666 warnings.simplefilter("ignore", UserWarning)
667 # Population range too large (n >= maxsize)
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200668 self.gen._randbelow_without_getrandbits(
669 maxsize+1, maxsize=maxsize
670 )
671 self.gen._randbelow_without_getrandbits(5640, maxsize=maxsize)
Wolfgang Maier091e95e2018-04-05 17:19:44 +0200672 # issue 33203: test that _randbelow raises ValueError on
673 # n == 0 also in its getrandbits-independent branch.
674 with self.assertRaises(ValueError):
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200675 self.gen._randbelow_without_getrandbits(0, maxsize=maxsize)
676
R David Murraye3e1c172013-04-02 12:47:23 -0400677 # This might be going too far to test a single line, but because of our
678 # noble aim of achieving 100% test coverage we need to write a case in
679 # which the following line in Random._randbelow() gets executed:
680 #
681 # rem = maxsize % n
682 # limit = (maxsize - rem) / maxsize
683 # r = random()
684 # while r >= limit:
685 # r = random() # <== *This line* <==<
686 #
687 # Therefore, to guarantee that the while loop is executed at least
688 # once, we need to mock random() so that it returns a number greater
689 # than 'limit' the first time it gets called.
690
691 n = 42
692 epsilon = 0.01
693 limit = (maxsize - (maxsize % n)) / maxsize
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200694 with unittest.mock.patch.object(random.Random, 'random') as random_mock:
695 random_mock.side_effect = [limit + epsilon, limit - epsilon]
696 self.gen._randbelow_without_getrandbits(n, maxsize=maxsize)
697 self.assertEqual(random_mock.call_count, 2)
R David Murraye3e1c172013-04-02 12:47:23 -0400698
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000699 def test_randrange_bug_1590891(self):
700 start = 1000000000000
701 stop = -100000000000000000000
702 step = -200
703 x = self.gen.randrange(start, stop, step)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000704 self.assertTrue(stop < x <= start)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000705 self.assertEqual((x+stop)%step, 0)
706
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700707 def test_choices_algorithms(self):
Raymond Hettinger24e42392016-11-13 00:42:56 -0500708 # The various ways of specifying weights should produce the same results
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700709 choices = self.gen.choices
Raymond Hettinger6023d332016-11-21 15:32:08 -0800710 n = 104729
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700711
712 self.gen.seed(8675309)
713 a = self.gen.choices(range(n), k=10000)
714
715 self.gen.seed(8675309)
716 b = self.gen.choices(range(n), [1]*n, k=10000)
717 self.assertEqual(a, b)
718
719 self.gen.seed(8675309)
720 c = self.gen.choices(range(n), cum_weights=range(1, n+1), k=10000)
721 self.assertEqual(a, c)
722
Raymond Hettinger77d574d2016-10-29 17:42:36 -0700723 # Amerian Roulette
724 population = ['Red', 'Black', 'Green']
725 weights = [18, 18, 2]
726 cum_weights = [18, 36, 38]
727 expanded_population = ['Red'] * 18 + ['Black'] * 18 + ['Green'] * 2
728
729 self.gen.seed(9035768)
730 a = self.gen.choices(expanded_population, k=10000)
731
732 self.gen.seed(9035768)
733 b = self.gen.choices(population, weights, k=10000)
734 self.assertEqual(a, b)
735
736 self.gen.seed(9035768)
737 c = self.gen.choices(population, cum_weights=cum_weights, k=10000)
738 self.assertEqual(a, c)
739
Raymond Hettinger2d0c2562009-02-19 09:53:18 +0000740def gamma(z, sqrt2pi=(2.0*pi)**0.5):
741 # Reflection to right half of complex plane
742 if z < 0.5:
743 return pi / sin(pi*z) / gamma(1.0-z)
744 # Lanczos approximation with g=7
745 az = z + (7.0 - 0.5)
746 return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
747 0.9999999999995183,
748 676.5203681218835 / z,
749 -1259.139216722289 / (z+1.0),
750 771.3234287757674 / (z+2.0),
751 -176.6150291498386 / (z+3.0),
752 12.50734324009056 / (z+4.0),
753 -0.1385710331296526 / (z+5.0),
754 0.9934937113930748e-05 / (z+6.0),
755 0.1659470187408462e-06 / (z+7.0),
756 ])
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000757
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000758class TestDistributions(unittest.TestCase):
759 def test_zeroinputs(self):
760 # Verify that distributions can handle a series of zero inputs'
761 g = random.Random()
Guido van Rossum805365e2007-05-07 22:24:25 +0000762 x = [g.random() for i in range(50)] + [0.0]*5
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000763 g.random = x[:].pop; g.uniform(1,10)
764 g.random = x[:].pop; g.paretovariate(1.0)
765 g.random = x[:].pop; g.expovariate(1.0)
766 g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200767 g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000768 g.random = x[:].pop; g.normalvariate(0.0, 1.0)
769 g.random = x[:].pop; g.gauss(0.0, 1.0)
770 g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
771 g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
772 g.random = x[:].pop; g.gammavariate(0.01, 1.0)
773 g.random = x[:].pop; g.gammavariate(1.0, 1.0)
774 g.random = x[:].pop; g.gammavariate(200.0, 1.0)
775 g.random = x[:].pop; g.betavariate(3.0, 3.0)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000776 g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000777
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000778 def test_avg_std(self):
779 # Use integration to test distribution average and standard deviation.
780 # Only works for distributions which do not consume variates in pairs
781 g = random.Random()
782 N = 5000
Guido van Rossum805365e2007-05-07 22:24:25 +0000783 x = [i/float(N) for i in range(1,N)]
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000784 for variate, args, mu, sigmasqrd in [
785 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
Christian Heimesfe337bf2008-03-23 21:54:12 +0000786 (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 +0000787 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200788 (g.vonmisesvariate, (1.23, 0), pi, pi**2/3),
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000789 (g.paretovariate, (5.0,), 5.0/(5.0-1),
790 5.0/((5.0-1)**2*(5.0-2))),
791 (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0),
792 gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
793 g.random = x[:].pop
794 y = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000795 for i in range(len(x)):
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000796 try:
797 y.append(variate(*args))
798 except IndexError:
799 pass
800 s1 = s2 = 0
801 for e in y:
802 s1 += e
803 s2 += (e - mu) ** 2
804 N = len(y)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200805 self.assertAlmostEqual(s1/N, mu, places=2,
806 msg='%s%r' % (variate.__name__, args))
807 self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2,
808 msg='%s%r' % (variate.__name__, args))
809
810 def test_constant(self):
811 g = random.Random()
812 N = 100
813 for variate, args, expected in [
814 (g.uniform, (10.0, 10.0), 10.0),
815 (g.triangular, (10.0, 10.0), 10.0),
Raymond Hettinger978c6ab2014-05-25 17:25:27 -0700816 (g.triangular, (10.0, 10.0, 10.0), 10.0),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200817 (g.expovariate, (float('inf'),), 0.0),
818 (g.vonmisesvariate, (3.0, float('inf')), 3.0),
819 (g.gauss, (10.0, 0.0), 10.0),
820 (g.lognormvariate, (0.0, 0.0), 1.0),
821 (g.lognormvariate, (-float('inf'), 0.0), 0.0),
822 (g.normalvariate, (10.0, 0.0), 10.0),
823 (g.paretovariate, (float('inf'),), 1.0),
824 (g.weibullvariate, (10.0, float('inf')), 10.0),
825 (g.weibullvariate, (0.0, 10.0), 0.0),
826 ]:
827 for i in range(N):
828 self.assertEqual(variate(*args), expected)
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000829
Mark Dickinsonbe5f9192013-02-10 14:16:10 +0000830 def test_von_mises_range(self):
831 # Issue 17149: von mises variates were not consistently in the
832 # range [0, 2*PI].
833 g = random.Random()
834 N = 100
835 for mu in 0.0, 0.1, 3.1, 6.2:
836 for kappa in 0.0, 2.3, 500.0:
837 for _ in range(N):
838 sample = g.vonmisesvariate(mu, kappa)
839 self.assertTrue(
840 0 <= sample <= random.TWOPI,
841 msg=("vonmisesvariate({}, {}) produced a result {} out"
842 " of range [0, 2*pi]").format(mu, kappa, sample))
843
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200844 def test_von_mises_large_kappa(self):
845 # Issue #17141: vonmisesvariate() was hang for large kappas
846 random.vonmisesvariate(0, 1e15)
847 random.vonmisesvariate(0, 1e100)
848
R David Murraye3e1c172013-04-02 12:47:23 -0400849 def test_gammavariate_errors(self):
850 # Both alpha and beta must be > 0.0
851 self.assertRaises(ValueError, random.gammavariate, -1, 3)
852 self.assertRaises(ValueError, random.gammavariate, 0, 2)
853 self.assertRaises(ValueError, random.gammavariate, 2, 0)
854 self.assertRaises(ValueError, random.gammavariate, 1, -3)
855
leodema63d15222018-12-24 07:54:25 +0100856 # There are three different possibilities in the current implementation
857 # of random.gammavariate(), depending on the value of 'alpha'. What we
858 # are going to do here is to fix the values returned by random() to
859 # generate test cases that provide 100% line coverage of the method.
R David Murraye3e1c172013-04-02 12:47:23 -0400860 @unittest.mock.patch('random.Random.random')
leodema63d15222018-12-24 07:54:25 +0100861 def test_gammavariate_alpha_greater_one(self, random_mock):
R David Murraye3e1c172013-04-02 12:47:23 -0400862
leodema63d15222018-12-24 07:54:25 +0100863 # #1: alpha > 1.0.
864 # We want the first random number to be outside the
R David Murraye3e1c172013-04-02 12:47:23 -0400865 # [1e-7, .9999999] range, so that the continue statement executes
866 # once. The values of u1 and u2 will be 0.5 and 0.3, respectively.
867 random_mock.side_effect = [1e-8, 0.5, 0.3]
868 returned_value = random.gammavariate(1.1, 2.3)
869 self.assertAlmostEqual(returned_value, 2.53)
870
leodema63d15222018-12-24 07:54:25 +0100871 @unittest.mock.patch('random.Random.random')
872 def test_gammavariate_alpha_equal_one(self, random_mock):
R David Murraye3e1c172013-04-02 12:47:23 -0400873
leodema63d15222018-12-24 07:54:25 +0100874 # #2.a: alpha == 1.
875 # The execution body of the while loop executes once.
876 # Then random.random() returns 0.45,
877 # which causes while to stop looping and the algorithm to terminate.
878 random_mock.side_effect = [0.45]
879 returned_value = random.gammavariate(1.0, 3.14)
880 self.assertAlmostEqual(returned_value, 1.877208182372648)
881
882 @unittest.mock.patch('random.Random.random')
883 def test_gammavariate_alpha_equal_one_equals_expovariate(self, random_mock):
884
885 # #2.b: alpha == 1.
886 # It must be equivalent of calling expovariate(1.0 / beta).
887 beta = 3.14
888 random_mock.side_effect = [1e-8, 1e-8]
889 gammavariate_returned_value = random.gammavariate(1.0, beta)
890 expovariate_returned_value = random.expovariate(1.0 / beta)
891 self.assertAlmostEqual(gammavariate_returned_value, expovariate_returned_value)
892
893 @unittest.mock.patch('random.Random.random')
894 def test_gammavariate_alpha_between_zero_and_one(self, random_mock):
895
896 # #3: 0 < alpha < 1.
897 # This is the most complex region of code to cover,
R David Murraye3e1c172013-04-02 12:47:23 -0400898 # as there are multiple if-else statements. Let's take a look at the
899 # source code, and determine the values that we need accordingly:
900 #
901 # while 1:
902 # u = random()
903 # b = (_e + alpha)/_e
904 # p = b*u
905 # if p <= 1.0: # <=== (A)
906 # x = p ** (1.0/alpha)
907 # else: # <=== (B)
908 # x = -_log((b-p)/alpha)
909 # u1 = random()
910 # if p > 1.0: # <=== (C)
911 # if u1 <= x ** (alpha - 1.0): # <=== (D)
912 # break
913 # elif u1 <= _exp(-x): # <=== (E)
914 # break
915 # return x * beta
916 #
917 # First, we want (A) to be True. For that we need that:
918 # b*random() <= 1.0
919 # r1 = random() <= 1.0 / b
920 #
921 # We now get to the second if-else branch, and here, since p <= 1.0,
922 # (C) is False and we take the elif branch, (E). For it to be True,
923 # so that the break is executed, we need that:
924 # r2 = random() <= _exp(-x)
925 # r2 <= _exp(-(p ** (1.0/alpha)))
926 # r2 <= _exp(-((b*r1) ** (1.0/alpha)))
927
928 _e = random._e
929 _exp = random._exp
930 _log = random._log
931 alpha = 0.35
932 beta = 1.45
933 b = (_e + alpha)/_e
934 epsilon = 0.01
935
936 r1 = 0.8859296441566 # 1.0 / b
937 r2 = 0.3678794411714 # _exp(-((b*r1) ** (1.0/alpha)))
938
939 # These four "random" values result in the following trace:
940 # (A) True, (E) False --> [next iteration of while]
941 # (A) True, (E) True --> [while loop breaks]
942 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
943 returned_value = random.gammavariate(alpha, beta)
944 self.assertAlmostEqual(returned_value, 1.4499999999997544)
945
946 # Let's now make (A) be False. If this is the case, when we get to the
947 # second if-else 'p' is greater than 1, so (C) evaluates to True. We
948 # now encounter a second if statement, (D), which in order to execute
949 # must satisfy the following condition:
950 # r2 <= x ** (alpha - 1.0)
951 # r2 <= (-_log((b-p)/alpha)) ** (alpha - 1.0)
952 # r2 <= (-_log((b-(b*r1))/alpha)) ** (alpha - 1.0)
953 r1 = 0.8959296441566 # (1.0 / b) + epsilon -- so that (A) is False
954 r2 = 0.9445400408898141
955
956 # And these four values result in the following trace:
957 # (B) and (C) True, (D) False --> [next iteration of while]
958 # (B) and (C) True, (D) True [while loop breaks]
959 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
960 returned_value = random.gammavariate(alpha, beta)
961 self.assertAlmostEqual(returned_value, 1.5830349561760781)
962
963 @unittest.mock.patch('random.Random.gammavariate')
964 def test_betavariate_return_zero(self, gammavariate_mock):
965 # betavariate() returns zero when the Gamma distribution
966 # that it uses internally returns this same value.
967 gammavariate_mock.return_value = 0.0
968 self.assertEqual(0.0, random.betavariate(2.71828, 3.14159))
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200969
Serhiy Storchakaec1622d2018-05-08 15:45:15 +0300970
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200971class TestRandomSubclassing(unittest.TestCase):
972 def test_random_subclass_with_kwargs(self):
973 # SF bug #1486663 -- this used to erroneously raise a TypeError
974 class Subclass(random.Random):
975 def __init__(self, newarg=None):
976 random.Random.__init__(self)
977 Subclass(newarg=1)
978
979 def test_subclasses_overriding_methods(self):
980 # Subclasses with an overridden random, but only the original
981 # getrandbits method should not rely on getrandbits in for randrange,
982 # but should use a getrandbits-independent implementation instead.
983
984 # subclass providing its own random **and** getrandbits methods
985 # like random.SystemRandom does => keep relying on getrandbits for
986 # randrange
987 class SubClass1(random.Random):
988 def random(self):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +0300989 called.add('SubClass1.random')
990 return random.Random.random(self)
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200991
992 def getrandbits(self, n):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +0300993 called.add('SubClass1.getrandbits')
994 return random.Random.getrandbits(self, n)
995 called = set()
996 SubClass1().randrange(42)
997 self.assertEqual(called, {'SubClass1.getrandbits'})
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200998
999 # subclass providing only random => can only use random for randrange
1000 class SubClass2(random.Random):
1001 def random(self):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001002 called.add('SubClass2.random')
1003 return random.Random.random(self)
1004 called = set()
1005 SubClass2().randrange(42)
1006 self.assertEqual(called, {'SubClass2.random'})
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001007
1008 # subclass defining getrandbits to complement its inherited random
1009 # => can now rely on getrandbits for randrange again
1010 class SubClass3(SubClass2):
1011 def getrandbits(self, n):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001012 called.add('SubClass3.getrandbits')
1013 return random.Random.getrandbits(self, n)
1014 called = set()
1015 SubClass3().randrange(42)
1016 self.assertEqual(called, {'SubClass3.getrandbits'})
1017
1018 # subclass providing only random and inherited getrandbits
1019 # => random takes precedence
1020 class SubClass4(SubClass3):
1021 def random(self):
1022 called.add('SubClass4.random')
1023 return random.Random.random(self)
1024 called = set()
1025 SubClass4().randrange(42)
1026 self.assertEqual(called, {'SubClass4.random'})
1027
1028 # Following subclasses don't define random or getrandbits directly,
1029 # but inherit them from classes which are not subclasses of Random
1030 class Mixin1:
1031 def random(self):
1032 called.add('Mixin1.random')
1033 return random.Random.random(self)
1034 class Mixin2:
1035 def getrandbits(self, n):
1036 called.add('Mixin2.getrandbits')
1037 return random.Random.getrandbits(self, n)
1038
1039 class SubClass5(Mixin1, random.Random):
1040 pass
1041 called = set()
1042 SubClass5().randrange(42)
1043 self.assertEqual(called, {'Mixin1.random'})
1044
1045 class SubClass6(Mixin2, random.Random):
1046 pass
1047 called = set()
1048 SubClass6().randrange(42)
1049 self.assertEqual(called, {'Mixin2.getrandbits'})
1050
1051 class SubClass7(Mixin1, Mixin2, random.Random):
1052 pass
1053 called = set()
1054 SubClass7().randrange(42)
1055 self.assertEqual(called, {'Mixin1.random'})
1056
1057 class SubClass8(Mixin2, Mixin1, random.Random):
1058 pass
1059 called = set()
1060 SubClass8().randrange(42)
1061 self.assertEqual(called, {'Mixin2.getrandbits'})
1062
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001063
Raymond Hettinger40f62172002-12-29 23:03:38 +00001064class TestModule(unittest.TestCase):
1065 def testMagicConstants(self):
1066 self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141)
1067 self.assertAlmostEqual(random.TWOPI, 6.28318530718)
1068 self.assertAlmostEqual(random.LOG4, 1.38629436111989)
1069 self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627)
1070
1071 def test__all__(self):
1072 # tests validity but not completeness of the __all__ list
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001073 self.assertTrue(set(random.__all__) <= set(dir(random)))
Raymond Hettinger40f62172002-12-29 23:03:38 +00001074
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001075 @unittest.skipUnless(hasattr(os, "fork"), "fork() required")
1076 def test_after_fork(self):
1077 # Test the global Random instance gets reseeded in child
1078 r, w = os.pipe()
Victor Stinnerda5e9302017-08-09 17:59:05 +02001079 pid = os.fork()
1080 if pid == 0:
1081 # child process
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001082 try:
1083 val = random.getrandbits(128)
1084 with open(w, "w") as f:
1085 f.write(str(val))
1086 finally:
1087 os._exit(0)
1088 else:
Victor Stinnerda5e9302017-08-09 17:59:05 +02001089 # parent process
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001090 os.close(w)
1091 val = random.getrandbits(128)
1092 with open(r, "r") as f:
1093 child_val = eval(f.read())
1094 self.assertNotEqual(val, child_val)
1095
Victor Stinnerda5e9302017-08-09 17:59:05 +02001096 pid, status = os.waitpid(pid, 0)
1097 self.assertEqual(status, 0)
1098
Thomas Woutersb2137042007-02-01 18:02:27 +00001099
Raymond Hettinger40f62172002-12-29 23:03:38 +00001100if __name__ == "__main__":
Ezio Melotti3e4a98b2013-04-19 05:45:27 +03001101 unittest.main()