1 | n/a | import unittest |
---|
2 | n/a | import unittest.mock |
---|
3 | n/a | import random |
---|
4 | n/a | import time |
---|
5 | n/a | import pickle |
---|
6 | n/a | import warnings |
---|
7 | n/a | from functools import partial |
---|
8 | n/a | from math import log, exp, pi, fsum, sin, factorial |
---|
9 | n/a | from test import support |
---|
10 | n/a | from fractions import Fraction |
---|
11 | n/a | |
---|
12 | n/a | class TestBasicOps: |
---|
13 | n/a | # Superclass with tests common to all generators. |
---|
14 | n/a | # Subclasses must arrange for self.gen to retrieve the Random instance |
---|
15 | n/a | # to be tested. |
---|
16 | n/a | |
---|
17 | n/a | def randomlist(self, n): |
---|
18 | n/a | """Helper function to make a list of random numbers""" |
---|
19 | n/a | return [self.gen.random() for i in range(n)] |
---|
20 | n/a | |
---|
21 | n/a | def test_autoseed(self): |
---|
22 | n/a | self.gen.seed() |
---|
23 | n/a | state1 = self.gen.getstate() |
---|
24 | n/a | time.sleep(0.1) |
---|
25 | n/a | self.gen.seed() # diffent seeds at different times |
---|
26 | n/a | state2 = self.gen.getstate() |
---|
27 | n/a | self.assertNotEqual(state1, state2) |
---|
28 | n/a | |
---|
29 | n/a | def test_saverestore(self): |
---|
30 | n/a | N = 1000 |
---|
31 | n/a | self.gen.seed() |
---|
32 | n/a | state = self.gen.getstate() |
---|
33 | n/a | randseq = self.randomlist(N) |
---|
34 | n/a | self.gen.setstate(state) # should regenerate the same sequence |
---|
35 | n/a | self.assertEqual(randseq, self.randomlist(N)) |
---|
36 | n/a | |
---|
37 | n/a | def test_seedargs(self): |
---|
38 | n/a | # Seed value with a negative hash. |
---|
39 | n/a | class MySeed(object): |
---|
40 | n/a | def __hash__(self): |
---|
41 | n/a | return -1729 |
---|
42 | n/a | for arg in [None, 0, 0, 1, 1, -1, -1, 10**20, -(10**20), |
---|
43 | n/a | 3.14, 1+2j, 'a', tuple('abc'), MySeed()]: |
---|
44 | n/a | self.gen.seed(arg) |
---|
45 | n/a | for arg in [list(range(3)), dict(one=1)]: |
---|
46 | n/a | self.assertRaises(TypeError, self.gen.seed, arg) |
---|
47 | n/a | self.assertRaises(TypeError, self.gen.seed, 1, 2, 3, 4) |
---|
48 | n/a | self.assertRaises(TypeError, type(self.gen), []) |
---|
49 | n/a | |
---|
50 | n/a | @unittest.mock.patch('random._urandom') # os.urandom |
---|
51 | n/a | def test_seed_when_randomness_source_not_found(self, urandom_mock): |
---|
52 | n/a | # Random.seed() uses time.time() when an operating system specific |
---|
53 | n/a | # randomness source is not found. To test this on machines were it |
---|
54 | n/a | # exists, run the above test, test_seedargs(), again after mocking |
---|
55 | n/a | # os.urandom() so that it raises the exception expected when the |
---|
56 | n/a | # randomness source is not available. |
---|
57 | n/a | urandom_mock.side_effect = NotImplementedError |
---|
58 | n/a | self.test_seedargs() |
---|
59 | n/a | |
---|
60 | n/a | def test_shuffle(self): |
---|
61 | n/a | shuffle = self.gen.shuffle |
---|
62 | n/a | lst = [] |
---|
63 | n/a | shuffle(lst) |
---|
64 | n/a | self.assertEqual(lst, []) |
---|
65 | n/a | lst = [37] |
---|
66 | n/a | shuffle(lst) |
---|
67 | n/a | self.assertEqual(lst, [37]) |
---|
68 | n/a | seqs = [list(range(n)) for n in range(10)] |
---|
69 | n/a | shuffled_seqs = [list(range(n)) for n in range(10)] |
---|
70 | n/a | for shuffled_seq in shuffled_seqs: |
---|
71 | n/a | shuffle(shuffled_seq) |
---|
72 | n/a | for (seq, shuffled_seq) in zip(seqs, shuffled_seqs): |
---|
73 | n/a | self.assertEqual(len(seq), len(shuffled_seq)) |
---|
74 | n/a | self.assertEqual(set(seq), set(shuffled_seq)) |
---|
75 | n/a | # The above tests all would pass if the shuffle was a |
---|
76 | n/a | # no-op. The following non-deterministic test covers that. It |
---|
77 | n/a | # asserts that the shuffled sequence of 1000 distinct elements |
---|
78 | n/a | # must be different from the original one. Although there is |
---|
79 | n/a | # mathematically a non-zero probability that this could |
---|
80 | n/a | # actually happen in a genuinely random shuffle, it is |
---|
81 | n/a | # completely negligible, given that the number of possible |
---|
82 | n/a | # permutations of 1000 objects is 1000! (factorial of 1000), |
---|
83 | n/a | # which is considerably larger than the number of atoms in the |
---|
84 | n/a | # universe... |
---|
85 | n/a | lst = list(range(1000)) |
---|
86 | n/a | shuffled_lst = list(range(1000)) |
---|
87 | n/a | shuffle(shuffled_lst) |
---|
88 | n/a | self.assertTrue(lst != shuffled_lst) |
---|
89 | n/a | shuffle(lst) |
---|
90 | n/a | self.assertTrue(lst != shuffled_lst) |
---|
91 | n/a | |
---|
92 | n/a | def test_choice(self): |
---|
93 | n/a | choice = self.gen.choice |
---|
94 | n/a | with self.assertRaises(IndexError): |
---|
95 | n/a | choice([]) |
---|
96 | n/a | self.assertEqual(choice([50]), 50) |
---|
97 | n/a | self.assertIn(choice([25, 75]), [25, 75]) |
---|
98 | n/a | |
---|
99 | n/a | def test_sample(self): |
---|
100 | n/a | # For the entire allowable range of 0 <= k <= N, validate that |
---|
101 | n/a | # the sample is of the correct length and contains only unique items |
---|
102 | n/a | N = 100 |
---|
103 | n/a | population = range(N) |
---|
104 | n/a | for k in range(N+1): |
---|
105 | n/a | s = self.gen.sample(population, k) |
---|
106 | n/a | self.assertEqual(len(s), k) |
---|
107 | n/a | uniq = set(s) |
---|
108 | n/a | self.assertEqual(len(uniq), k) |
---|
109 | n/a | self.assertTrue(uniq <= set(population)) |
---|
110 | n/a | self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0 |
---|
111 | n/a | # Exception raised if size of sample exceeds that of population |
---|
112 | n/a | self.assertRaises(ValueError, self.gen.sample, population, N+1) |
---|
113 | n/a | self.assertRaises(ValueError, self.gen.sample, [], -1) |
---|
114 | n/a | |
---|
115 | n/a | def test_sample_distribution(self): |
---|
116 | n/a | # For the entire allowable range of 0 <= k <= N, validate that |
---|
117 | n/a | # sample generates all possible permutations |
---|
118 | n/a | n = 5 |
---|
119 | n/a | pop = range(n) |
---|
120 | n/a | trials = 10000 # large num prevents false negatives without slowing normal case |
---|
121 | n/a | for k in range(n): |
---|
122 | n/a | expected = factorial(n) // factorial(n-k) |
---|
123 | n/a | perms = {} |
---|
124 | n/a | for i in range(trials): |
---|
125 | n/a | perms[tuple(self.gen.sample(pop, k))] = None |
---|
126 | n/a | if len(perms) == expected: |
---|
127 | n/a | break |
---|
128 | n/a | else: |
---|
129 | n/a | self.fail() |
---|
130 | n/a | |
---|
131 | n/a | def test_sample_inputs(self): |
---|
132 | n/a | # SF bug #801342 -- population can be any iterable defining __len__() |
---|
133 | n/a | self.gen.sample(set(range(20)), 2) |
---|
134 | n/a | self.gen.sample(range(20), 2) |
---|
135 | n/a | self.gen.sample(range(20), 2) |
---|
136 | n/a | self.gen.sample(str('abcdefghijklmnopqrst'), 2) |
---|
137 | n/a | self.gen.sample(tuple('abcdefghijklmnopqrst'), 2) |
---|
138 | n/a | |
---|
139 | n/a | def test_sample_on_dicts(self): |
---|
140 | n/a | self.assertRaises(TypeError, self.gen.sample, dict.fromkeys('abcdef'), 2) |
---|
141 | n/a | |
---|
142 | n/a | def test_choices(self): |
---|
143 | n/a | choices = self.gen.choices |
---|
144 | n/a | data = ['red', 'green', 'blue', 'yellow'] |
---|
145 | n/a | str_data = 'abcd' |
---|
146 | n/a | range_data = range(4) |
---|
147 | n/a | set_data = set(range(4)) |
---|
148 | n/a | |
---|
149 | n/a | # basic functionality |
---|
150 | n/a | for sample in [ |
---|
151 | n/a | choices(data, k=5), |
---|
152 | n/a | choices(data, range(4), k=5), |
---|
153 | n/a | choices(k=5, population=data, weights=range(4)), |
---|
154 | n/a | choices(k=5, population=data, cum_weights=range(4)), |
---|
155 | n/a | ]: |
---|
156 | n/a | self.assertEqual(len(sample), 5) |
---|
157 | n/a | self.assertEqual(type(sample), list) |
---|
158 | n/a | self.assertTrue(set(sample) <= set(data)) |
---|
159 | n/a | |
---|
160 | n/a | # test argument handling |
---|
161 | n/a | with self.assertRaises(TypeError): # missing arguments |
---|
162 | n/a | choices(2) |
---|
163 | n/a | |
---|
164 | n/a | self.assertEqual(choices(data, k=0), []) # k == 0 |
---|
165 | n/a | self.assertEqual(choices(data, k=-1), []) # negative k behaves like ``[0] * -1`` |
---|
166 | n/a | with self.assertRaises(TypeError): |
---|
167 | n/a | choices(data, k=2.5) # k is a float |
---|
168 | n/a | |
---|
169 | n/a | self.assertTrue(set(choices(str_data, k=5)) <= set(str_data)) # population is a string sequence |
---|
170 | n/a | self.assertTrue(set(choices(range_data, k=5)) <= set(range_data)) # population is a range |
---|
171 | n/a | with self.assertRaises(TypeError): |
---|
172 | n/a | choices(set_data, k=2) # population is not a sequence |
---|
173 | n/a | |
---|
174 | n/a | self.assertTrue(set(choices(data, None, k=5)) <= set(data)) # weights is None |
---|
175 | n/a | self.assertTrue(set(choices(data, weights=None, k=5)) <= set(data)) |
---|
176 | n/a | with self.assertRaises(ValueError): |
---|
177 | n/a | choices(data, [1,2], k=5) # len(weights) != len(population) |
---|
178 | n/a | with self.assertRaises(TypeError): |
---|
179 | n/a | choices(data, 10, k=5) # non-iterable weights |
---|
180 | n/a | with self.assertRaises(TypeError): |
---|
181 | n/a | choices(data, [None]*4, k=5) # non-numeric weights |
---|
182 | n/a | for weights in [ |
---|
183 | n/a | [15, 10, 25, 30], # integer weights |
---|
184 | n/a | [15.1, 10.2, 25.2, 30.3], # float weights |
---|
185 | n/a | [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional weights |
---|
186 | n/a | [True, False, True, False] # booleans (include / exclude) |
---|
187 | n/a | ]: |
---|
188 | n/a | self.assertTrue(set(choices(data, weights, k=5)) <= set(data)) |
---|
189 | n/a | |
---|
190 | n/a | with self.assertRaises(ValueError): |
---|
191 | n/a | choices(data, cum_weights=[1,2], k=5) # len(weights) != len(population) |
---|
192 | n/a | with self.assertRaises(TypeError): |
---|
193 | n/a | choices(data, cum_weights=10, k=5) # non-iterable cum_weights |
---|
194 | n/a | with self.assertRaises(TypeError): |
---|
195 | n/a | choices(data, cum_weights=[None]*4, k=5) # non-numeric cum_weights |
---|
196 | n/a | with self.assertRaises(TypeError): |
---|
197 | n/a | choices(data, range(4), cum_weights=range(4), k=5) # both weights and cum_weights |
---|
198 | n/a | for weights in [ |
---|
199 | n/a | [15, 10, 25, 30], # integer cum_weights |
---|
200 | n/a | [15.1, 10.2, 25.2, 30.3], # float cum_weights |
---|
201 | n/a | [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional cum_weights |
---|
202 | n/a | ]: |
---|
203 | n/a | self.assertTrue(set(choices(data, cum_weights=weights, k=5)) <= set(data)) |
---|
204 | n/a | |
---|
205 | n/a | # Test weight focused on a single element of the population |
---|
206 | n/a | self.assertEqual(choices('abcd', [1, 0, 0, 0]), ['a']) |
---|
207 | n/a | self.assertEqual(choices('abcd', [0, 1, 0, 0]), ['b']) |
---|
208 | n/a | self.assertEqual(choices('abcd', [0, 0, 1, 0]), ['c']) |
---|
209 | n/a | self.assertEqual(choices('abcd', [0, 0, 0, 1]), ['d']) |
---|
210 | n/a | |
---|
211 | n/a | # Test consistency with random.choice() for empty population |
---|
212 | n/a | with self.assertRaises(IndexError): |
---|
213 | n/a | choices([], k=1) |
---|
214 | n/a | with self.assertRaises(IndexError): |
---|
215 | n/a | choices([], weights=[], k=1) |
---|
216 | n/a | with self.assertRaises(IndexError): |
---|
217 | n/a | choices([], cum_weights=[], k=5) |
---|
218 | n/a | |
---|
219 | n/a | def test_gauss(self): |
---|
220 | n/a | # Ensure that the seed() method initializes all the hidden state. In |
---|
221 | n/a | # particular, through 2.2.1 it failed to reset a piece of state used |
---|
222 | n/a | # by (and only by) the .gauss() method. |
---|
223 | n/a | |
---|
224 | n/a | for seed in 1, 12, 123, 1234, 12345, 123456, 654321: |
---|
225 | n/a | self.gen.seed(seed) |
---|
226 | n/a | x1 = self.gen.random() |
---|
227 | n/a | y1 = self.gen.gauss(0, 1) |
---|
228 | n/a | |
---|
229 | n/a | self.gen.seed(seed) |
---|
230 | n/a | x2 = self.gen.random() |
---|
231 | n/a | y2 = self.gen.gauss(0, 1) |
---|
232 | n/a | |
---|
233 | n/a | self.assertEqual(x1, x2) |
---|
234 | n/a | self.assertEqual(y1, y2) |
---|
235 | n/a | |
---|
236 | n/a | def test_pickling(self): |
---|
237 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
238 | n/a | state = pickle.dumps(self.gen, proto) |
---|
239 | n/a | origseq = [self.gen.random() for i in range(10)] |
---|
240 | n/a | newgen = pickle.loads(state) |
---|
241 | n/a | restoredseq = [newgen.random() for i in range(10)] |
---|
242 | n/a | self.assertEqual(origseq, restoredseq) |
---|
243 | n/a | |
---|
244 | n/a | def test_bug_1727780(self): |
---|
245 | n/a | # verify that version-2-pickles can be loaded |
---|
246 | n/a | # fine, whether they are created on 32-bit or 64-bit |
---|
247 | n/a | # platforms, and that version-3-pickles load fine. |
---|
248 | n/a | files = [("randv2_32.pck", 780), |
---|
249 | n/a | ("randv2_64.pck", 866), |
---|
250 | n/a | ("randv3.pck", 343)] |
---|
251 | n/a | for file, value in files: |
---|
252 | n/a | f = open(support.findfile(file),"rb") |
---|
253 | n/a | r = pickle.load(f) |
---|
254 | n/a | f.close() |
---|
255 | n/a | self.assertEqual(int(r.random()*1000), value) |
---|
256 | n/a | |
---|
257 | n/a | def test_bug_9025(self): |
---|
258 | n/a | # Had problem with an uneven distribution in int(n*random()) |
---|
259 | n/a | # Verify the fix by checking that distributions fall within expectations. |
---|
260 | n/a | n = 100000 |
---|
261 | n/a | randrange = self.gen.randrange |
---|
262 | n/a | k = sum(randrange(6755399441055744) % 3 == 2 for i in range(n)) |
---|
263 | n/a | self.assertTrue(0.30 < k/n < .37, (k/n)) |
---|
264 | n/a | |
---|
265 | n/a | try: |
---|
266 | n/a | random.SystemRandom().random() |
---|
267 | n/a | except NotImplementedError: |
---|
268 | n/a | SystemRandom_available = False |
---|
269 | n/a | else: |
---|
270 | n/a | SystemRandom_available = True |
---|
271 | n/a | |
---|
272 | n/a | @unittest.skipUnless(SystemRandom_available, "random.SystemRandom not available") |
---|
273 | n/a | class SystemRandom_TestBasicOps(TestBasicOps, unittest.TestCase): |
---|
274 | n/a | gen = random.SystemRandom() |
---|
275 | n/a | |
---|
276 | n/a | def test_autoseed(self): |
---|
277 | n/a | # Doesn't need to do anything except not fail |
---|
278 | n/a | self.gen.seed() |
---|
279 | n/a | |
---|
280 | n/a | def test_saverestore(self): |
---|
281 | n/a | self.assertRaises(NotImplementedError, self.gen.getstate) |
---|
282 | n/a | self.assertRaises(NotImplementedError, self.gen.setstate, None) |
---|
283 | n/a | |
---|
284 | n/a | def test_seedargs(self): |
---|
285 | n/a | # Doesn't need to do anything except not fail |
---|
286 | n/a | self.gen.seed(100) |
---|
287 | n/a | |
---|
288 | n/a | def test_gauss(self): |
---|
289 | n/a | self.gen.gauss_next = None |
---|
290 | n/a | self.gen.seed(100) |
---|
291 | n/a | self.assertEqual(self.gen.gauss_next, None) |
---|
292 | n/a | |
---|
293 | n/a | def test_pickling(self): |
---|
294 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
295 | n/a | self.assertRaises(NotImplementedError, pickle.dumps, self.gen, proto) |
---|
296 | n/a | |
---|
297 | n/a | def test_53_bits_per_float(self): |
---|
298 | n/a | # This should pass whenever a C double has 53 bit precision. |
---|
299 | n/a | span = 2 ** 53 |
---|
300 | n/a | cum = 0 |
---|
301 | n/a | for i in range(100): |
---|
302 | n/a | cum |= int(self.gen.random() * span) |
---|
303 | n/a | self.assertEqual(cum, span-1) |
---|
304 | n/a | |
---|
305 | n/a | def test_bigrand(self): |
---|
306 | n/a | # The randrange routine should build-up the required number of bits |
---|
307 | n/a | # in stages so that all bit positions are active. |
---|
308 | n/a | span = 2 ** 500 |
---|
309 | n/a | cum = 0 |
---|
310 | n/a | for i in range(100): |
---|
311 | n/a | r = self.gen.randrange(span) |
---|
312 | n/a | self.assertTrue(0 <= r < span) |
---|
313 | n/a | cum |= r |
---|
314 | n/a | self.assertEqual(cum, span-1) |
---|
315 | n/a | |
---|
316 | n/a | def test_bigrand_ranges(self): |
---|
317 | n/a | for i in [40,80, 160, 200, 211, 250, 375, 512, 550]: |
---|
318 | n/a | start = self.gen.randrange(2 ** (i-2)) |
---|
319 | n/a | stop = self.gen.randrange(2 ** i) |
---|
320 | n/a | if stop <= start: |
---|
321 | n/a | continue |
---|
322 | n/a | self.assertTrue(start <= self.gen.randrange(start, stop) < stop) |
---|
323 | n/a | |
---|
324 | n/a | def test_rangelimits(self): |
---|
325 | n/a | for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]: |
---|
326 | n/a | self.assertEqual(set(range(start,stop)), |
---|
327 | n/a | set([self.gen.randrange(start,stop) for i in range(100)])) |
---|
328 | n/a | |
---|
329 | n/a | def test_randrange_nonunit_step(self): |
---|
330 | n/a | rint = self.gen.randrange(0, 10, 2) |
---|
331 | n/a | self.assertIn(rint, (0, 2, 4, 6, 8)) |
---|
332 | n/a | rint = self.gen.randrange(0, 2, 2) |
---|
333 | n/a | self.assertEqual(rint, 0) |
---|
334 | n/a | |
---|
335 | n/a | def test_randrange_errors(self): |
---|
336 | n/a | raises = partial(self.assertRaises, ValueError, self.gen.randrange) |
---|
337 | n/a | # Empty range |
---|
338 | n/a | raises(3, 3) |
---|
339 | n/a | raises(-721) |
---|
340 | n/a | raises(0, 100, -12) |
---|
341 | n/a | # Non-integer start/stop |
---|
342 | n/a | raises(3.14159) |
---|
343 | n/a | raises(0, 2.71828) |
---|
344 | n/a | # Zero and non-integer step |
---|
345 | n/a | raises(0, 42, 0) |
---|
346 | n/a | raises(0, 42, 3.14159) |
---|
347 | n/a | |
---|
348 | n/a | def test_genrandbits(self): |
---|
349 | n/a | # Verify ranges |
---|
350 | n/a | for k in range(1, 1000): |
---|
351 | n/a | self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k) |
---|
352 | n/a | |
---|
353 | n/a | # Verify all bits active |
---|
354 | n/a | getbits = self.gen.getrandbits |
---|
355 | n/a | for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]: |
---|
356 | n/a | cum = 0 |
---|
357 | n/a | for i in range(100): |
---|
358 | n/a | cum |= getbits(span) |
---|
359 | n/a | self.assertEqual(cum, 2**span-1) |
---|
360 | n/a | |
---|
361 | n/a | # Verify argument checking |
---|
362 | n/a | self.assertRaises(TypeError, self.gen.getrandbits) |
---|
363 | n/a | self.assertRaises(TypeError, self.gen.getrandbits, 1, 2) |
---|
364 | n/a | self.assertRaises(ValueError, self.gen.getrandbits, 0) |
---|
365 | n/a | self.assertRaises(ValueError, self.gen.getrandbits, -1) |
---|
366 | n/a | self.assertRaises(TypeError, self.gen.getrandbits, 10.1) |
---|
367 | n/a | |
---|
368 | n/a | def test_randbelow_logic(self, _log=log, int=int): |
---|
369 | n/a | # check bitcount transition points: 2**i and 2**(i+1)-1 |
---|
370 | n/a | # show that: k = int(1.001 + _log(n, 2)) |
---|
371 | n/a | # is equal to or one greater than the number of bits in n |
---|
372 | n/a | for i in range(1, 1000): |
---|
373 | n/a | n = 1 << i # check an exact power of two |
---|
374 | n/a | numbits = i+1 |
---|
375 | n/a | k = int(1.00001 + _log(n, 2)) |
---|
376 | n/a | self.assertEqual(k, numbits) |
---|
377 | n/a | self.assertEqual(n, 2**(k-1)) |
---|
378 | n/a | |
---|
379 | n/a | n += n - 1 # check 1 below the next power of two |
---|
380 | n/a | k = int(1.00001 + _log(n, 2)) |
---|
381 | n/a | self.assertIn(k, [numbits, numbits+1]) |
---|
382 | n/a | self.assertTrue(2**k > n > 2**(k-2)) |
---|
383 | n/a | |
---|
384 | n/a | n -= n >> 15 # check a little farther below the next power of two |
---|
385 | n/a | k = int(1.00001 + _log(n, 2)) |
---|
386 | n/a | self.assertEqual(k, numbits) # note the stronger assertion |
---|
387 | n/a | self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion |
---|
388 | n/a | |
---|
389 | n/a | |
---|
390 | n/a | class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase): |
---|
391 | n/a | gen = random.Random() |
---|
392 | n/a | |
---|
393 | n/a | def test_guaranteed_stable(self): |
---|
394 | n/a | # These sequences are guaranteed to stay the same across versions of python |
---|
395 | n/a | self.gen.seed(3456147, version=1) |
---|
396 | n/a | self.assertEqual([self.gen.random().hex() for i in range(4)], |
---|
397 | n/a | ['0x1.ac362300d90d2p-1', '0x1.9d16f74365005p-1', |
---|
398 | n/a | '0x1.1ebb4352e4c4dp-1', '0x1.1a7422abf9c11p-1']) |
---|
399 | n/a | self.gen.seed("the quick brown fox", version=2) |
---|
400 | n/a | self.assertEqual([self.gen.random().hex() for i in range(4)], |
---|
401 | n/a | ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4', |
---|
402 | n/a | '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1']) |
---|
403 | n/a | |
---|
404 | n/a | def test_bug_27706(self): |
---|
405 | n/a | # Verify that version 1 seeds are unaffected by hash randomization |
---|
406 | n/a | |
---|
407 | n/a | self.gen.seed('nofar', version=1) # hash('nofar') == 5990528763808513177 |
---|
408 | n/a | self.assertEqual([self.gen.random().hex() for i in range(4)], |
---|
409 | n/a | ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5', |
---|
410 | n/a | '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6']) |
---|
411 | n/a | |
---|
412 | n/a | self.gen.seed('rachel', version=1) # hash('rachel') == -9091735575445484789 |
---|
413 | n/a | self.assertEqual([self.gen.random().hex() for i in range(4)], |
---|
414 | n/a | ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3', |
---|
415 | n/a | '0x1.3052b9c072678p-2', '0x1.578f332106574p-3']) |
---|
416 | n/a | |
---|
417 | n/a | self.gen.seed('', version=1) # hash('') == 0 |
---|
418 | n/a | self.assertEqual([self.gen.random().hex() for i in range(4)], |
---|
419 | n/a | ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1', |
---|
420 | n/a | '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2']) |
---|
421 | n/a | |
---|
422 | n/a | def test_setstate_first_arg(self): |
---|
423 | n/a | self.assertRaises(ValueError, self.gen.setstate, (1, None, None)) |
---|
424 | n/a | |
---|
425 | n/a | def test_setstate_middle_arg(self): |
---|
426 | n/a | # Wrong type, s/b tuple |
---|
427 | n/a | self.assertRaises(TypeError, self.gen.setstate, (2, None, None)) |
---|
428 | n/a | # Wrong length, s/b 625 |
---|
429 | n/a | self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None)) |
---|
430 | n/a | # Wrong type, s/b tuple of 625 ints |
---|
431 | n/a | self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None)) |
---|
432 | n/a | # Last element s/b an int also |
---|
433 | n/a | self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None)) |
---|
434 | n/a | # Last element s/b between 0 and 624 |
---|
435 | n/a | with self.assertRaises((ValueError, OverflowError)): |
---|
436 | n/a | self.gen.setstate((2, (1,)*624+(625,), None)) |
---|
437 | n/a | with self.assertRaises((ValueError, OverflowError)): |
---|
438 | n/a | self.gen.setstate((2, (1,)*624+(-1,), None)) |
---|
439 | n/a | |
---|
440 | n/a | # Little trick to make "tuple(x % (2**32) for x in internalstate)" |
---|
441 | n/a | # raise ValueError. I cannot think of a simple way to achieve this, so |
---|
442 | n/a | # I am opting for using a generator as the middle argument of setstate |
---|
443 | n/a | # which attempts to cast a NaN to integer. |
---|
444 | n/a | state_values = self.gen.getstate()[1] |
---|
445 | n/a | state_values = list(state_values) |
---|
446 | n/a | state_values[-1] = float('nan') |
---|
447 | n/a | state = (int(x) for x in state_values) |
---|
448 | n/a | self.assertRaises(TypeError, self.gen.setstate, (2, state, None)) |
---|
449 | n/a | |
---|
450 | n/a | def test_referenceImplementation(self): |
---|
451 | n/a | # Compare the python implementation with results from the original |
---|
452 | n/a | # code. Create 2000 53-bit precision random floats. Compare only |
---|
453 | n/a | # the last ten entries to show that the independent implementations |
---|
454 | n/a | # are tracking. Here is the main() function needed to create the |
---|
455 | n/a | # list of expected random numbers: |
---|
456 | n/a | # void main(void){ |
---|
457 | n/a | # int i; |
---|
458 | n/a | # unsigned long init[4]={61731, 24903, 614, 42143}, length=4; |
---|
459 | n/a | # init_by_array(init, length); |
---|
460 | n/a | # for (i=0; i<2000; i++) { |
---|
461 | n/a | # printf("%.15f ", genrand_res53()); |
---|
462 | n/a | # if (i%5==4) printf("\n"); |
---|
463 | n/a | # } |
---|
464 | n/a | # } |
---|
465 | n/a | expected = [0.45839803073713259, |
---|
466 | n/a | 0.86057815201978782, |
---|
467 | n/a | 0.92848331726782152, |
---|
468 | n/a | 0.35932681119782461, |
---|
469 | n/a | 0.081823493762449573, |
---|
470 | n/a | 0.14332226470169329, |
---|
471 | n/a | 0.084297823823520024, |
---|
472 | n/a | 0.53814864671831453, |
---|
473 | n/a | 0.089215024911993401, |
---|
474 | n/a | 0.78486196105372907] |
---|
475 | n/a | |
---|
476 | n/a | self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96)) |
---|
477 | n/a | actual = self.randomlist(2000)[-10:] |
---|
478 | n/a | for a, e in zip(actual, expected): |
---|
479 | n/a | self.assertAlmostEqual(a,e,places=14) |
---|
480 | n/a | |
---|
481 | n/a | def test_strong_reference_implementation(self): |
---|
482 | n/a | # Like test_referenceImplementation, but checks for exact bit-level |
---|
483 | n/a | # equality. This should pass on any box where C double contains |
---|
484 | n/a | # at least 53 bits of precision (the underlying algorithm suffers |
---|
485 | n/a | # no rounding errors -- all results are exact). |
---|
486 | n/a | from math import ldexp |
---|
487 | n/a | |
---|
488 | n/a | expected = [0x0eab3258d2231f, |
---|
489 | n/a | 0x1b89db315277a5, |
---|
490 | n/a | 0x1db622a5518016, |
---|
491 | n/a | 0x0b7f9af0d575bf, |
---|
492 | n/a | 0x029e4c4db82240, |
---|
493 | n/a | 0x04961892f5d673, |
---|
494 | n/a | 0x02b291598e4589, |
---|
495 | n/a | 0x11388382c15694, |
---|
496 | n/a | 0x02dad977c9e1fe, |
---|
497 | n/a | 0x191d96d4d334c6] |
---|
498 | n/a | self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96)) |
---|
499 | n/a | actual = self.randomlist(2000)[-10:] |
---|
500 | n/a | for a, e in zip(actual, expected): |
---|
501 | n/a | self.assertEqual(int(ldexp(a, 53)), e) |
---|
502 | n/a | |
---|
503 | n/a | def test_long_seed(self): |
---|
504 | n/a | # This is most interesting to run in debug mode, just to make sure |
---|
505 | n/a | # nothing blows up. Under the covers, a dynamically resized array |
---|
506 | n/a | # is allocated, consuming space proportional to the number of bits |
---|
507 | n/a | # in the seed. Unfortunately, that's a quadratic-time algorithm, |
---|
508 | n/a | # so don't make this horribly big. |
---|
509 | n/a | seed = (1 << (10000 * 8)) - 1 # about 10K bytes |
---|
510 | n/a | self.gen.seed(seed) |
---|
511 | n/a | |
---|
512 | n/a | def test_53_bits_per_float(self): |
---|
513 | n/a | # This should pass whenever a C double has 53 bit precision. |
---|
514 | n/a | span = 2 ** 53 |
---|
515 | n/a | cum = 0 |
---|
516 | n/a | for i in range(100): |
---|
517 | n/a | cum |= int(self.gen.random() * span) |
---|
518 | n/a | self.assertEqual(cum, span-1) |
---|
519 | n/a | |
---|
520 | n/a | def test_bigrand(self): |
---|
521 | n/a | # The randrange routine should build-up the required number of bits |
---|
522 | n/a | # in stages so that all bit positions are active. |
---|
523 | n/a | span = 2 ** 500 |
---|
524 | n/a | cum = 0 |
---|
525 | n/a | for i in range(100): |
---|
526 | n/a | r = self.gen.randrange(span) |
---|
527 | n/a | self.assertTrue(0 <= r < span) |
---|
528 | n/a | cum |= r |
---|
529 | n/a | self.assertEqual(cum, span-1) |
---|
530 | n/a | |
---|
531 | n/a | def test_bigrand_ranges(self): |
---|
532 | n/a | for i in [40,80, 160, 200, 211, 250, 375, 512, 550]: |
---|
533 | n/a | start = self.gen.randrange(2 ** (i-2)) |
---|
534 | n/a | stop = self.gen.randrange(2 ** i) |
---|
535 | n/a | if stop <= start: |
---|
536 | n/a | continue |
---|
537 | n/a | self.assertTrue(start <= self.gen.randrange(start, stop) < stop) |
---|
538 | n/a | |
---|
539 | n/a | def test_rangelimits(self): |
---|
540 | n/a | for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]: |
---|
541 | n/a | self.assertEqual(set(range(start,stop)), |
---|
542 | n/a | set([self.gen.randrange(start,stop) for i in range(100)])) |
---|
543 | n/a | |
---|
544 | n/a | def test_genrandbits(self): |
---|
545 | n/a | # Verify cross-platform repeatability |
---|
546 | n/a | self.gen.seed(1234567) |
---|
547 | n/a | self.assertEqual(self.gen.getrandbits(100), |
---|
548 | n/a | 97904845777343510404718956115) |
---|
549 | n/a | # Verify ranges |
---|
550 | n/a | for k in range(1, 1000): |
---|
551 | n/a | self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k) |
---|
552 | n/a | |
---|
553 | n/a | # Verify all bits active |
---|
554 | n/a | getbits = self.gen.getrandbits |
---|
555 | n/a | for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]: |
---|
556 | n/a | cum = 0 |
---|
557 | n/a | for i in range(100): |
---|
558 | n/a | cum |= getbits(span) |
---|
559 | n/a | self.assertEqual(cum, 2**span-1) |
---|
560 | n/a | |
---|
561 | n/a | # Verify argument checking |
---|
562 | n/a | self.assertRaises(TypeError, self.gen.getrandbits) |
---|
563 | n/a | self.assertRaises(TypeError, self.gen.getrandbits, 'a') |
---|
564 | n/a | self.assertRaises(TypeError, self.gen.getrandbits, 1, 2) |
---|
565 | n/a | self.assertRaises(ValueError, self.gen.getrandbits, 0) |
---|
566 | n/a | self.assertRaises(ValueError, self.gen.getrandbits, -1) |
---|
567 | n/a | |
---|
568 | n/a | def test_randbelow_logic(self, _log=log, int=int): |
---|
569 | n/a | # check bitcount transition points: 2**i and 2**(i+1)-1 |
---|
570 | n/a | # show that: k = int(1.001 + _log(n, 2)) |
---|
571 | n/a | # is equal to or one greater than the number of bits in n |
---|
572 | n/a | for i in range(1, 1000): |
---|
573 | n/a | n = 1 << i # check an exact power of two |
---|
574 | n/a | numbits = i+1 |
---|
575 | n/a | k = int(1.00001 + _log(n, 2)) |
---|
576 | n/a | self.assertEqual(k, numbits) |
---|
577 | n/a | self.assertEqual(n, 2**(k-1)) |
---|
578 | n/a | |
---|
579 | n/a | n += n - 1 # check 1 below the next power of two |
---|
580 | n/a | k = int(1.00001 + _log(n, 2)) |
---|
581 | n/a | self.assertIn(k, [numbits, numbits+1]) |
---|
582 | n/a | self.assertTrue(2**k > n > 2**(k-2)) |
---|
583 | n/a | |
---|
584 | n/a | n -= n >> 15 # check a little farther below the next power of two |
---|
585 | n/a | k = int(1.00001 + _log(n, 2)) |
---|
586 | n/a | self.assertEqual(k, numbits) # note the stronger assertion |
---|
587 | n/a | self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion |
---|
588 | n/a | |
---|
589 | n/a | @unittest.mock.patch('random.Random.random') |
---|
590 | n/a | def test_randbelow_overridden_random(self, random_mock): |
---|
591 | n/a | # Random._randbelow() can only use random() when the built-in one |
---|
592 | n/a | # has been overridden but no new getrandbits() method was supplied. |
---|
593 | n/a | random_mock.side_effect = random.SystemRandom().random |
---|
594 | n/a | maxsize = 1<<random.BPF |
---|
595 | n/a | with warnings.catch_warnings(): |
---|
596 | n/a | warnings.simplefilter("ignore", UserWarning) |
---|
597 | n/a | # Population range too large (n >= maxsize) |
---|
598 | n/a | self.gen._randbelow(maxsize+1, maxsize = maxsize) |
---|
599 | n/a | self.gen._randbelow(5640, maxsize = maxsize) |
---|
600 | n/a | |
---|
601 | n/a | # This might be going too far to test a single line, but because of our |
---|
602 | n/a | # noble aim of achieving 100% test coverage we need to write a case in |
---|
603 | n/a | # which the following line in Random._randbelow() gets executed: |
---|
604 | n/a | # |
---|
605 | n/a | # rem = maxsize % n |
---|
606 | n/a | # limit = (maxsize - rem) / maxsize |
---|
607 | n/a | # r = random() |
---|
608 | n/a | # while r >= limit: |
---|
609 | n/a | # r = random() # <== *This line* <==< |
---|
610 | n/a | # |
---|
611 | n/a | # Therefore, to guarantee that the while loop is executed at least |
---|
612 | n/a | # once, we need to mock random() so that it returns a number greater |
---|
613 | n/a | # than 'limit' the first time it gets called. |
---|
614 | n/a | |
---|
615 | n/a | n = 42 |
---|
616 | n/a | epsilon = 0.01 |
---|
617 | n/a | limit = (maxsize - (maxsize % n)) / maxsize |
---|
618 | n/a | random_mock.side_effect = [limit + epsilon, limit - epsilon] |
---|
619 | n/a | self.gen._randbelow(n, maxsize = maxsize) |
---|
620 | n/a | |
---|
621 | n/a | def test_randrange_bug_1590891(self): |
---|
622 | n/a | start = 1000000000000 |
---|
623 | n/a | stop = -100000000000000000000 |
---|
624 | n/a | step = -200 |
---|
625 | n/a | x = self.gen.randrange(start, stop, step) |
---|
626 | n/a | self.assertTrue(stop < x <= start) |
---|
627 | n/a | self.assertEqual((x+stop)%step, 0) |
---|
628 | n/a | |
---|
629 | n/a | def test_choices_algorithms(self): |
---|
630 | n/a | # The various ways of specifying weights should produce the same results |
---|
631 | n/a | choices = self.gen.choices |
---|
632 | n/a | n = 104729 |
---|
633 | n/a | |
---|
634 | n/a | self.gen.seed(8675309) |
---|
635 | n/a | a = self.gen.choices(range(n), k=10000) |
---|
636 | n/a | |
---|
637 | n/a | self.gen.seed(8675309) |
---|
638 | n/a | b = self.gen.choices(range(n), [1]*n, k=10000) |
---|
639 | n/a | self.assertEqual(a, b) |
---|
640 | n/a | |
---|
641 | n/a | self.gen.seed(8675309) |
---|
642 | n/a | c = self.gen.choices(range(n), cum_weights=range(1, n+1), k=10000) |
---|
643 | n/a | self.assertEqual(a, c) |
---|
644 | n/a | |
---|
645 | n/a | # Amerian Roulette |
---|
646 | n/a | population = ['Red', 'Black', 'Green'] |
---|
647 | n/a | weights = [18, 18, 2] |
---|
648 | n/a | cum_weights = [18, 36, 38] |
---|
649 | n/a | expanded_population = ['Red'] * 18 + ['Black'] * 18 + ['Green'] * 2 |
---|
650 | n/a | |
---|
651 | n/a | self.gen.seed(9035768) |
---|
652 | n/a | a = self.gen.choices(expanded_population, k=10000) |
---|
653 | n/a | |
---|
654 | n/a | self.gen.seed(9035768) |
---|
655 | n/a | b = self.gen.choices(population, weights, k=10000) |
---|
656 | n/a | self.assertEqual(a, b) |
---|
657 | n/a | |
---|
658 | n/a | self.gen.seed(9035768) |
---|
659 | n/a | c = self.gen.choices(population, cum_weights=cum_weights, k=10000) |
---|
660 | n/a | self.assertEqual(a, c) |
---|
661 | n/a | |
---|
662 | n/a | def gamma(z, sqrt2pi=(2.0*pi)**0.5): |
---|
663 | n/a | # Reflection to right half of complex plane |
---|
664 | n/a | if z < 0.5: |
---|
665 | n/a | return pi / sin(pi*z) / gamma(1.0-z) |
---|
666 | n/a | # Lanczos approximation with g=7 |
---|
667 | n/a | az = z + (7.0 - 0.5) |
---|
668 | n/a | return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([ |
---|
669 | n/a | 0.9999999999995183, |
---|
670 | n/a | 676.5203681218835 / z, |
---|
671 | n/a | -1259.139216722289 / (z+1.0), |
---|
672 | n/a | 771.3234287757674 / (z+2.0), |
---|
673 | n/a | -176.6150291498386 / (z+3.0), |
---|
674 | n/a | 12.50734324009056 / (z+4.0), |
---|
675 | n/a | -0.1385710331296526 / (z+5.0), |
---|
676 | n/a | 0.9934937113930748e-05 / (z+6.0), |
---|
677 | n/a | 0.1659470187408462e-06 / (z+7.0), |
---|
678 | n/a | ]) |
---|
679 | n/a | |
---|
680 | n/a | class TestDistributions(unittest.TestCase): |
---|
681 | n/a | def test_zeroinputs(self): |
---|
682 | n/a | # Verify that distributions can handle a series of zero inputs' |
---|
683 | n/a | g = random.Random() |
---|
684 | n/a | x = [g.random() for i in range(50)] + [0.0]*5 |
---|
685 | n/a | g.random = x[:].pop; g.uniform(1,10) |
---|
686 | n/a | g.random = x[:].pop; g.paretovariate(1.0) |
---|
687 | n/a | g.random = x[:].pop; g.expovariate(1.0) |
---|
688 | n/a | g.random = x[:].pop; g.weibullvariate(1.0, 1.0) |
---|
689 | n/a | g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0) |
---|
690 | n/a | g.random = x[:].pop; g.normalvariate(0.0, 1.0) |
---|
691 | n/a | g.random = x[:].pop; g.gauss(0.0, 1.0) |
---|
692 | n/a | g.random = x[:].pop; g.lognormvariate(0.0, 1.0) |
---|
693 | n/a | g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0) |
---|
694 | n/a | g.random = x[:].pop; g.gammavariate(0.01, 1.0) |
---|
695 | n/a | g.random = x[:].pop; g.gammavariate(1.0, 1.0) |
---|
696 | n/a | g.random = x[:].pop; g.gammavariate(200.0, 1.0) |
---|
697 | n/a | g.random = x[:].pop; g.betavariate(3.0, 3.0) |
---|
698 | n/a | g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0) |
---|
699 | n/a | |
---|
700 | n/a | def test_avg_std(self): |
---|
701 | n/a | # Use integration to test distribution average and standard deviation. |
---|
702 | n/a | # Only works for distributions which do not consume variates in pairs |
---|
703 | n/a | g = random.Random() |
---|
704 | n/a | N = 5000 |
---|
705 | n/a | x = [i/float(N) for i in range(1,N)] |
---|
706 | n/a | for variate, args, mu, sigmasqrd in [ |
---|
707 | n/a | (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12), |
---|
708 | n/a | (g.triangular, (0.0, 1.0, 1.0/3.0), 4.0/9.0, 7.0/9.0/18.0), |
---|
709 | n/a | (g.expovariate, (1.5,), 1/1.5, 1/1.5**2), |
---|
710 | n/a | (g.vonmisesvariate, (1.23, 0), pi, pi**2/3), |
---|
711 | n/a | (g.paretovariate, (5.0,), 5.0/(5.0-1), |
---|
712 | n/a | 5.0/((5.0-1)**2*(5.0-2))), |
---|
713 | n/a | (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0), |
---|
714 | n/a | gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]: |
---|
715 | n/a | g.random = x[:].pop |
---|
716 | n/a | y = [] |
---|
717 | n/a | for i in range(len(x)): |
---|
718 | n/a | try: |
---|
719 | n/a | y.append(variate(*args)) |
---|
720 | n/a | except IndexError: |
---|
721 | n/a | pass |
---|
722 | n/a | s1 = s2 = 0 |
---|
723 | n/a | for e in y: |
---|
724 | n/a | s1 += e |
---|
725 | n/a | s2 += (e - mu) ** 2 |
---|
726 | n/a | N = len(y) |
---|
727 | n/a | self.assertAlmostEqual(s1/N, mu, places=2, |
---|
728 | n/a | msg='%s%r' % (variate.__name__, args)) |
---|
729 | n/a | self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2, |
---|
730 | n/a | msg='%s%r' % (variate.__name__, args)) |
---|
731 | n/a | |
---|
732 | n/a | def test_constant(self): |
---|
733 | n/a | g = random.Random() |
---|
734 | n/a | N = 100 |
---|
735 | n/a | for variate, args, expected in [ |
---|
736 | n/a | (g.uniform, (10.0, 10.0), 10.0), |
---|
737 | n/a | (g.triangular, (10.0, 10.0), 10.0), |
---|
738 | n/a | (g.triangular, (10.0, 10.0, 10.0), 10.0), |
---|
739 | n/a | (g.expovariate, (float('inf'),), 0.0), |
---|
740 | n/a | (g.vonmisesvariate, (3.0, float('inf')), 3.0), |
---|
741 | n/a | (g.gauss, (10.0, 0.0), 10.0), |
---|
742 | n/a | (g.lognormvariate, (0.0, 0.0), 1.0), |
---|
743 | n/a | (g.lognormvariate, (-float('inf'), 0.0), 0.0), |
---|
744 | n/a | (g.normalvariate, (10.0, 0.0), 10.0), |
---|
745 | n/a | (g.paretovariate, (float('inf'),), 1.0), |
---|
746 | n/a | (g.weibullvariate, (10.0, float('inf')), 10.0), |
---|
747 | n/a | (g.weibullvariate, (0.0, 10.0), 0.0), |
---|
748 | n/a | ]: |
---|
749 | n/a | for i in range(N): |
---|
750 | n/a | self.assertEqual(variate(*args), expected) |
---|
751 | n/a | |
---|
752 | n/a | def test_von_mises_range(self): |
---|
753 | n/a | # Issue 17149: von mises variates were not consistently in the |
---|
754 | n/a | # range [0, 2*PI]. |
---|
755 | n/a | g = random.Random() |
---|
756 | n/a | N = 100 |
---|
757 | n/a | for mu in 0.0, 0.1, 3.1, 6.2: |
---|
758 | n/a | for kappa in 0.0, 2.3, 500.0: |
---|
759 | n/a | for _ in range(N): |
---|
760 | n/a | sample = g.vonmisesvariate(mu, kappa) |
---|
761 | n/a | self.assertTrue( |
---|
762 | n/a | 0 <= sample <= random.TWOPI, |
---|
763 | n/a | msg=("vonmisesvariate({}, {}) produced a result {} out" |
---|
764 | n/a | " of range [0, 2*pi]").format(mu, kappa, sample)) |
---|
765 | n/a | |
---|
766 | n/a | def test_von_mises_large_kappa(self): |
---|
767 | n/a | # Issue #17141: vonmisesvariate() was hang for large kappas |
---|
768 | n/a | random.vonmisesvariate(0, 1e15) |
---|
769 | n/a | random.vonmisesvariate(0, 1e100) |
---|
770 | n/a | |
---|
771 | n/a | def test_gammavariate_errors(self): |
---|
772 | n/a | # Both alpha and beta must be > 0.0 |
---|
773 | n/a | self.assertRaises(ValueError, random.gammavariate, -1, 3) |
---|
774 | n/a | self.assertRaises(ValueError, random.gammavariate, 0, 2) |
---|
775 | n/a | self.assertRaises(ValueError, random.gammavariate, 2, 0) |
---|
776 | n/a | self.assertRaises(ValueError, random.gammavariate, 1, -3) |
---|
777 | n/a | |
---|
778 | n/a | @unittest.mock.patch('random.Random.random') |
---|
779 | n/a | def test_gammavariate_full_code_coverage(self, random_mock): |
---|
780 | n/a | # There are three different possibilities in the current implementation |
---|
781 | n/a | # of random.gammavariate(), depending on the value of 'alpha'. What we |
---|
782 | n/a | # are going to do here is to fix the values returned by random() to |
---|
783 | n/a | # generate test cases that provide 100% line coverage of the method. |
---|
784 | n/a | |
---|
785 | n/a | # #1: alpha > 1.0: we want the first random number to be outside the |
---|
786 | n/a | # [1e-7, .9999999] range, so that the continue statement executes |
---|
787 | n/a | # once. The values of u1 and u2 will be 0.5 and 0.3, respectively. |
---|
788 | n/a | random_mock.side_effect = [1e-8, 0.5, 0.3] |
---|
789 | n/a | returned_value = random.gammavariate(1.1, 2.3) |
---|
790 | n/a | self.assertAlmostEqual(returned_value, 2.53) |
---|
791 | n/a | |
---|
792 | n/a | # #2: alpha == 1: first random number less than 1e-7 to that the body |
---|
793 | n/a | # of the while loop executes once. Then random.random() returns 0.45, |
---|
794 | n/a | # which causes while to stop looping and the algorithm to terminate. |
---|
795 | n/a | random_mock.side_effect = [1e-8, 0.45] |
---|
796 | n/a | returned_value = random.gammavariate(1.0, 3.14) |
---|
797 | n/a | self.assertAlmostEqual(returned_value, 2.507314166123803) |
---|
798 | n/a | |
---|
799 | n/a | # #3: 0 < alpha < 1. This is the most complex region of code to cover, |
---|
800 | n/a | # as there are multiple if-else statements. Let's take a look at the |
---|
801 | n/a | # source code, and determine the values that we need accordingly: |
---|
802 | n/a | # |
---|
803 | n/a | # while 1: |
---|
804 | n/a | # u = random() |
---|
805 | n/a | # b = (_e + alpha)/_e |
---|
806 | n/a | # p = b*u |
---|
807 | n/a | # if p <= 1.0: # <=== (A) |
---|
808 | n/a | # x = p ** (1.0/alpha) |
---|
809 | n/a | # else: # <=== (B) |
---|
810 | n/a | # x = -_log((b-p)/alpha) |
---|
811 | n/a | # u1 = random() |
---|
812 | n/a | # if p > 1.0: # <=== (C) |
---|
813 | n/a | # if u1 <= x ** (alpha - 1.0): # <=== (D) |
---|
814 | n/a | # break |
---|
815 | n/a | # elif u1 <= _exp(-x): # <=== (E) |
---|
816 | n/a | # break |
---|
817 | n/a | # return x * beta |
---|
818 | n/a | # |
---|
819 | n/a | # First, we want (A) to be True. For that we need that: |
---|
820 | n/a | # b*random() <= 1.0 |
---|
821 | n/a | # r1 = random() <= 1.0 / b |
---|
822 | n/a | # |
---|
823 | n/a | # We now get to the second if-else branch, and here, since p <= 1.0, |
---|
824 | n/a | # (C) is False and we take the elif branch, (E). For it to be True, |
---|
825 | n/a | # so that the break is executed, we need that: |
---|
826 | n/a | # r2 = random() <= _exp(-x) |
---|
827 | n/a | # r2 <= _exp(-(p ** (1.0/alpha))) |
---|
828 | n/a | # r2 <= _exp(-((b*r1) ** (1.0/alpha))) |
---|
829 | n/a | |
---|
830 | n/a | _e = random._e |
---|
831 | n/a | _exp = random._exp |
---|
832 | n/a | _log = random._log |
---|
833 | n/a | alpha = 0.35 |
---|
834 | n/a | beta = 1.45 |
---|
835 | n/a | b = (_e + alpha)/_e |
---|
836 | n/a | epsilon = 0.01 |
---|
837 | n/a | |
---|
838 | n/a | r1 = 0.8859296441566 # 1.0 / b |
---|
839 | n/a | r2 = 0.3678794411714 # _exp(-((b*r1) ** (1.0/alpha))) |
---|
840 | n/a | |
---|
841 | n/a | # These four "random" values result in the following trace: |
---|
842 | n/a | # (A) True, (E) False --> [next iteration of while] |
---|
843 | n/a | # (A) True, (E) True --> [while loop breaks] |
---|
844 | n/a | random_mock.side_effect = [r1, r2 + epsilon, r1, r2] |
---|
845 | n/a | returned_value = random.gammavariate(alpha, beta) |
---|
846 | n/a | self.assertAlmostEqual(returned_value, 1.4499999999997544) |
---|
847 | n/a | |
---|
848 | n/a | # Let's now make (A) be False. If this is the case, when we get to the |
---|
849 | n/a | # second if-else 'p' is greater than 1, so (C) evaluates to True. We |
---|
850 | n/a | # now encounter a second if statement, (D), which in order to execute |
---|
851 | n/a | # must satisfy the following condition: |
---|
852 | n/a | # r2 <= x ** (alpha - 1.0) |
---|
853 | n/a | # r2 <= (-_log((b-p)/alpha)) ** (alpha - 1.0) |
---|
854 | n/a | # r2 <= (-_log((b-(b*r1))/alpha)) ** (alpha - 1.0) |
---|
855 | n/a | r1 = 0.8959296441566 # (1.0 / b) + epsilon -- so that (A) is False |
---|
856 | n/a | r2 = 0.9445400408898141 |
---|
857 | n/a | |
---|
858 | n/a | # And these four values result in the following trace: |
---|
859 | n/a | # (B) and (C) True, (D) False --> [next iteration of while] |
---|
860 | n/a | # (B) and (C) True, (D) True [while loop breaks] |
---|
861 | n/a | random_mock.side_effect = [r1, r2 + epsilon, r1, r2] |
---|
862 | n/a | returned_value = random.gammavariate(alpha, beta) |
---|
863 | n/a | self.assertAlmostEqual(returned_value, 1.5830349561760781) |
---|
864 | n/a | |
---|
865 | n/a | @unittest.mock.patch('random.Random.gammavariate') |
---|
866 | n/a | def test_betavariate_return_zero(self, gammavariate_mock): |
---|
867 | n/a | # betavariate() returns zero when the Gamma distribution |
---|
868 | n/a | # that it uses internally returns this same value. |
---|
869 | n/a | gammavariate_mock.return_value = 0.0 |
---|
870 | n/a | self.assertEqual(0.0, random.betavariate(2.71828, 3.14159)) |
---|
871 | n/a | |
---|
872 | n/a | class TestModule(unittest.TestCase): |
---|
873 | n/a | def testMagicConstants(self): |
---|
874 | n/a | self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141) |
---|
875 | n/a | self.assertAlmostEqual(random.TWOPI, 6.28318530718) |
---|
876 | n/a | self.assertAlmostEqual(random.LOG4, 1.38629436111989) |
---|
877 | n/a | self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627) |
---|
878 | n/a | |
---|
879 | n/a | def test__all__(self): |
---|
880 | n/a | # tests validity but not completeness of the __all__ list |
---|
881 | n/a | self.assertTrue(set(random.__all__) <= set(dir(random))) |
---|
882 | n/a | |
---|
883 | n/a | def test_random_subclass_with_kwargs(self): |
---|
884 | n/a | # SF bug #1486663 -- this used to erroneously raise a TypeError |
---|
885 | n/a | class Subclass(random.Random): |
---|
886 | n/a | def __init__(self, newarg=None): |
---|
887 | n/a | random.Random.__init__(self) |
---|
888 | n/a | Subclass(newarg=1) |
---|
889 | n/a | |
---|
890 | n/a | |
---|
891 | n/a | if __name__ == "__main__": |
---|
892 | n/a | unittest.main() |
---|