blob: 840f3e7ce81b6147709d78e37612ee1ae578d2b7 [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
Raymond Hettinger40f62172002-12-29 23:03:38 +00004import time
Raymond Hettinger5f078ff2003-06-24 20:29:04 +00005import pickle
Raymond Hettinger2f726e92003-10-05 09:09:15 +00006import warnings
R David Murraye3e1c172013-04-02 12:47:23 -04007from functools import partial
Georg Brandl1b37e872010-03-14 10:45:50 +00008from math import log, exp, pi, fsum, sin
Benjamin Petersonee8712c2008-05-20 21:35:26 +00009from test import support
Raymond Hettingere8f1e002016-09-06 17:15:29 -070010from fractions import Fraction
Tim Peters46c04e12002-05-05 20:40:00 +000011
Ezio Melotti3e4a98b2013-04-19 05:45:27 +030012class TestBasicOps:
Raymond Hettinger40f62172002-12-29 23:03:38 +000013 # Superclass with tests common to all generators.
14 # Subclasses must arrange for self.gen to retrieve the Random instance
15 # to be tested.
Tim Peters46c04e12002-05-05 20:40:00 +000016
Raymond Hettinger40f62172002-12-29 23:03:38 +000017 def randomlist(self, n):
18 """Helper function to make a list of random numbers"""
Guido van Rossum805365e2007-05-07 22:24:25 +000019 return [self.gen.random() for i in range(n)]
Tim Peters46c04e12002-05-05 20:40:00 +000020
Raymond Hettinger40f62172002-12-29 23:03:38 +000021 def test_autoseed(self):
22 self.gen.seed()
23 state1 = self.gen.getstate()
Raymond Hettinger3081d592003-08-09 18:30:57 +000024 time.sleep(0.1)
Raymond Hettinger40f62172002-12-29 23:03:38 +000025 self.gen.seed() # diffent seeds at different times
26 state2 = self.gen.getstate()
27 self.assertNotEqual(state1, state2)
Tim Peters46c04e12002-05-05 20:40:00 +000028
Raymond Hettinger40f62172002-12-29 23:03:38 +000029 def test_saverestore(self):
30 N = 1000
31 self.gen.seed()
32 state = self.gen.getstate()
33 randseq = self.randomlist(N)
34 self.gen.setstate(state) # should regenerate the same sequence
35 self.assertEqual(randseq, self.randomlist(N))
36
37 def test_seedargs(self):
Mark Dickinson95aeae02012-06-24 11:05:30 +010038 # Seed value with a negative hash.
39 class MySeed(object):
40 def __hash__(self):
41 return -1729
Guido van Rossume2a383d2007-01-15 16:59:06 +000042 for arg in [None, 0, 0, 1, 1, -1, -1, 10**20, -(10**20),
Mark Dickinson95aeae02012-06-24 11:05:30 +010043 3.14, 1+2j, 'a', tuple('abc'), MySeed()]:
Raymond Hettinger40f62172002-12-29 23:03:38 +000044 self.gen.seed(arg)
Guido van Rossum805365e2007-05-07 22:24:25 +000045 for arg in [list(range(3)), dict(one=1)]:
Raymond Hettinger40f62172002-12-29 23:03:38 +000046 self.assertRaises(TypeError, self.gen.seed, arg)
Raymond Hettingerf763a722010-09-07 00:38:15 +000047 self.assertRaises(TypeError, self.gen.seed, 1, 2, 3, 4)
Raymond Hettinger58335872004-07-09 14:26:18 +000048 self.assertRaises(TypeError, type(self.gen), [])
Raymond Hettinger40f62172002-12-29 23:03:38 +000049
R David Murraye3e1c172013-04-02 12:47:23 -040050 @unittest.mock.patch('random._urandom') # os.urandom
51 def test_seed_when_randomness_source_not_found(self, urandom_mock):
52 # Random.seed() uses time.time() when an operating system specific
53 # randomness source is not found. To test this on machines were it
54 # exists, run the above test, test_seedargs(), again after mocking
55 # os.urandom() so that it raises the exception expected when the
56 # randomness source is not available.
57 urandom_mock.side_effect = NotImplementedError
58 self.test_seedargs()
59
Antoine Pitrou5e394332012-11-04 02:10:33 +010060 def test_shuffle(self):
61 shuffle = self.gen.shuffle
62 lst = []
63 shuffle(lst)
64 self.assertEqual(lst, [])
65 lst = [37]
66 shuffle(lst)
67 self.assertEqual(lst, [37])
68 seqs = [list(range(n)) for n in range(10)]
69 shuffled_seqs = [list(range(n)) for n in range(10)]
70 for shuffled_seq in shuffled_seqs:
71 shuffle(shuffled_seq)
72 for (seq, shuffled_seq) in zip(seqs, shuffled_seqs):
73 self.assertEqual(len(seq), len(shuffled_seq))
74 self.assertEqual(set(seq), set(shuffled_seq))
Antoine Pitrou5e394332012-11-04 02:10:33 +010075 # The above tests all would pass if the shuffle was a
76 # no-op. The following non-deterministic test covers that. It
77 # asserts that the shuffled sequence of 1000 distinct elements
78 # must be different from the original one. Although there is
79 # mathematically a non-zero probability that this could
80 # actually happen in a genuinely random shuffle, it is
81 # completely negligible, given that the number of possible
82 # permutations of 1000 objects is 1000! (factorial of 1000),
83 # which is considerably larger than the number of atoms in the
84 # universe...
85 lst = list(range(1000))
86 shuffled_lst = list(range(1000))
87 shuffle(shuffled_lst)
88 self.assertTrue(lst != shuffled_lst)
89 shuffle(lst)
90 self.assertTrue(lst != shuffled_lst)
91
Raymond Hettingerdc4872e2010-09-07 10:06:56 +000092 def test_choice(self):
93 choice = self.gen.choice
94 with self.assertRaises(IndexError):
95 choice([])
96 self.assertEqual(choice([50]), 50)
97 self.assertIn(choice([25, 75]), [25, 75])
98
Raymond Hettinger40f62172002-12-29 23:03:38 +000099 def test_sample(self):
100 # For the entire allowable range of 0 <= k <= N, validate that
101 # the sample is of the correct length and contains only unique items
102 N = 100
Guido van Rossum805365e2007-05-07 22:24:25 +0000103 population = range(N)
104 for k in range(N+1):
Raymond Hettinger40f62172002-12-29 23:03:38 +0000105 s = self.gen.sample(population, k)
106 self.assertEqual(len(s), k)
Raymond Hettingera690a992003-11-16 16:17:49 +0000107 uniq = set(s)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000108 self.assertEqual(len(uniq), k)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000109 self.assertTrue(uniq <= set(population))
Raymond Hettinger8ec78812003-01-04 05:55:11 +0000110 self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0
R David Murraye3e1c172013-04-02 12:47:23 -0400111 # Exception raised if size of sample exceeds that of population
112 self.assertRaises(ValueError, self.gen.sample, population, N+1)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000113
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000114 def test_sample_distribution(self):
115 # For the entire allowable range of 0 <= k <= N, validate that
116 # sample generates all possible permutations
117 n = 5
118 pop = range(n)
119 trials = 10000 # large num prevents false negatives without slowing normal case
120 def factorial(n):
Guido van Rossum89da5d72006-08-22 00:21:25 +0000121 if n == 0:
122 return 1
123 return n * factorial(n - 1)
Guido van Rossum805365e2007-05-07 22:24:25 +0000124 for k in range(n):
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +0000125 expected = factorial(n) // factorial(n-k)
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000126 perms = {}
Guido van Rossum805365e2007-05-07 22:24:25 +0000127 for i in range(trials):
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000128 perms[tuple(self.gen.sample(pop, k))] = None
129 if len(perms) == expected:
130 break
131 else:
132 self.fail()
133
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000134 def test_sample_inputs(self):
135 # SF bug #801342 -- population can be any iterable defining __len__()
Raymond Hettingera690a992003-11-16 16:17:49 +0000136 self.gen.sample(set(range(20)), 2)
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000137 self.gen.sample(range(20), 2)
Guido van Rossum805365e2007-05-07 22:24:25 +0000138 self.gen.sample(range(20), 2)
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000139 self.gen.sample(str('abcdefghijklmnopqrst'), 2)
140 self.gen.sample(tuple('abcdefghijklmnopqrst'), 2)
141
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000142 def test_sample_on_dicts(self):
Raymond Hettinger1acde192008-01-14 01:00:53 +0000143 self.assertRaises(TypeError, self.gen.sample, dict.fromkeys('abcdef'), 2)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000144
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700145 def test_choices(self):
146 choices = self.gen.choices
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700147 data = ['red', 'green', 'blue', 'yellow']
148 str_data = 'abcd'
149 range_data = range(4)
150 set_data = set(range(4))
151
152 # basic functionality
153 for sample in [
Raymond Hettinger9016f282016-09-26 21:45:57 -0700154 choices(data, k=5),
155 choices(data, range(4), k=5),
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700156 choices(k=5, population=data, weights=range(4)),
157 choices(k=5, population=data, cum_weights=range(4)),
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700158 ]:
159 self.assertEqual(len(sample), 5)
160 self.assertEqual(type(sample), list)
161 self.assertTrue(set(sample) <= set(data))
162
163 # test argument handling
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700164 with self.assertRaises(TypeError): # missing arguments
165 choices(2)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700166
Raymond Hettinger9016f282016-09-26 21:45:57 -0700167 self.assertEqual(choices(data, k=0), []) # k == 0
168 self.assertEqual(choices(data, k=-1), []) # negative k behaves like ``[0] * -1``
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700169 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700170 choices(data, k=2.5) # k is a float
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700171
Raymond Hettinger9016f282016-09-26 21:45:57 -0700172 self.assertTrue(set(choices(str_data, k=5)) <= set(str_data)) # population is a string sequence
173 self.assertTrue(set(choices(range_data, k=5)) <= set(range_data)) # population is a range
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700174 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700175 choices(set_data, k=2) # population is not a sequence
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700176
Raymond Hettinger9016f282016-09-26 21:45:57 -0700177 self.assertTrue(set(choices(data, None, k=5)) <= set(data)) # weights is None
178 self.assertTrue(set(choices(data, weights=None, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700179 with self.assertRaises(ValueError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700180 choices(data, [1,2], k=5) # len(weights) != len(population)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700181 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700182 choices(data, 10, k=5) # non-iterable weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700183 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700184 choices(data, [None]*4, k=5) # non-numeric weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700185 for weights in [
186 [15, 10, 25, 30], # integer weights
187 [15.1, 10.2, 25.2, 30.3], # float weights
188 [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional weights
189 [True, False, True, False] # booleans (include / exclude)
190 ]:
Raymond Hettinger9016f282016-09-26 21:45:57 -0700191 self.assertTrue(set(choices(data, weights, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700192
193 with self.assertRaises(ValueError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700194 choices(data, cum_weights=[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, cum_weights=10, k=5) # non-iterable cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700197 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700198 choices(data, cum_weights=[None]*4, k=5) # non-numeric cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700199 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700200 choices(data, range(4), cum_weights=range(4), k=5) # both weights and cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700201 for weights in [
202 [15, 10, 25, 30], # integer cum_weights
203 [15.1, 10.2, 25.2, 30.3], # float cum_weights
204 [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional cum_weights
205 ]:
Raymond Hettinger9016f282016-09-26 21:45:57 -0700206 self.assertTrue(set(choices(data, cum_weights=weights, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700207
Raymond Hettinger40f62172002-12-29 23:03:38 +0000208 def test_gauss(self):
209 # Ensure that the seed() method initializes all the hidden state. In
210 # particular, through 2.2.1 it failed to reset a piece of state used
211 # by (and only by) the .gauss() method.
212
213 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
214 self.gen.seed(seed)
215 x1 = self.gen.random()
216 y1 = self.gen.gauss(0, 1)
217
218 self.gen.seed(seed)
219 x2 = self.gen.random()
220 y2 = self.gen.gauss(0, 1)
221
222 self.assertEqual(x1, x2)
223 self.assertEqual(y1, y2)
224
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000225 def test_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200226 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
227 state = pickle.dumps(self.gen, proto)
228 origseq = [self.gen.random() for i in range(10)]
229 newgen = pickle.loads(state)
230 restoredseq = [newgen.random() for i in range(10)]
231 self.assertEqual(origseq, restoredseq)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000232
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000233 def test_bug_1727780(self):
234 # verify that version-2-pickles can be loaded
235 # fine, whether they are created on 32-bit or 64-bit
236 # platforms, and that version-3-pickles load fine.
237 files = [("randv2_32.pck", 780),
238 ("randv2_64.pck", 866),
239 ("randv3.pck", 343)]
240 for file, value in files:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000241 f = open(support.findfile(file),"rb")
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000242 r = pickle.load(f)
243 f.close()
Raymond Hettinger05156612010-09-07 04:44:52 +0000244 self.assertEqual(int(r.random()*1000), value)
245
246 def test_bug_9025(self):
247 # Had problem with an uneven distribution in int(n*random())
248 # Verify the fix by checking that distributions fall within expectations.
249 n = 100000
250 randrange = self.gen.randrange
251 k = sum(randrange(6755399441055744) % 3 == 2 for i in range(n))
252 self.assertTrue(0.30 < k/n < .37, (k/n))
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000253
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300254try:
255 random.SystemRandom().random()
256except NotImplementedError:
257 SystemRandom_available = False
258else:
259 SystemRandom_available = True
260
261@unittest.skipUnless(SystemRandom_available, "random.SystemRandom not available")
262class SystemRandom_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000263 gen = random.SystemRandom()
Raymond Hettinger356a4592004-08-30 06:14:31 +0000264
265 def test_autoseed(self):
266 # Doesn't need to do anything except not fail
267 self.gen.seed()
268
269 def test_saverestore(self):
270 self.assertRaises(NotImplementedError, self.gen.getstate)
271 self.assertRaises(NotImplementedError, self.gen.setstate, None)
272
273 def test_seedargs(self):
274 # Doesn't need to do anything except not fail
275 self.gen.seed(100)
276
Raymond Hettinger356a4592004-08-30 06:14:31 +0000277 def test_gauss(self):
278 self.gen.gauss_next = None
279 self.gen.seed(100)
280 self.assertEqual(self.gen.gauss_next, None)
281
282 def test_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200283 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
284 self.assertRaises(NotImplementedError, pickle.dumps, self.gen, proto)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000285
286 def test_53_bits_per_float(self):
287 # This should pass whenever a C double has 53 bit precision.
288 span = 2 ** 53
289 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000290 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000291 cum |= int(self.gen.random() * span)
292 self.assertEqual(cum, span-1)
293
294 def test_bigrand(self):
295 # The randrange routine should build-up the required number of bits
296 # in stages so that all bit positions are active.
297 span = 2 ** 500
298 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000299 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000300 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000301 self.assertTrue(0 <= r < span)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000302 cum |= r
303 self.assertEqual(cum, span-1)
304
305 def test_bigrand_ranges(self):
306 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600307 start = self.gen.randrange(2 ** (i-2))
308 stop = self.gen.randrange(2 ** i)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000309 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600310 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000311 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000312
313 def test_rangelimits(self):
314 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
315 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000316 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000317
R David Murraye3e1c172013-04-02 12:47:23 -0400318 def test_randrange_nonunit_step(self):
319 rint = self.gen.randrange(0, 10, 2)
320 self.assertIn(rint, (0, 2, 4, 6, 8))
321 rint = self.gen.randrange(0, 2, 2)
322 self.assertEqual(rint, 0)
323
324 def test_randrange_errors(self):
325 raises = partial(self.assertRaises, ValueError, self.gen.randrange)
326 # Empty range
327 raises(3, 3)
328 raises(-721)
329 raises(0, 100, -12)
330 # Non-integer start/stop
331 raises(3.14159)
332 raises(0, 2.71828)
333 # Zero and non-integer step
334 raises(0, 42, 0)
335 raises(0, 42, 3.14159)
336
Raymond Hettinger356a4592004-08-30 06:14:31 +0000337 def test_genrandbits(self):
338 # Verify ranges
Guido van Rossum805365e2007-05-07 22:24:25 +0000339 for k in range(1, 1000):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000340 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000341
342 # Verify all bits active
343 getbits = self.gen.getrandbits
344 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
345 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000346 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000347 cum |= getbits(span)
348 self.assertEqual(cum, 2**span-1)
349
350 # Verify argument checking
351 self.assertRaises(TypeError, self.gen.getrandbits)
352 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
353 self.assertRaises(ValueError, self.gen.getrandbits, 0)
354 self.assertRaises(ValueError, self.gen.getrandbits, -1)
355 self.assertRaises(TypeError, self.gen.getrandbits, 10.1)
356
357 def test_randbelow_logic(self, _log=log, int=int):
358 # check bitcount transition points: 2**i and 2**(i+1)-1
359 # show that: k = int(1.001 + _log(n, 2))
360 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000361 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000362 n = 1 << i # check an exact power of two
Raymond Hettinger356a4592004-08-30 06:14:31 +0000363 numbits = i+1
364 k = int(1.00001 + _log(n, 2))
365 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000366 self.assertEqual(n, 2**(k-1))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000367
368 n += n - 1 # check 1 below the next power of two
369 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000370 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000371 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000372
373 n -= n >> 15 # check a little farther below the next power of two
374 k = int(1.00001 + _log(n, 2))
375 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000376 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger356a4592004-08-30 06:14:31 +0000377
378
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300379class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger40f62172002-12-29 23:03:38 +0000380 gen = random.Random()
381
Raymond Hettingerf763a722010-09-07 00:38:15 +0000382 def test_guaranteed_stable(self):
383 # These sequences are guaranteed to stay the same across versions of python
384 self.gen.seed(3456147, version=1)
385 self.assertEqual([self.gen.random().hex() for i in range(4)],
386 ['0x1.ac362300d90d2p-1', '0x1.9d16f74365005p-1',
387 '0x1.1ebb4352e4c4dp-1', '0x1.1a7422abf9c11p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000388 self.gen.seed("the quick brown fox", version=2)
389 self.assertEqual([self.gen.random().hex() for i in range(4)],
Raymond Hettinger3fcf0022010-12-08 01:13:53 +0000390 ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4',
391 '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000392
Raymond Hettingerc7bab7c2016-08-31 15:01:08 -0700393 def test_bug_27706(self):
394 # Verify that version 1 seeds are unaffected by hash randomization
395
396 self.gen.seed('nofar', version=1) # hash('nofar') == 5990528763808513177
397 self.assertEqual([self.gen.random().hex() for i in range(4)],
398 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
399 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
400
401 self.gen.seed('rachel', version=1) # hash('rachel') == -9091735575445484789
402 self.assertEqual([self.gen.random().hex() for i in range(4)],
403 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
404 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
405
406 self.gen.seed('', version=1) # hash('') == 0
407 self.assertEqual([self.gen.random().hex() for i in range(4)],
408 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
409 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
410
Raymond Hettinger58335872004-07-09 14:26:18 +0000411 def test_setstate_first_arg(self):
412 self.assertRaises(ValueError, self.gen.setstate, (1, None, None))
413
414 def test_setstate_middle_arg(self):
415 # Wrong type, s/b tuple
416 self.assertRaises(TypeError, self.gen.setstate, (2, None, None))
417 # Wrong length, s/b 625
418 self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None))
419 # Wrong type, s/b tuple of 625 ints
420 self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None))
421 # Last element s/b an int also
422 self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None))
Serhiy Storchaka178f0b62015-07-24 09:02:53 +0300423 # Last element s/b between 0 and 624
424 with self.assertRaises((ValueError, OverflowError)):
425 self.gen.setstate((2, (1,)*624+(625,), None))
426 with self.assertRaises((ValueError, OverflowError)):
427 self.gen.setstate((2, (1,)*624+(-1,), None))
Raymond Hettinger58335872004-07-09 14:26:18 +0000428
R David Murraye3e1c172013-04-02 12:47:23 -0400429 # Little trick to make "tuple(x % (2**32) for x in internalstate)"
430 # raise ValueError. I cannot think of a simple way to achieve this, so
431 # I am opting for using a generator as the middle argument of setstate
432 # which attempts to cast a NaN to integer.
433 state_values = self.gen.getstate()[1]
434 state_values = list(state_values)
435 state_values[-1] = float('nan')
436 state = (int(x) for x in state_values)
437 self.assertRaises(TypeError, self.gen.setstate, (2, state, None))
438
Raymond Hettinger40f62172002-12-29 23:03:38 +0000439 def test_referenceImplementation(self):
440 # Compare the python implementation with results from the original
441 # code. Create 2000 53-bit precision random floats. Compare only
442 # the last ten entries to show that the independent implementations
443 # are tracking. Here is the main() function needed to create the
444 # list of expected random numbers:
445 # void main(void){
446 # int i;
447 # unsigned long init[4]={61731, 24903, 614, 42143}, length=4;
448 # init_by_array(init, length);
449 # for (i=0; i<2000; i++) {
450 # printf("%.15f ", genrand_res53());
451 # if (i%5==4) printf("\n");
452 # }
453 # }
454 expected = [0.45839803073713259,
455 0.86057815201978782,
456 0.92848331726782152,
457 0.35932681119782461,
458 0.081823493762449573,
459 0.14332226470169329,
460 0.084297823823520024,
461 0.53814864671831453,
462 0.089215024911993401,
463 0.78486196105372907]
464
Guido van Rossume2a383d2007-01-15 16:59:06 +0000465 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000466 actual = self.randomlist(2000)[-10:]
467 for a, e in zip(actual, expected):
468 self.assertAlmostEqual(a,e,places=14)
469
470 def test_strong_reference_implementation(self):
471 # Like test_referenceImplementation, but checks for exact bit-level
472 # equality. This should pass on any box where C double contains
473 # at least 53 bits of precision (the underlying algorithm suffers
474 # no rounding errors -- all results are exact).
475 from math import ldexp
476
Guido van Rossume2a383d2007-01-15 16:59:06 +0000477 expected = [0x0eab3258d2231f,
478 0x1b89db315277a5,
479 0x1db622a5518016,
480 0x0b7f9af0d575bf,
481 0x029e4c4db82240,
482 0x04961892f5d673,
483 0x02b291598e4589,
484 0x11388382c15694,
485 0x02dad977c9e1fe,
486 0x191d96d4d334c6]
487 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000488 actual = self.randomlist(2000)[-10:]
489 for a, e in zip(actual, expected):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000490 self.assertEqual(int(ldexp(a, 53)), e)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000491
492 def test_long_seed(self):
493 # This is most interesting to run in debug mode, just to make sure
494 # nothing blows up. Under the covers, a dynamically resized array
495 # is allocated, consuming space proportional to the number of bits
496 # in the seed. Unfortunately, that's a quadratic-time algorithm,
497 # so don't make this horribly big.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000498 seed = (1 << (10000 * 8)) - 1 # about 10K bytes
Raymond Hettinger40f62172002-12-29 23:03:38 +0000499 self.gen.seed(seed)
500
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000501 def test_53_bits_per_float(self):
502 # This should pass whenever a C double has 53 bit precision.
503 span = 2 ** 53
504 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000505 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000506 cum |= int(self.gen.random() * span)
507 self.assertEqual(cum, span-1)
508
509 def test_bigrand(self):
510 # The randrange routine should build-up the required number of bits
511 # in stages so that all bit positions are active.
512 span = 2 ** 500
513 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000514 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000515 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000516 self.assertTrue(0 <= r < span)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000517 cum |= r
518 self.assertEqual(cum, span-1)
519
520 def test_bigrand_ranges(self):
521 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600522 start = self.gen.randrange(2 ** (i-2))
523 stop = self.gen.randrange(2 ** i)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000524 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600525 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000526 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000527
528 def test_rangelimits(self):
529 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
Raymond Hettingera690a992003-11-16 16:17:49 +0000530 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000531 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000532
533 def test_genrandbits(self):
534 # Verify cross-platform repeatability
535 self.gen.seed(1234567)
536 self.assertEqual(self.gen.getrandbits(100),
Guido van Rossume2a383d2007-01-15 16:59:06 +0000537 97904845777343510404718956115)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000538 # Verify ranges
Guido van Rossum805365e2007-05-07 22:24:25 +0000539 for k in range(1, 1000):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000540 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000541
542 # Verify all bits active
543 getbits = self.gen.getrandbits
544 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
545 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000546 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000547 cum |= getbits(span)
548 self.assertEqual(cum, 2**span-1)
549
Raymond Hettinger58335872004-07-09 14:26:18 +0000550 # Verify argument checking
551 self.assertRaises(TypeError, self.gen.getrandbits)
552 self.assertRaises(TypeError, self.gen.getrandbits, 'a')
553 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
554 self.assertRaises(ValueError, self.gen.getrandbits, 0)
555 self.assertRaises(ValueError, self.gen.getrandbits, -1)
556
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000557 def test_randbelow_logic(self, _log=log, int=int):
558 # check bitcount transition points: 2**i and 2**(i+1)-1
559 # show that: k = int(1.001 + _log(n, 2))
560 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000561 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000562 n = 1 << i # check an exact power of two
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000563 numbits = i+1
564 k = int(1.00001 + _log(n, 2))
565 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000566 self.assertEqual(n, 2**(k-1))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000567
568 n += n - 1 # check 1 below the next power of two
569 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000570 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000571 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000572
573 n -= n >> 15 # check a little farther below the next power of two
574 k = int(1.00001 + _log(n, 2))
575 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000576 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000577
R David Murraye3e1c172013-04-02 12:47:23 -0400578 @unittest.mock.patch('random.Random.random')
Martin Pantere26da7c2016-06-02 10:07:09 +0000579 def test_randbelow_overridden_random(self, random_mock):
R David Murraye3e1c172013-04-02 12:47:23 -0400580 # Random._randbelow() can only use random() when the built-in one
581 # has been overridden but no new getrandbits() method was supplied.
582 random_mock.side_effect = random.SystemRandom().random
583 maxsize = 1<<random.BPF
584 with warnings.catch_warnings():
585 warnings.simplefilter("ignore", UserWarning)
586 # Population range too large (n >= maxsize)
587 self.gen._randbelow(maxsize+1, maxsize = maxsize)
588 self.gen._randbelow(5640, maxsize = maxsize)
589
590 # This might be going too far to test a single line, but because of our
591 # noble aim of achieving 100% test coverage we need to write a case in
592 # which the following line in Random._randbelow() gets executed:
593 #
594 # rem = maxsize % n
595 # limit = (maxsize - rem) / maxsize
596 # r = random()
597 # while r >= limit:
598 # r = random() # <== *This line* <==<
599 #
600 # Therefore, to guarantee that the while loop is executed at least
601 # once, we need to mock random() so that it returns a number greater
602 # than 'limit' the first time it gets called.
603
604 n = 42
605 epsilon = 0.01
606 limit = (maxsize - (maxsize % n)) / maxsize
607 random_mock.side_effect = [limit + epsilon, limit - epsilon]
608 self.gen._randbelow(n, maxsize = maxsize)
609
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000610 def test_randrange_bug_1590891(self):
611 start = 1000000000000
612 stop = -100000000000000000000
613 step = -200
614 x = self.gen.randrange(start, stop, step)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000615 self.assertTrue(stop < x <= start)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000616 self.assertEqual((x+stop)%step, 0)
617
Raymond Hettinger2d0c2562009-02-19 09:53:18 +0000618def gamma(z, sqrt2pi=(2.0*pi)**0.5):
619 # Reflection to right half of complex plane
620 if z < 0.5:
621 return pi / sin(pi*z) / gamma(1.0-z)
622 # Lanczos approximation with g=7
623 az = z + (7.0 - 0.5)
624 return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
625 0.9999999999995183,
626 676.5203681218835 / z,
627 -1259.139216722289 / (z+1.0),
628 771.3234287757674 / (z+2.0),
629 -176.6150291498386 / (z+3.0),
630 12.50734324009056 / (z+4.0),
631 -0.1385710331296526 / (z+5.0),
632 0.9934937113930748e-05 / (z+6.0),
633 0.1659470187408462e-06 / (z+7.0),
634 ])
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000635
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000636class TestDistributions(unittest.TestCase):
637 def test_zeroinputs(self):
638 # Verify that distributions can handle a series of zero inputs'
639 g = random.Random()
Guido van Rossum805365e2007-05-07 22:24:25 +0000640 x = [g.random() for i in range(50)] + [0.0]*5
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000641 g.random = x[:].pop; g.uniform(1,10)
642 g.random = x[:].pop; g.paretovariate(1.0)
643 g.random = x[:].pop; g.expovariate(1.0)
644 g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200645 g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000646 g.random = x[:].pop; g.normalvariate(0.0, 1.0)
647 g.random = x[:].pop; g.gauss(0.0, 1.0)
648 g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
649 g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
650 g.random = x[:].pop; g.gammavariate(0.01, 1.0)
651 g.random = x[:].pop; g.gammavariate(1.0, 1.0)
652 g.random = x[:].pop; g.gammavariate(200.0, 1.0)
653 g.random = x[:].pop; g.betavariate(3.0, 3.0)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000654 g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000655
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000656 def test_avg_std(self):
657 # Use integration to test distribution average and standard deviation.
658 # Only works for distributions which do not consume variates in pairs
659 g = random.Random()
660 N = 5000
Guido van Rossum805365e2007-05-07 22:24:25 +0000661 x = [i/float(N) for i in range(1,N)]
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000662 for variate, args, mu, sigmasqrd in [
663 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
Christian Heimesfe337bf2008-03-23 21:54:12 +0000664 (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 +0000665 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200666 (g.vonmisesvariate, (1.23, 0), pi, pi**2/3),
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000667 (g.paretovariate, (5.0,), 5.0/(5.0-1),
668 5.0/((5.0-1)**2*(5.0-2))),
669 (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0),
670 gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
671 g.random = x[:].pop
672 y = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000673 for i in range(len(x)):
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000674 try:
675 y.append(variate(*args))
676 except IndexError:
677 pass
678 s1 = s2 = 0
679 for e in y:
680 s1 += e
681 s2 += (e - mu) ** 2
682 N = len(y)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200683 self.assertAlmostEqual(s1/N, mu, places=2,
684 msg='%s%r' % (variate.__name__, args))
685 self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2,
686 msg='%s%r' % (variate.__name__, args))
687
688 def test_constant(self):
689 g = random.Random()
690 N = 100
691 for variate, args, expected in [
692 (g.uniform, (10.0, 10.0), 10.0),
693 (g.triangular, (10.0, 10.0), 10.0),
Raymond Hettinger978c6ab2014-05-25 17:25:27 -0700694 (g.triangular, (10.0, 10.0, 10.0), 10.0),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200695 (g.expovariate, (float('inf'),), 0.0),
696 (g.vonmisesvariate, (3.0, float('inf')), 3.0),
697 (g.gauss, (10.0, 0.0), 10.0),
698 (g.lognormvariate, (0.0, 0.0), 1.0),
699 (g.lognormvariate, (-float('inf'), 0.0), 0.0),
700 (g.normalvariate, (10.0, 0.0), 10.0),
701 (g.paretovariate, (float('inf'),), 1.0),
702 (g.weibullvariate, (10.0, float('inf')), 10.0),
703 (g.weibullvariate, (0.0, 10.0), 0.0),
704 ]:
705 for i in range(N):
706 self.assertEqual(variate(*args), expected)
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000707
Mark Dickinsonbe5f9192013-02-10 14:16:10 +0000708 def test_von_mises_range(self):
709 # Issue 17149: von mises variates were not consistently in the
710 # range [0, 2*PI].
711 g = random.Random()
712 N = 100
713 for mu in 0.0, 0.1, 3.1, 6.2:
714 for kappa in 0.0, 2.3, 500.0:
715 for _ in range(N):
716 sample = g.vonmisesvariate(mu, kappa)
717 self.assertTrue(
718 0 <= sample <= random.TWOPI,
719 msg=("vonmisesvariate({}, {}) produced a result {} out"
720 " of range [0, 2*pi]").format(mu, kappa, sample))
721
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200722 def test_von_mises_large_kappa(self):
723 # Issue #17141: vonmisesvariate() was hang for large kappas
724 random.vonmisesvariate(0, 1e15)
725 random.vonmisesvariate(0, 1e100)
726
R David Murraye3e1c172013-04-02 12:47:23 -0400727 def test_gammavariate_errors(self):
728 # Both alpha and beta must be > 0.0
729 self.assertRaises(ValueError, random.gammavariate, -1, 3)
730 self.assertRaises(ValueError, random.gammavariate, 0, 2)
731 self.assertRaises(ValueError, random.gammavariate, 2, 0)
732 self.assertRaises(ValueError, random.gammavariate, 1, -3)
733
734 @unittest.mock.patch('random.Random.random')
735 def test_gammavariate_full_code_coverage(self, random_mock):
736 # There are three different possibilities in the current implementation
737 # of random.gammavariate(), depending on the value of 'alpha'. What we
738 # are going to do here is to fix the values returned by random() to
739 # generate test cases that provide 100% line coverage of the method.
740
741 # #1: alpha > 1.0: we want the first random number to be outside the
742 # [1e-7, .9999999] range, so that the continue statement executes
743 # once. The values of u1 and u2 will be 0.5 and 0.3, respectively.
744 random_mock.side_effect = [1e-8, 0.5, 0.3]
745 returned_value = random.gammavariate(1.1, 2.3)
746 self.assertAlmostEqual(returned_value, 2.53)
747
748 # #2: alpha == 1: first random number less than 1e-7 to that the body
749 # of the while loop executes once. Then random.random() returns 0.45,
750 # which causes while to stop looping and the algorithm to terminate.
751 random_mock.side_effect = [1e-8, 0.45]
752 returned_value = random.gammavariate(1.0, 3.14)
753 self.assertAlmostEqual(returned_value, 2.507314166123803)
754
755 # #3: 0 < alpha < 1. This is the most complex region of code to cover,
756 # as there are multiple if-else statements. Let's take a look at the
757 # source code, and determine the values that we need accordingly:
758 #
759 # while 1:
760 # u = random()
761 # b = (_e + alpha)/_e
762 # p = b*u
763 # if p <= 1.0: # <=== (A)
764 # x = p ** (1.0/alpha)
765 # else: # <=== (B)
766 # x = -_log((b-p)/alpha)
767 # u1 = random()
768 # if p > 1.0: # <=== (C)
769 # if u1 <= x ** (alpha - 1.0): # <=== (D)
770 # break
771 # elif u1 <= _exp(-x): # <=== (E)
772 # break
773 # return x * beta
774 #
775 # First, we want (A) to be True. For that we need that:
776 # b*random() <= 1.0
777 # r1 = random() <= 1.0 / b
778 #
779 # We now get to the second if-else branch, and here, since p <= 1.0,
780 # (C) is False and we take the elif branch, (E). For it to be True,
781 # so that the break is executed, we need that:
782 # r2 = random() <= _exp(-x)
783 # r2 <= _exp(-(p ** (1.0/alpha)))
784 # r2 <= _exp(-((b*r1) ** (1.0/alpha)))
785
786 _e = random._e
787 _exp = random._exp
788 _log = random._log
789 alpha = 0.35
790 beta = 1.45
791 b = (_e + alpha)/_e
792 epsilon = 0.01
793
794 r1 = 0.8859296441566 # 1.0 / b
795 r2 = 0.3678794411714 # _exp(-((b*r1) ** (1.0/alpha)))
796
797 # These four "random" values result in the following trace:
798 # (A) True, (E) False --> [next iteration of while]
799 # (A) True, (E) True --> [while loop breaks]
800 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
801 returned_value = random.gammavariate(alpha, beta)
802 self.assertAlmostEqual(returned_value, 1.4499999999997544)
803
804 # Let's now make (A) be False. If this is the case, when we get to the
805 # second if-else 'p' is greater than 1, so (C) evaluates to True. We
806 # now encounter a second if statement, (D), which in order to execute
807 # must satisfy the following condition:
808 # r2 <= x ** (alpha - 1.0)
809 # r2 <= (-_log((b-p)/alpha)) ** (alpha - 1.0)
810 # r2 <= (-_log((b-(b*r1))/alpha)) ** (alpha - 1.0)
811 r1 = 0.8959296441566 # (1.0 / b) + epsilon -- so that (A) is False
812 r2 = 0.9445400408898141
813
814 # And these four values result in the following trace:
815 # (B) and (C) True, (D) False --> [next iteration of while]
816 # (B) and (C) True, (D) True [while loop breaks]
817 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
818 returned_value = random.gammavariate(alpha, beta)
819 self.assertAlmostEqual(returned_value, 1.5830349561760781)
820
821 @unittest.mock.patch('random.Random.gammavariate')
822 def test_betavariate_return_zero(self, gammavariate_mock):
823 # betavariate() returns zero when the Gamma distribution
824 # that it uses internally returns this same value.
825 gammavariate_mock.return_value = 0.0
826 self.assertEqual(0.0, random.betavariate(2.71828, 3.14159))
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200827
Raymond Hettinger40f62172002-12-29 23:03:38 +0000828class TestModule(unittest.TestCase):
829 def testMagicConstants(self):
830 self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141)
831 self.assertAlmostEqual(random.TWOPI, 6.28318530718)
832 self.assertAlmostEqual(random.LOG4, 1.38629436111989)
833 self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627)
834
835 def test__all__(self):
836 # tests validity but not completeness of the __all__ list
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000837 self.assertTrue(set(random.__all__) <= set(dir(random)))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000838
Thomas Woutersb2137042007-02-01 18:02:27 +0000839 def test_random_subclass_with_kwargs(self):
840 # SF bug #1486663 -- this used to erroneously raise a TypeError
841 class Subclass(random.Random):
842 def __init__(self, newarg=None):
843 random.Random.__init__(self)
844 Subclass(newarg=1)
845
846
Raymond Hettinger40f62172002-12-29 23:03:38 +0000847if __name__ == "__main__":
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300848 unittest.main()