blob: 0c1fdeec9915ee8720fa902f22bfcd8b0b7a6b3e [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
Dong-hee Na6989af02020-06-21 18:44:58 +09008import test.support
9
R David Murraye3e1c172013-04-02 12:47:23 -040010from functools import partial
Victor Stinnerbd1b49a2016-10-19 10:11:37 +020011from math import log, exp, pi, fsum, sin, factorial
Benjamin Petersonee8712c2008-05-20 21:35:26 +000012from test import support
Raymond Hettingere8f1e002016-09-06 17:15:29 -070013from fractions import Fraction
Raymond Hettinger81a5fc32020-05-08 07:53:15 -070014from collections import Counter
csabellaf111fd22017-05-11 11:19:35 -040015
Ezio Melotti3e4a98b2013-04-19 05:45:27 +030016class TestBasicOps:
Raymond Hettinger40f62172002-12-29 23:03:38 +000017 # Superclass with tests common to all generators.
18 # Subclasses must arrange for self.gen to retrieve the Random instance
19 # to be tested.
Tim Peters46c04e12002-05-05 20:40:00 +000020
Raymond Hettinger40f62172002-12-29 23:03:38 +000021 def randomlist(self, n):
22 """Helper function to make a list of random numbers"""
Guido van Rossum805365e2007-05-07 22:24:25 +000023 return [self.gen.random() for i in range(n)]
Tim Peters46c04e12002-05-05 20:40:00 +000024
Raymond Hettinger40f62172002-12-29 23:03:38 +000025 def test_autoseed(self):
26 self.gen.seed()
27 state1 = self.gen.getstate()
Raymond Hettinger3081d592003-08-09 18:30:57 +000028 time.sleep(0.1)
Mike53f7a7c2017-12-14 14:04:53 +030029 self.gen.seed() # different seeds at different times
Raymond Hettinger40f62172002-12-29 23:03:38 +000030 state2 = self.gen.getstate()
31 self.assertNotEqual(state1, state2)
Tim Peters46c04e12002-05-05 20:40:00 +000032
Raymond Hettinger40f62172002-12-29 23:03:38 +000033 def test_saverestore(self):
34 N = 1000
35 self.gen.seed()
36 state = self.gen.getstate()
37 randseq = self.randomlist(N)
38 self.gen.setstate(state) # should regenerate the same sequence
39 self.assertEqual(randseq, self.randomlist(N))
40
41 def test_seedargs(self):
Mark Dickinson95aeae02012-06-24 11:05:30 +010042 # Seed value with a negative hash.
43 class MySeed(object):
44 def __hash__(self):
45 return -1729
Xtreaka06d6832019-09-12 09:13:20 +010046 for arg in [None, 0, 1, -1, 10**20, -(10**20),
Victor Stinner00d7cd82020-03-10 15:15:14 +010047 False, True, 3.14, 'a']:
Raymond Hettinger40f62172002-12-29 23:03:38 +000048 self.gen.seed(arg)
Xtreaka06d6832019-09-12 09:13:20 +010049
50 for arg in [1+2j, tuple('abc'), MySeed()]:
51 with self.assertWarns(DeprecationWarning):
52 self.gen.seed(arg)
53
Guido van Rossum805365e2007-05-07 22:24:25 +000054 for arg in [list(range(3)), dict(one=1)]:
Xtreaka06d6832019-09-12 09:13:20 +010055 with self.assertWarns(DeprecationWarning):
56 self.assertRaises(TypeError, self.gen.seed, arg)
Raymond Hettingerf763a722010-09-07 00:38:15 +000057 self.assertRaises(TypeError, self.gen.seed, 1, 2, 3, 4)
Raymond Hettinger58335872004-07-09 14:26:18 +000058 self.assertRaises(TypeError, type(self.gen), [])
Raymond Hettinger40f62172002-12-29 23:03:38 +000059
R David Murraye3e1c172013-04-02 12:47:23 -040060 @unittest.mock.patch('random._urandom') # os.urandom
61 def test_seed_when_randomness_source_not_found(self, urandom_mock):
62 # Random.seed() uses time.time() when an operating system specific
csabellaf111fd22017-05-11 11:19:35 -040063 # randomness source is not found. To test this on machines where it
R David Murraye3e1c172013-04-02 12:47:23 -040064 # exists, run the above test, test_seedargs(), again after mocking
65 # os.urandom() so that it raises the exception expected when the
66 # randomness source is not available.
67 urandom_mock.side_effect = NotImplementedError
68 self.test_seedargs()
69
Antoine Pitrou5e394332012-11-04 02:10:33 +010070 def test_shuffle(self):
71 shuffle = self.gen.shuffle
72 lst = []
73 shuffle(lst)
74 self.assertEqual(lst, [])
75 lst = [37]
76 shuffle(lst)
77 self.assertEqual(lst, [37])
78 seqs = [list(range(n)) for n in range(10)]
79 shuffled_seqs = [list(range(n)) for n in range(10)]
80 for shuffled_seq in shuffled_seqs:
81 shuffle(shuffled_seq)
82 for (seq, shuffled_seq) in zip(seqs, shuffled_seqs):
83 self.assertEqual(len(seq), len(shuffled_seq))
84 self.assertEqual(set(seq), set(shuffled_seq))
Antoine Pitrou5e394332012-11-04 02:10:33 +010085 # The above tests all would pass if the shuffle was a
86 # no-op. The following non-deterministic test covers that. It
87 # asserts that the shuffled sequence of 1000 distinct elements
88 # must be different from the original one. Although there is
89 # mathematically a non-zero probability that this could
90 # actually happen in a genuinely random shuffle, it is
91 # completely negligible, given that the number of possible
92 # permutations of 1000 objects is 1000! (factorial of 1000),
93 # which is considerably larger than the number of atoms in the
94 # universe...
95 lst = list(range(1000))
96 shuffled_lst = list(range(1000))
97 shuffle(shuffled_lst)
98 self.assertTrue(lst != shuffled_lst)
99 shuffle(lst)
100 self.assertTrue(lst != shuffled_lst)
csabellaf111fd22017-05-11 11:19:35 -0400101 self.assertRaises(TypeError, shuffle, (1, 2, 3))
102
103 def test_shuffle_random_argument(self):
104 # Test random argument to shuffle.
105 shuffle = self.gen.shuffle
106 mock_random = unittest.mock.Mock(return_value=0.5)
107 seq = bytearray(b'abcdefghijk')
Raymond Hettinger190fac92020-05-02 16:45:32 -0700108 with self.assertWarns(DeprecationWarning):
109 shuffle(seq, mock_random)
csabellaf111fd22017-05-11 11:19:35 -0400110 mock_random.assert_called_with()
Antoine Pitrou5e394332012-11-04 02:10:33 +0100111
Raymond Hettingerdc4872e2010-09-07 10:06:56 +0000112 def test_choice(self):
113 choice = self.gen.choice
114 with self.assertRaises(IndexError):
115 choice([])
116 self.assertEqual(choice([50]), 50)
117 self.assertIn(choice([25, 75]), [25, 75])
118
Raymond Hettinger40f62172002-12-29 23:03:38 +0000119 def test_sample(self):
120 # For the entire allowable range of 0 <= k <= N, validate that
121 # the sample is of the correct length and contains only unique items
122 N = 100
Guido van Rossum805365e2007-05-07 22:24:25 +0000123 population = range(N)
124 for k in range(N+1):
Raymond Hettinger40f62172002-12-29 23:03:38 +0000125 s = self.gen.sample(population, k)
126 self.assertEqual(len(s), k)
Raymond Hettingera690a992003-11-16 16:17:49 +0000127 uniq = set(s)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000128 self.assertEqual(len(uniq), k)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000129 self.assertTrue(uniq <= set(population))
Raymond Hettinger8ec78812003-01-04 05:55:11 +0000130 self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0
R David Murraye3e1c172013-04-02 12:47:23 -0400131 # Exception raised if size of sample exceeds that of population
132 self.assertRaises(ValueError, self.gen.sample, population, N+1)
Raymond Hettingerbf871262016-11-21 14:34:33 -0800133 self.assertRaises(ValueError, self.gen.sample, [], -1)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000134
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000135 def test_sample_distribution(self):
136 # For the entire allowable range of 0 <= k <= N, validate that
137 # sample generates all possible permutations
138 n = 5
139 pop = range(n)
140 trials = 10000 # large num prevents false negatives without slowing normal case
Guido van Rossum805365e2007-05-07 22:24:25 +0000141 for k in range(n):
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +0000142 expected = factorial(n) // factorial(n-k)
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000143 perms = {}
Guido van Rossum805365e2007-05-07 22:24:25 +0000144 for i in range(trials):
Raymond Hettinger7b0cf762003-01-17 17:23:23 +0000145 perms[tuple(self.gen.sample(pop, k))] = None
146 if len(perms) == expected:
147 break
148 else:
149 self.fail()
150
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000151 def test_sample_inputs(self):
152 # SF bug #801342 -- population can be any iterable defining __len__()
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000153 self.gen.sample(range(20), 2)
Guido van Rossum805365e2007-05-07 22:24:25 +0000154 self.gen.sample(range(20), 2)
Raymond Hettinger66d09f12003-09-06 04:25:54 +0000155 self.gen.sample(str('abcdefghijklmnopqrst'), 2)
156 self.gen.sample(tuple('abcdefghijklmnopqrst'), 2)
157
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000158 def test_sample_on_dicts(self):
Raymond Hettinger1acde192008-01-14 01:00:53 +0000159 self.assertRaises(TypeError, self.gen.sample, dict.fromkeys('abcdef'), 2)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000160
Raymond Hettinger4fe00202020-04-19 00:36:42 -0700161 def test_sample_on_sets(self):
162 with self.assertWarns(DeprecationWarning):
163 population = {10, 20, 30, 40, 50, 60, 70}
164 self.gen.sample(population, k=5)
165
Raymond Hettinger81a5fc32020-05-08 07:53:15 -0700166 def test_sample_with_counts(self):
167 sample = self.gen.sample
168
169 # General case
170 colors = ['red', 'green', 'blue', 'orange', 'black', 'brown', 'amber']
171 counts = [500, 200, 20, 10, 5, 0, 1 ]
172 k = 700
173 summary = Counter(sample(colors, counts=counts, k=k))
174 self.assertEqual(sum(summary.values()), k)
175 for color, weight in zip(colors, counts):
176 self.assertLessEqual(summary[color], weight)
177 self.assertNotIn('brown', summary)
178
179 # Case that exhausts the population
180 k = sum(counts)
181 summary = Counter(sample(colors, counts=counts, k=k))
182 self.assertEqual(sum(summary.values()), k)
183 for color, weight in zip(colors, counts):
184 self.assertLessEqual(summary[color], weight)
185 self.assertNotIn('brown', summary)
186
187 # Case with population size of 1
188 summary = Counter(sample(['x'], counts=[10], k=8))
189 self.assertEqual(summary, Counter(x=8))
190
191 # Case with all counts equal.
192 nc = len(colors)
193 summary = Counter(sample(colors, counts=[10]*nc, k=10*nc))
194 self.assertEqual(summary, Counter(10*colors))
195
196 # Test error handling
197 with self.assertRaises(TypeError):
198 sample(['red', 'green', 'blue'], counts=10, k=10) # counts not iterable
199 with self.assertRaises(ValueError):
200 sample(['red', 'green', 'blue'], counts=[-3, -7, -8], k=2) # counts are negative
201 with self.assertRaises(ValueError):
202 sample(['red', 'green', 'blue'], counts=[0, 0, 0], k=2) # counts are zero
203 with self.assertRaises(ValueError):
204 sample(['red', 'green'], counts=[10, 10], k=21) # population too small
205 with self.assertRaises(ValueError):
206 sample(['red', 'green', 'blue'], counts=[1, 2], k=2) # too few counts
207 with self.assertRaises(ValueError):
208 sample(['red', 'green', 'blue'], counts=[1, 2, 3, 4], k=2) # too many counts
209
210 def test_sample_counts_equivalence(self):
211 # Test the documented strong equivalence to a sample with repeated elements.
212 # We run this test on random.Random() which makes deterministic selections
213 # for a given seed value.
214 sample = random.sample
215 seed = random.seed
216
217 colors = ['red', 'green', 'blue', 'orange', 'black', 'amber']
218 counts = [500, 200, 20, 10, 5, 1 ]
219 k = 700
220 seed(8675309)
221 s1 = sample(colors, counts=counts, k=k)
222 seed(8675309)
223 expanded = [color for (color, count) in zip(colors, counts) for i in range(count)]
224 self.assertEqual(len(expanded), sum(counts))
225 s2 = sample(expanded, k=k)
226 self.assertEqual(s1, s2)
227
228 pop = 'abcdefghi'
229 counts = [10, 9, 8, 7, 6, 5, 4, 3, 2]
230 seed(8675309)
231 s1 = ''.join(sample(pop, counts=counts, k=30))
232 expanded = ''.join([letter for (letter, count) in zip(pop, counts) for i in range(count)])
233 seed(8675309)
234 s2 = ''.join(sample(expanded, k=30))
235 self.assertEqual(s1, s2)
236
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700237 def test_choices(self):
238 choices = self.gen.choices
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700239 data = ['red', 'green', 'blue', 'yellow']
240 str_data = 'abcd'
241 range_data = range(4)
242 set_data = set(range(4))
243
244 # basic functionality
245 for sample in [
Raymond Hettinger9016f282016-09-26 21:45:57 -0700246 choices(data, k=5),
247 choices(data, range(4), k=5),
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700248 choices(k=5, population=data, weights=range(4)),
249 choices(k=5, population=data, cum_weights=range(4)),
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700250 ]:
251 self.assertEqual(len(sample), 5)
252 self.assertEqual(type(sample), list)
253 self.assertTrue(set(sample) <= set(data))
254
255 # test argument handling
Raymond Hettinger28aa4a02016-09-07 00:08:44 -0700256 with self.assertRaises(TypeError): # missing arguments
257 choices(2)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700258
Raymond Hettinger9016f282016-09-26 21:45:57 -0700259 self.assertEqual(choices(data, k=0), []) # k == 0
260 self.assertEqual(choices(data, k=-1), []) # negative k behaves like ``[0] * -1``
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700261 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700262 choices(data, k=2.5) # k is a float
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700263
Raymond Hettinger9016f282016-09-26 21:45:57 -0700264 self.assertTrue(set(choices(str_data, k=5)) <= set(str_data)) # population is a string sequence
265 self.assertTrue(set(choices(range_data, k=5)) <= set(range_data)) # population is a range
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700266 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700267 choices(set_data, k=2) # population is not a sequence
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700268
Raymond Hettinger9016f282016-09-26 21:45:57 -0700269 self.assertTrue(set(choices(data, None, k=5)) <= set(data)) # weights is None
270 self.assertTrue(set(choices(data, weights=None, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700271 with self.assertRaises(ValueError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700272 choices(data, [1,2], k=5) # len(weights) != len(population)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700273 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700274 choices(data, 10, k=5) # non-iterable weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700275 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700276 choices(data, [None]*4, k=5) # non-numeric weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700277 for weights in [
278 [15, 10, 25, 30], # integer weights
279 [15.1, 10.2, 25.2, 30.3], # float weights
280 [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional weights
281 [True, False, True, False] # booleans (include / exclude)
282 ]:
Raymond Hettinger9016f282016-09-26 21:45:57 -0700283 self.assertTrue(set(choices(data, weights, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700284
285 with self.assertRaises(ValueError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700286 choices(data, cum_weights=[1,2], k=5) # len(weights) != len(population)
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700287 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700288 choices(data, cum_weights=10, k=5) # non-iterable cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700289 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700290 choices(data, cum_weights=[None]*4, k=5) # non-numeric cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700291 with self.assertRaises(TypeError):
Raymond Hettinger9016f282016-09-26 21:45:57 -0700292 choices(data, range(4), cum_weights=range(4), k=5) # both weights and cum_weights
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700293 for weights in [
294 [15, 10, 25, 30], # integer cum_weights
295 [15.1, 10.2, 25.2, 30.3], # float cum_weights
296 [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional cum_weights
297 ]:
Raymond Hettinger9016f282016-09-26 21:45:57 -0700298 self.assertTrue(set(choices(data, cum_weights=weights, k=5)) <= set(data))
Raymond Hettingere8f1e002016-09-06 17:15:29 -0700299
Raymond Hettinger7b166522016-10-14 01:19:38 -0400300 # Test weight focused on a single element of the population
301 self.assertEqual(choices('abcd', [1, 0, 0, 0]), ['a'])
302 self.assertEqual(choices('abcd', [0, 1, 0, 0]), ['b'])
303 self.assertEqual(choices('abcd', [0, 0, 1, 0]), ['c'])
304 self.assertEqual(choices('abcd', [0, 0, 0, 1]), ['d'])
305
306 # Test consistency with random.choice() for empty population
307 with self.assertRaises(IndexError):
308 choices([], k=1)
309 with self.assertRaises(IndexError):
310 choices([], weights=[], k=1)
311 with self.assertRaises(IndexError):
312 choices([], cum_weights=[], k=5)
313
Raymond Hettingerddf71712018-06-27 01:08:31 -0700314 def test_choices_subnormal(self):
Min ho Kim96e12d52019-07-22 06:12:33 +1000315 # Subnormal weights would occasionally trigger an IndexError
Raymond Hettingerddf71712018-06-27 01:08:31 -0700316 # in choices() when the value returned by random() was large
317 # enough to make `random() * total` round up to the total.
318 # See https://bugs.python.org/msg275594 for more detail.
319 choices = self.gen.choices
320 choices(population=[1, 2], weights=[1e-323, 1e-323], k=5000)
321
Raymond Hettinger041d8b42019-11-23 02:22:13 -0800322 def test_choices_with_all_zero_weights(self):
323 # See issue #38881
324 with self.assertRaises(ValueError):
325 self.gen.choices('AB', [0.0, 0.0])
326
Ram Rachumb0dfc752020-09-29 04:32:10 +0300327 def test_choices_negative_total(self):
328 with self.assertRaises(ValueError):
329 self.gen.choices('ABC', [3, -5, 1])
330
331 def test_choices_infinite_total(self):
332 with self.assertRaises(ValueError):
333 self.gen.choices('A', [float('inf')])
334 with self.assertRaises(ValueError):
335 self.gen.choices('AB', [0.0, float('inf')])
336 with self.assertRaises(ValueError):
337 self.gen.choices('AB', [-float('inf'), 123])
338 with self.assertRaises(ValueError):
339 self.gen.choices('AB', [0.0, float('nan')])
340 with self.assertRaises(ValueError):
341 self.gen.choices('AB', [float('-inf'), float('inf')])
342
Raymond Hettinger40f62172002-12-29 23:03:38 +0000343 def test_gauss(self):
344 # Ensure that the seed() method initializes all the hidden state. In
345 # particular, through 2.2.1 it failed to reset a piece of state used
346 # by (and only by) the .gauss() method.
347
348 for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
349 self.gen.seed(seed)
350 x1 = self.gen.random()
351 y1 = self.gen.gauss(0, 1)
352
353 self.gen.seed(seed)
354 x2 = self.gen.random()
355 y2 = self.gen.gauss(0, 1)
356
357 self.assertEqual(x1, x2)
358 self.assertEqual(y1, y2)
359
Antoine Pitrou75a33782020-04-17 19:32:14 +0200360 def test_getrandbits(self):
361 # Verify ranges
362 for k in range(1, 1000):
363 self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
364 self.assertEqual(self.gen.getrandbits(0), 0)
365
366 # Verify all bits active
367 getbits = self.gen.getrandbits
368 for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
369 all_bits = 2**span-1
370 cum = 0
371 cpl_cum = 0
372 for i in range(100):
373 v = getbits(span)
374 cum |= v
375 cpl_cum |= all_bits ^ v
376 self.assertEqual(cum, all_bits)
377 self.assertEqual(cpl_cum, all_bits)
378
379 # Verify argument checking
380 self.assertRaises(TypeError, self.gen.getrandbits)
381 self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
382 self.assertRaises(ValueError, self.gen.getrandbits, -1)
383 self.assertRaises(TypeError, self.gen.getrandbits, 10.1)
384
Raymond Hettinger5f078ff2003-06-24 20:29:04 +0000385 def test_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200386 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
387 state = pickle.dumps(self.gen, proto)
388 origseq = [self.gen.random() for i in range(10)]
389 newgen = pickle.loads(state)
390 restoredseq = [newgen.random() for i in range(10)]
391 self.assertEqual(origseq, restoredseq)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000392
Dong-hee Na6989af02020-06-21 18:44:58 +0900393 @test.support.cpython_only
394 def test_bug_41052(self):
395 # _random.Random should not be allowed to serialization
396 import _random
397 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
398 r = _random.Random()
399 self.assertRaises(TypeError, pickle.dumps, r, proto)
400
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000401 def test_bug_1727780(self):
402 # verify that version-2-pickles can be loaded
403 # fine, whether they are created on 32-bit or 64-bit
404 # platforms, and that version-3-pickles load fine.
405 files = [("randv2_32.pck", 780),
406 ("randv2_64.pck", 866),
407 ("randv3.pck", 343)]
408 for file, value in files:
Serhiy Storchaka5b10b982019-03-05 10:06:26 +0200409 with open(support.findfile(file),"rb") as f:
410 r = pickle.load(f)
Raymond Hettinger05156612010-09-07 04:44:52 +0000411 self.assertEqual(int(r.random()*1000), value)
412
413 def test_bug_9025(self):
414 # Had problem with an uneven distribution in int(n*random())
415 # Verify the fix by checking that distributions fall within expectations.
416 n = 100000
417 randrange = self.gen.randrange
418 k = sum(randrange(6755399441055744) % 3 == 2 for i in range(n))
419 self.assertTrue(0.30 < k/n < .37, (k/n))
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000420
Victor Stinner9f5fe792020-04-17 19:05:35 +0200421 def test_randbytes(self):
422 # Verify ranges
423 for n in range(1, 10):
424 data = self.gen.randbytes(n)
425 self.assertEqual(type(data), bytes)
426 self.assertEqual(len(data), n)
427
428 self.assertEqual(self.gen.randbytes(0), b'')
429
430 # Verify argument checking
431 self.assertRaises(TypeError, self.gen.randbytes)
432 self.assertRaises(TypeError, self.gen.randbytes, 1, 2)
433 self.assertRaises(ValueError, self.gen.randbytes, -1)
434 self.assertRaises(TypeError, self.gen.randbytes, 1.0)
435
436
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300437try:
438 random.SystemRandom().random()
439except NotImplementedError:
440 SystemRandom_available = False
441else:
442 SystemRandom_available = True
443
444@unittest.skipUnless(SystemRandom_available, "random.SystemRandom not available")
445class SystemRandom_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger23f12412004-09-13 22:23:21 +0000446 gen = random.SystemRandom()
Raymond Hettinger356a4592004-08-30 06:14:31 +0000447
448 def test_autoseed(self):
449 # Doesn't need to do anything except not fail
450 self.gen.seed()
451
452 def test_saverestore(self):
453 self.assertRaises(NotImplementedError, self.gen.getstate)
454 self.assertRaises(NotImplementedError, self.gen.setstate, None)
455
456 def test_seedargs(self):
457 # Doesn't need to do anything except not fail
458 self.gen.seed(100)
459
Raymond Hettinger356a4592004-08-30 06:14:31 +0000460 def test_gauss(self):
461 self.gen.gauss_next = None
462 self.gen.seed(100)
463 self.assertEqual(self.gen.gauss_next, None)
464
465 def test_pickling(self):
Serhiy Storchakabad12572014-12-15 14:03:42 +0200466 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
467 self.assertRaises(NotImplementedError, pickle.dumps, self.gen, proto)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000468
469 def test_53_bits_per_float(self):
470 # This should pass whenever a C double has 53 bit precision.
471 span = 2 ** 53
472 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000473 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000474 cum |= int(self.gen.random() * span)
475 self.assertEqual(cum, span-1)
476
477 def test_bigrand(self):
478 # The randrange routine should build-up the required number of bits
479 # in stages so that all bit positions are active.
480 span = 2 ** 500
481 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000482 for i in range(100):
Raymond Hettinger356a4592004-08-30 06:14:31 +0000483 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000484 self.assertTrue(0 <= r < span)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000485 cum |= r
486 self.assertEqual(cum, span-1)
487
488 def test_bigrand_ranges(self):
489 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600490 start = self.gen.randrange(2 ** (i-2))
491 stop = self.gen.randrange(2 ** i)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000492 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600493 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000494 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger356a4592004-08-30 06:14:31 +0000495
496 def test_rangelimits(self):
497 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
498 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000499 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000500
R David Murraye3e1c172013-04-02 12:47:23 -0400501 def test_randrange_nonunit_step(self):
502 rint = self.gen.randrange(0, 10, 2)
503 self.assertIn(rint, (0, 2, 4, 6, 8))
504 rint = self.gen.randrange(0, 2, 2)
505 self.assertEqual(rint, 0)
506
507 def test_randrange_errors(self):
508 raises = partial(self.assertRaises, ValueError, self.gen.randrange)
509 # Empty range
510 raises(3, 3)
511 raises(-721)
512 raises(0, 100, -12)
513 # Non-integer start/stop
514 raises(3.14159)
515 raises(0, 2.71828)
516 # Zero and non-integer step
517 raises(0, 42, 0)
518 raises(0, 42, 3.14159)
519
Raymond Hettinger356a4592004-08-30 06:14:31 +0000520 def test_randbelow_logic(self, _log=log, int=int):
521 # check bitcount transition points: 2**i and 2**(i+1)-1
522 # show that: k = int(1.001 + _log(n, 2))
523 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000524 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000525 n = 1 << i # check an exact power of two
Raymond Hettinger356a4592004-08-30 06:14:31 +0000526 numbits = i+1
527 k = int(1.00001 + _log(n, 2))
528 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000529 self.assertEqual(n, 2**(k-1))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000530
531 n += n - 1 # check 1 below the next power of two
532 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000533 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000534 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger356a4592004-08-30 06:14:31 +0000535
536 n -= n >> 15 # check a little farther below the next power of two
537 k = int(1.00001 + _log(n, 2))
538 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000539 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger356a4592004-08-30 06:14:31 +0000540
541
Ezio Melotti3e4a98b2013-04-19 05:45:27 +0300542class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase):
Raymond Hettinger40f62172002-12-29 23:03:38 +0000543 gen = random.Random()
544
Raymond Hettingerf763a722010-09-07 00:38:15 +0000545 def test_guaranteed_stable(self):
546 # These sequences are guaranteed to stay the same across versions of python
547 self.gen.seed(3456147, version=1)
548 self.assertEqual([self.gen.random().hex() for i in range(4)],
549 ['0x1.ac362300d90d2p-1', '0x1.9d16f74365005p-1',
550 '0x1.1ebb4352e4c4dp-1', '0x1.1a7422abf9c11p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000551 self.gen.seed("the quick brown fox", version=2)
552 self.assertEqual([self.gen.random().hex() for i in range(4)],
Raymond Hettinger3fcf0022010-12-08 01:13:53 +0000553 ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4',
554 '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1'])
Raymond Hettingerf763a722010-09-07 00:38:15 +0000555
Raymond Hettingerc7bab7c2016-08-31 15:01:08 -0700556 def test_bug_27706(self):
557 # Verify that version 1 seeds are unaffected by hash randomization
558
559 self.gen.seed('nofar', version=1) # hash('nofar') == 5990528763808513177
560 self.assertEqual([self.gen.random().hex() for i in range(4)],
561 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
562 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
563
564 self.gen.seed('rachel', version=1) # hash('rachel') == -9091735575445484789
565 self.assertEqual([self.gen.random().hex() for i in range(4)],
566 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
567 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
568
569 self.gen.seed('', version=1) # hash('') == 0
570 self.assertEqual([self.gen.random().hex() for i in range(4)],
571 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
572 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
573
Oren Milmand780b2d2017-09-28 10:50:01 +0300574 def test_bug_31478(self):
575 # There shouldn't be an assertion failure in _random.Random.seed() in
576 # case the argument has a bad __abs__() method.
577 class BadInt(int):
578 def __abs__(self):
579 return None
580 try:
581 self.gen.seed(BadInt())
582 except TypeError:
583 pass
584
Raymond Hettinger132a7d72017-09-17 09:04:30 -0700585 def test_bug_31482(self):
586 # Verify that version 1 seeds are unaffected by hash randomization
587 # when the seeds are expressed as bytes rather than strings.
588 # The hash(b) values listed are the Python2.7 hash() values
589 # which were used for seeding.
590
591 self.gen.seed(b'nofar', version=1) # hash('nofar') == 5990528763808513177
592 self.assertEqual([self.gen.random().hex() for i in range(4)],
593 ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
594 '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
595
596 self.gen.seed(b'rachel', version=1) # hash('rachel') == -9091735575445484789
597 self.assertEqual([self.gen.random().hex() for i in range(4)],
598 ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
599 '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
600
601 self.gen.seed(b'', version=1) # hash('') == 0
602 self.assertEqual([self.gen.random().hex() for i in range(4)],
603 ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
604 '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
605
606 b = b'\x00\x20\x40\x60\x80\xA0\xC0\xE0\xF0'
607 self.gen.seed(b, version=1) # hash(b) == 5015594239749365497
608 self.assertEqual([self.gen.random().hex() for i in range(4)],
609 ['0x1.52c2fde444d23p-1', '0x1.875174f0daea4p-2',
610 '0x1.9e9b2c50e5cd2p-1', '0x1.fa57768bd321cp-2'])
611
Raymond Hettinger58335872004-07-09 14:26:18 +0000612 def test_setstate_first_arg(self):
613 self.assertRaises(ValueError, self.gen.setstate, (1, None, None))
614
615 def test_setstate_middle_arg(self):
bladebryan9616a822017-04-21 23:10:46 -0700616 start_state = self.gen.getstate()
Raymond Hettinger58335872004-07-09 14:26:18 +0000617 # Wrong type, s/b tuple
618 self.assertRaises(TypeError, self.gen.setstate, (2, None, None))
619 # Wrong length, s/b 625
620 self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None))
621 # Wrong type, s/b tuple of 625 ints
622 self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None))
623 # Last element s/b an int also
624 self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None))
Serhiy Storchaka178f0b62015-07-24 09:02:53 +0300625 # Last element s/b between 0 and 624
626 with self.assertRaises((ValueError, OverflowError)):
627 self.gen.setstate((2, (1,)*624+(625,), None))
628 with self.assertRaises((ValueError, OverflowError)):
629 self.gen.setstate((2, (1,)*624+(-1,), None))
bladebryan9616a822017-04-21 23:10:46 -0700630 # Failed calls to setstate() should not have changed the state.
631 bits100 = self.gen.getrandbits(100)
632 self.gen.setstate(start_state)
633 self.assertEqual(self.gen.getrandbits(100), bits100)
Raymond Hettinger58335872004-07-09 14:26:18 +0000634
R David Murraye3e1c172013-04-02 12:47:23 -0400635 # Little trick to make "tuple(x % (2**32) for x in internalstate)"
636 # raise ValueError. I cannot think of a simple way to achieve this, so
637 # I am opting for using a generator as the middle argument of setstate
638 # which attempts to cast a NaN to integer.
639 state_values = self.gen.getstate()[1]
640 state_values = list(state_values)
641 state_values[-1] = float('nan')
642 state = (int(x) for x in state_values)
643 self.assertRaises(TypeError, self.gen.setstate, (2, state, None))
644
Raymond Hettinger40f62172002-12-29 23:03:38 +0000645 def test_referenceImplementation(self):
646 # Compare the python implementation with results from the original
647 # code. Create 2000 53-bit precision random floats. Compare only
648 # the last ten entries to show that the independent implementations
649 # are tracking. Here is the main() function needed to create the
650 # list of expected random numbers:
651 # void main(void){
652 # int i;
653 # unsigned long init[4]={61731, 24903, 614, 42143}, length=4;
654 # init_by_array(init, length);
655 # for (i=0; i<2000; i++) {
656 # printf("%.15f ", genrand_res53());
657 # if (i%5==4) printf("\n");
658 # }
659 # }
660 expected = [0.45839803073713259,
661 0.86057815201978782,
662 0.92848331726782152,
663 0.35932681119782461,
664 0.081823493762449573,
665 0.14332226470169329,
666 0.084297823823520024,
667 0.53814864671831453,
668 0.089215024911993401,
669 0.78486196105372907]
670
Guido van Rossume2a383d2007-01-15 16:59:06 +0000671 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000672 actual = self.randomlist(2000)[-10:]
673 for a, e in zip(actual, expected):
674 self.assertAlmostEqual(a,e,places=14)
675
676 def test_strong_reference_implementation(self):
677 # Like test_referenceImplementation, but checks for exact bit-level
678 # equality. This should pass on any box where C double contains
679 # at least 53 bits of precision (the underlying algorithm suffers
680 # no rounding errors -- all results are exact).
681 from math import ldexp
682
Guido van Rossume2a383d2007-01-15 16:59:06 +0000683 expected = [0x0eab3258d2231f,
684 0x1b89db315277a5,
685 0x1db622a5518016,
686 0x0b7f9af0d575bf,
687 0x029e4c4db82240,
688 0x04961892f5d673,
689 0x02b291598e4589,
690 0x11388382c15694,
691 0x02dad977c9e1fe,
692 0x191d96d4d334c6]
693 self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
Raymond Hettinger40f62172002-12-29 23:03:38 +0000694 actual = self.randomlist(2000)[-10:]
695 for a, e in zip(actual, expected):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000696 self.assertEqual(int(ldexp(a, 53)), e)
Raymond Hettinger40f62172002-12-29 23:03:38 +0000697
698 def test_long_seed(self):
699 # This is most interesting to run in debug mode, just to make sure
700 # nothing blows up. Under the covers, a dynamically resized array
701 # is allocated, consuming space proportional to the number of bits
702 # in the seed. Unfortunately, that's a quadratic-time algorithm,
703 # so don't make this horribly big.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000704 seed = (1 << (10000 * 8)) - 1 # about 10K bytes
Raymond Hettinger40f62172002-12-29 23:03:38 +0000705 self.gen.seed(seed)
706
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000707 def test_53_bits_per_float(self):
708 # This should pass whenever a C double has 53 bit precision.
709 span = 2 ** 53
710 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000711 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000712 cum |= int(self.gen.random() * span)
713 self.assertEqual(cum, span-1)
714
715 def test_bigrand(self):
716 # The randrange routine should build-up the required number of bits
717 # in stages so that all bit positions are active.
718 span = 2 ** 500
719 cum = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000720 for i in range(100):
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000721 r = self.gen.randrange(span)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000722 self.assertTrue(0 <= r < span)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000723 cum |= r
724 self.assertEqual(cum, span-1)
725
726 def test_bigrand_ranges(self):
727 for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
Zachary Warea6edea52013-11-26 14:50:10 -0600728 start = self.gen.randrange(2 ** (i-2))
729 stop = self.gen.randrange(2 ** i)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000730 if stop <= start:
Zachary Warea6edea52013-11-26 14:50:10 -0600731 continue
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000732 self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000733
734 def test_rangelimits(self):
735 for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
Raymond Hettingera690a992003-11-16 16:17:49 +0000736 self.assertEqual(set(range(start,stop)),
Guido van Rossum805365e2007-05-07 22:24:25 +0000737 set([self.gen.randrange(start,stop) for i in range(100)]))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000738
Antoine Pitrou75a33782020-04-17 19:32:14 +0200739 def test_getrandbits(self):
740 super().test_getrandbits()
741
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000742 # Verify cross-platform repeatability
743 self.gen.seed(1234567)
744 self.assertEqual(self.gen.getrandbits(100),
Guido van Rossume2a383d2007-01-15 16:59:06 +0000745 97904845777343510404718956115)
Raymond Hettinger58335872004-07-09 14:26:18 +0000746
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200747 def test_randrange_uses_getrandbits(self):
748 # Verify use of getrandbits by randrange
749 # Use same seed as in the cross-platform repeatability test
Antoine Pitrou75a33782020-04-17 19:32:14 +0200750 # in test_getrandbits above.
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200751 self.gen.seed(1234567)
752 # If randrange uses getrandbits, it should pick getrandbits(100)
753 # when called with a 100-bits stop argument.
754 self.assertEqual(self.gen.randrange(2**99),
755 97904845777343510404718956115)
756
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000757 def test_randbelow_logic(self, _log=log, int=int):
758 # check bitcount transition points: 2**i and 2**(i+1)-1
759 # show that: k = int(1.001 + _log(n, 2))
760 # is equal to or one greater than the number of bits in n
Guido van Rossum805365e2007-05-07 22:24:25 +0000761 for i in range(1, 1000):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000762 n = 1 << i # check an exact power of two
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000763 numbits = i+1
764 k = int(1.00001 + _log(n, 2))
765 self.assertEqual(k, numbits)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000766 self.assertEqual(n, 2**(k-1))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000767
768 n += n - 1 # check 1 below the next power of two
769 k = int(1.00001 + _log(n, 2))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000770 self.assertIn(k, [numbits, numbits+1])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000771 self.assertTrue(2**k > n > 2**(k-2))
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000772
773 n -= n >> 15 # check a little farther below the next power of two
774 k = int(1.00001 + _log(n, 2))
775 self.assertEqual(k, numbits) # note the stronger assertion
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000776 self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
Raymond Hettinger2f726e92003-10-05 09:09:15 +0000777
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200778 def test_randbelow_without_getrandbits(self):
R David Murraye3e1c172013-04-02 12:47:23 -0400779 # Random._randbelow() can only use random() when the built-in one
780 # has been overridden but no new getrandbits() method was supplied.
R David Murraye3e1c172013-04-02 12:47:23 -0400781 maxsize = 1<<random.BPF
782 with warnings.catch_warnings():
783 warnings.simplefilter("ignore", UserWarning)
784 # Population range too large (n >= maxsize)
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200785 self.gen._randbelow_without_getrandbits(
786 maxsize+1, maxsize=maxsize
787 )
788 self.gen._randbelow_without_getrandbits(5640, maxsize=maxsize)
Raymond Hettinger4168f1e2020-05-01 10:34:19 -0700789 # issue 33203: test that _randbelow returns zero on
Wolfgang Maier091e95e2018-04-05 17:19:44 +0200790 # n == 0 also in its getrandbits-independent branch.
Raymond Hettinger4168f1e2020-05-01 10:34:19 -0700791 x = self.gen._randbelow_without_getrandbits(0, maxsize=maxsize)
792 self.assertEqual(x, 0)
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200793
R David Murraye3e1c172013-04-02 12:47:23 -0400794 # This might be going too far to test a single line, but because of our
795 # noble aim of achieving 100% test coverage we need to write a case in
796 # which the following line in Random._randbelow() gets executed:
797 #
798 # rem = maxsize % n
799 # limit = (maxsize - rem) / maxsize
800 # r = random()
801 # while r >= limit:
802 # r = random() # <== *This line* <==<
803 #
804 # Therefore, to guarantee that the while loop is executed at least
805 # once, we need to mock random() so that it returns a number greater
806 # than 'limit' the first time it gets called.
807
808 n = 42
809 epsilon = 0.01
810 limit = (maxsize - (maxsize % n)) / maxsize
Wolfgang Maierba3a87a2018-04-17 17:16:17 +0200811 with unittest.mock.patch.object(random.Random, 'random') as random_mock:
812 random_mock.side_effect = [limit + epsilon, limit - epsilon]
813 self.gen._randbelow_without_getrandbits(n, maxsize=maxsize)
814 self.assertEqual(random_mock.call_count, 2)
R David Murraye3e1c172013-04-02 12:47:23 -0400815
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000816 def test_randrange_bug_1590891(self):
817 start = 1000000000000
818 stop = -100000000000000000000
819 step = -200
820 x = self.gen.randrange(start, stop, step)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000821 self.assertTrue(stop < x <= start)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000822 self.assertEqual((x+stop)%step, 0)
823
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700824 def test_choices_algorithms(self):
Raymond Hettinger24e42392016-11-13 00:42:56 -0500825 # The various ways of specifying weights should produce the same results
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700826 choices = self.gen.choices
Raymond Hettinger6023d332016-11-21 15:32:08 -0800827 n = 104729
Raymond Hettinger30d00e52016-10-29 16:55:36 -0700828
829 self.gen.seed(8675309)
830 a = self.gen.choices(range(n), k=10000)
831
832 self.gen.seed(8675309)
833 b = self.gen.choices(range(n), [1]*n, k=10000)
834 self.assertEqual(a, b)
835
836 self.gen.seed(8675309)
837 c = self.gen.choices(range(n), cum_weights=range(1, n+1), k=10000)
838 self.assertEqual(a, c)
839
penguindustin96466302019-05-06 14:57:17 -0400840 # American Roulette
Raymond Hettinger77d574d2016-10-29 17:42:36 -0700841 population = ['Red', 'Black', 'Green']
842 weights = [18, 18, 2]
843 cum_weights = [18, 36, 38]
844 expanded_population = ['Red'] * 18 + ['Black'] * 18 + ['Green'] * 2
845
846 self.gen.seed(9035768)
847 a = self.gen.choices(expanded_population, k=10000)
848
849 self.gen.seed(9035768)
850 b = self.gen.choices(population, weights, k=10000)
851 self.assertEqual(a, b)
852
853 self.gen.seed(9035768)
854 c = self.gen.choices(population, cum_weights=cum_weights, k=10000)
855 self.assertEqual(a, c)
856
Victor Stinner9f5fe792020-04-17 19:05:35 +0200857 def test_randbytes(self):
858 super().test_randbytes()
859
860 # Mersenne Twister randbytes() is deterministic
861 # and does not depend on the endian and bitness.
862 seed = 8675309
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300863 expected = b'3\xa8\xf9f\xf4\xa4\xd06\x19\x8f\x9f\x82\x02oe\xf0'
Victor Stinner9f5fe792020-04-17 19:05:35 +0200864
865 self.gen.seed(seed)
866 self.assertEqual(self.gen.randbytes(16), expected)
867
868 # randbytes(0) must not consume any entropy
869 self.gen.seed(seed)
870 self.assertEqual(self.gen.randbytes(0), b'')
871 self.assertEqual(self.gen.randbytes(16), expected)
872
873 # Four randbytes(4) calls give the same output than randbytes(16)
874 self.gen.seed(seed)
875 self.assertEqual(b''.join([self.gen.randbytes(4) for _ in range(4)]),
876 expected)
877
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300878 # Each randbytes(1), randbytes(2) or randbytes(3) call consumes
879 # 4 bytes of entropy
Victor Stinner9f5fe792020-04-17 19:05:35 +0200880 self.gen.seed(seed)
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300881 expected1 = expected[3::4]
882 self.assertEqual(b''.join(self.gen.randbytes(1) for _ in range(4)),
883 expected1)
884
885 self.gen.seed(seed)
886 expected2 = b''.join(expected[i + 2: i + 4]
Victor Stinner9f5fe792020-04-17 19:05:35 +0200887 for i in range(0, len(expected), 4))
888 self.assertEqual(b''.join(self.gen.randbytes(2) for _ in range(4)),
889 expected2)
890
891 self.gen.seed(seed)
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300892 expected3 = b''.join(expected[i + 1: i + 4]
Victor Stinner9f5fe792020-04-17 19:05:35 +0200893 for i in range(0, len(expected), 4))
894 self.assertEqual(b''.join(self.gen.randbytes(3) for _ in range(4)),
895 expected3)
896
Serhiy Storchaka223221b2020-04-17 23:51:28 +0300897 def test_randbytes_getrandbits(self):
898 # There is a simple relation between randbytes() and getrandbits()
899 seed = 2849427419
900 gen2 = random.Random()
901 self.gen.seed(seed)
902 gen2.seed(seed)
903 for n in range(9):
904 self.assertEqual(self.gen.randbytes(n),
905 gen2.getrandbits(n * 8).to_bytes(n, 'little'))
906
Victor Stinner9f5fe792020-04-17 19:05:35 +0200907
Raymond Hettinger2d0c2562009-02-19 09:53:18 +0000908def gamma(z, sqrt2pi=(2.0*pi)**0.5):
909 # Reflection to right half of complex plane
910 if z < 0.5:
911 return pi / sin(pi*z) / gamma(1.0-z)
912 # Lanczos approximation with g=7
913 az = z + (7.0 - 0.5)
914 return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
915 0.9999999999995183,
916 676.5203681218835 / z,
917 -1259.139216722289 / (z+1.0),
918 771.3234287757674 / (z+2.0),
919 -176.6150291498386 / (z+3.0),
920 12.50734324009056 / (z+4.0),
921 -0.1385710331296526 / (z+5.0),
922 0.9934937113930748e-05 / (z+6.0),
923 0.1659470187408462e-06 / (z+7.0),
924 ])
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000925
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000926class TestDistributions(unittest.TestCase):
927 def test_zeroinputs(self):
928 # Verify that distributions can handle a series of zero inputs'
929 g = random.Random()
Guido van Rossum805365e2007-05-07 22:24:25 +0000930 x = [g.random() for i in range(50)] + [0.0]*5
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000931 g.random = x[:].pop; g.uniform(1,10)
932 g.random = x[:].pop; g.paretovariate(1.0)
933 g.random = x[:].pop; g.expovariate(1.0)
934 g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200935 g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000936 g.random = x[:].pop; g.normalvariate(0.0, 1.0)
937 g.random = x[:].pop; g.gauss(0.0, 1.0)
938 g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
939 g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
940 g.random = x[:].pop; g.gammavariate(0.01, 1.0)
941 g.random = x[:].pop; g.gammavariate(1.0, 1.0)
942 g.random = x[:].pop; g.gammavariate(200.0, 1.0)
943 g.random = x[:].pop; g.betavariate(3.0, 3.0)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000944 g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
Raymond Hettinger15ec3732003-01-05 01:08:34 +0000945
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000946 def test_avg_std(self):
947 # Use integration to test distribution average and standard deviation.
948 # Only works for distributions which do not consume variates in pairs
949 g = random.Random()
950 N = 5000
Guido van Rossum805365e2007-05-07 22:24:25 +0000951 x = [i/float(N) for i in range(1,N)]
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000952 for variate, args, mu, sigmasqrd in [
953 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
Christian Heimesfe337bf2008-03-23 21:54:12 +0000954 (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 +0000955 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200956 (g.vonmisesvariate, (1.23, 0), pi, pi**2/3),
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000957 (g.paretovariate, (5.0,), 5.0/(5.0-1),
958 5.0/((5.0-1)**2*(5.0-2))),
959 (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0),
960 gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
961 g.random = x[:].pop
962 y = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000963 for i in range(len(x)):
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000964 try:
965 y.append(variate(*args))
966 except IndexError:
967 pass
968 s1 = s2 = 0
969 for e in y:
970 s1 += e
971 s2 += (e - mu) ** 2
972 N = len(y)
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200973 self.assertAlmostEqual(s1/N, mu, places=2,
974 msg='%s%r' % (variate.__name__, args))
975 self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2,
976 msg='%s%r' % (variate.__name__, args))
977
978 def test_constant(self):
979 g = random.Random()
980 N = 100
981 for variate, args, expected in [
982 (g.uniform, (10.0, 10.0), 10.0),
983 (g.triangular, (10.0, 10.0), 10.0),
Raymond Hettinger978c6ab2014-05-25 17:25:27 -0700984 (g.triangular, (10.0, 10.0, 10.0), 10.0),
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +0200985 (g.expovariate, (float('inf'),), 0.0),
986 (g.vonmisesvariate, (3.0, float('inf')), 3.0),
987 (g.gauss, (10.0, 0.0), 10.0),
988 (g.lognormvariate, (0.0, 0.0), 1.0),
989 (g.lognormvariate, (-float('inf'), 0.0), 0.0),
990 (g.normalvariate, (10.0, 0.0), 10.0),
991 (g.paretovariate, (float('inf'),), 1.0),
992 (g.weibullvariate, (10.0, float('inf')), 10.0),
993 (g.weibullvariate, (0.0, 10.0), 0.0),
994 ]:
995 for i in range(N):
996 self.assertEqual(variate(*args), expected)
Raymond Hettinger3dd990c2003-01-05 09:20:06 +0000997
Mark Dickinsonbe5f9192013-02-10 14:16:10 +0000998 def test_von_mises_range(self):
999 # Issue 17149: von mises variates were not consistently in the
1000 # range [0, 2*PI].
1001 g = random.Random()
1002 N = 100
1003 for mu in 0.0, 0.1, 3.1, 6.2:
1004 for kappa in 0.0, 2.3, 500.0:
1005 for _ in range(N):
1006 sample = g.vonmisesvariate(mu, kappa)
1007 self.assertTrue(
1008 0 <= sample <= random.TWOPI,
1009 msg=("vonmisesvariate({}, {}) produced a result {} out"
1010 " of range [0, 2*pi]").format(mu, kappa, sample))
1011
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +02001012 def test_von_mises_large_kappa(self):
1013 # Issue #17141: vonmisesvariate() was hang for large kappas
1014 random.vonmisesvariate(0, 1e15)
1015 random.vonmisesvariate(0, 1e100)
1016
R David Murraye3e1c172013-04-02 12:47:23 -04001017 def test_gammavariate_errors(self):
1018 # Both alpha and beta must be > 0.0
1019 self.assertRaises(ValueError, random.gammavariate, -1, 3)
1020 self.assertRaises(ValueError, random.gammavariate, 0, 2)
1021 self.assertRaises(ValueError, random.gammavariate, 2, 0)
1022 self.assertRaises(ValueError, random.gammavariate, 1, -3)
1023
leodema63d15222018-12-24 07:54:25 +01001024 # There are three different possibilities in the current implementation
1025 # of random.gammavariate(), depending on the value of 'alpha'. What we
1026 # are going to do here is to fix the values returned by random() to
1027 # generate test cases that provide 100% line coverage of the method.
R David Murraye3e1c172013-04-02 12:47:23 -04001028 @unittest.mock.patch('random.Random.random')
leodema63d15222018-12-24 07:54:25 +01001029 def test_gammavariate_alpha_greater_one(self, random_mock):
R David Murraye3e1c172013-04-02 12:47:23 -04001030
leodema63d15222018-12-24 07:54:25 +01001031 # #1: alpha > 1.0.
1032 # We want the first random number to be outside the
R David Murraye3e1c172013-04-02 12:47:23 -04001033 # [1e-7, .9999999] range, so that the continue statement executes
1034 # once. The values of u1 and u2 will be 0.5 and 0.3, respectively.
1035 random_mock.side_effect = [1e-8, 0.5, 0.3]
1036 returned_value = random.gammavariate(1.1, 2.3)
1037 self.assertAlmostEqual(returned_value, 2.53)
1038
leodema63d15222018-12-24 07:54:25 +01001039 @unittest.mock.patch('random.Random.random')
1040 def test_gammavariate_alpha_equal_one(self, random_mock):
R David Murraye3e1c172013-04-02 12:47:23 -04001041
leodema63d15222018-12-24 07:54:25 +01001042 # #2.a: alpha == 1.
1043 # The execution body of the while loop executes once.
1044 # Then random.random() returns 0.45,
1045 # which causes while to stop looping and the algorithm to terminate.
1046 random_mock.side_effect = [0.45]
1047 returned_value = random.gammavariate(1.0, 3.14)
1048 self.assertAlmostEqual(returned_value, 1.877208182372648)
1049
1050 @unittest.mock.patch('random.Random.random')
1051 def test_gammavariate_alpha_equal_one_equals_expovariate(self, random_mock):
1052
1053 # #2.b: alpha == 1.
1054 # It must be equivalent of calling expovariate(1.0 / beta).
1055 beta = 3.14
1056 random_mock.side_effect = [1e-8, 1e-8]
1057 gammavariate_returned_value = random.gammavariate(1.0, beta)
1058 expovariate_returned_value = random.expovariate(1.0 / beta)
1059 self.assertAlmostEqual(gammavariate_returned_value, expovariate_returned_value)
1060
1061 @unittest.mock.patch('random.Random.random')
1062 def test_gammavariate_alpha_between_zero_and_one(self, random_mock):
1063
1064 # #3: 0 < alpha < 1.
1065 # This is the most complex region of code to cover,
R David Murraye3e1c172013-04-02 12:47:23 -04001066 # as there are multiple if-else statements. Let's take a look at the
1067 # source code, and determine the values that we need accordingly:
1068 #
1069 # while 1:
1070 # u = random()
1071 # b = (_e + alpha)/_e
1072 # p = b*u
1073 # if p <= 1.0: # <=== (A)
1074 # x = p ** (1.0/alpha)
1075 # else: # <=== (B)
1076 # x = -_log((b-p)/alpha)
1077 # u1 = random()
1078 # if p > 1.0: # <=== (C)
1079 # if u1 <= x ** (alpha - 1.0): # <=== (D)
1080 # break
1081 # elif u1 <= _exp(-x): # <=== (E)
1082 # break
1083 # return x * beta
1084 #
1085 # First, we want (A) to be True. For that we need that:
1086 # b*random() <= 1.0
1087 # r1 = random() <= 1.0 / b
1088 #
1089 # We now get to the second if-else branch, and here, since p <= 1.0,
1090 # (C) is False and we take the elif branch, (E). For it to be True,
1091 # so that the break is executed, we need that:
1092 # r2 = random() <= _exp(-x)
1093 # r2 <= _exp(-(p ** (1.0/alpha)))
1094 # r2 <= _exp(-((b*r1) ** (1.0/alpha)))
1095
1096 _e = random._e
1097 _exp = random._exp
1098 _log = random._log
1099 alpha = 0.35
1100 beta = 1.45
1101 b = (_e + alpha)/_e
1102 epsilon = 0.01
1103
1104 r1 = 0.8859296441566 # 1.0 / b
1105 r2 = 0.3678794411714 # _exp(-((b*r1) ** (1.0/alpha)))
1106
1107 # These four "random" values result in the following trace:
1108 # (A) True, (E) False --> [next iteration of while]
1109 # (A) True, (E) True --> [while loop breaks]
1110 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
1111 returned_value = random.gammavariate(alpha, beta)
1112 self.assertAlmostEqual(returned_value, 1.4499999999997544)
1113
1114 # Let's now make (A) be False. If this is the case, when we get to the
1115 # second if-else 'p' is greater than 1, so (C) evaluates to True. We
1116 # now encounter a second if statement, (D), which in order to execute
1117 # must satisfy the following condition:
1118 # r2 <= x ** (alpha - 1.0)
1119 # r2 <= (-_log((b-p)/alpha)) ** (alpha - 1.0)
1120 # r2 <= (-_log((b-(b*r1))/alpha)) ** (alpha - 1.0)
1121 r1 = 0.8959296441566 # (1.0 / b) + epsilon -- so that (A) is False
1122 r2 = 0.9445400408898141
1123
1124 # And these four values result in the following trace:
1125 # (B) and (C) True, (D) False --> [next iteration of while]
1126 # (B) and (C) True, (D) True [while loop breaks]
1127 random_mock.side_effect = [r1, r2 + epsilon, r1, r2]
1128 returned_value = random.gammavariate(alpha, beta)
1129 self.assertAlmostEqual(returned_value, 1.5830349561760781)
1130
1131 @unittest.mock.patch('random.Random.gammavariate')
1132 def test_betavariate_return_zero(self, gammavariate_mock):
1133 # betavariate() returns zero when the Gamma distribution
1134 # that it uses internally returns this same value.
1135 gammavariate_mock.return_value = 0.0
1136 self.assertEqual(0.0, random.betavariate(2.71828, 3.14159))
Serhiy Storchaka6c22b1d2013-02-10 19:28:56 +02001137
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001138
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001139class TestRandomSubclassing(unittest.TestCase):
1140 def test_random_subclass_with_kwargs(self):
1141 # SF bug #1486663 -- this used to erroneously raise a TypeError
1142 class Subclass(random.Random):
1143 def __init__(self, newarg=None):
1144 random.Random.__init__(self)
1145 Subclass(newarg=1)
1146
1147 def test_subclasses_overriding_methods(self):
1148 # Subclasses with an overridden random, but only the original
1149 # getrandbits method should not rely on getrandbits in for randrange,
1150 # but should use a getrandbits-independent implementation instead.
1151
1152 # subclass providing its own random **and** getrandbits methods
1153 # like random.SystemRandom does => keep relying on getrandbits for
1154 # randrange
1155 class SubClass1(random.Random):
1156 def random(self):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001157 called.add('SubClass1.random')
1158 return random.Random.random(self)
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001159
1160 def getrandbits(self, n):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001161 called.add('SubClass1.getrandbits')
1162 return random.Random.getrandbits(self, n)
1163 called = set()
1164 SubClass1().randrange(42)
1165 self.assertEqual(called, {'SubClass1.getrandbits'})
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001166
1167 # subclass providing only random => can only use random for randrange
1168 class SubClass2(random.Random):
1169 def random(self):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001170 called.add('SubClass2.random')
1171 return random.Random.random(self)
1172 called = set()
1173 SubClass2().randrange(42)
1174 self.assertEqual(called, {'SubClass2.random'})
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001175
1176 # subclass defining getrandbits to complement its inherited random
1177 # => can now rely on getrandbits for randrange again
1178 class SubClass3(SubClass2):
1179 def getrandbits(self, n):
Serhiy Storchakaec1622d2018-05-08 15:45:15 +03001180 called.add('SubClass3.getrandbits')
1181 return random.Random.getrandbits(self, n)
1182 called = set()
1183 SubClass3().randrange(42)
1184 self.assertEqual(called, {'SubClass3.getrandbits'})
1185
1186 # subclass providing only random and inherited getrandbits
1187 # => random takes precedence
1188 class SubClass4(SubClass3):
1189 def random(self):
1190 called.add('SubClass4.random')
1191 return random.Random.random(self)
1192 called = set()
1193 SubClass4().randrange(42)
1194 self.assertEqual(called, {'SubClass4.random'})
1195
1196 # Following subclasses don't define random or getrandbits directly,
1197 # but inherit them from classes which are not subclasses of Random
1198 class Mixin1:
1199 def random(self):
1200 called.add('Mixin1.random')
1201 return random.Random.random(self)
1202 class Mixin2:
1203 def getrandbits(self, n):
1204 called.add('Mixin2.getrandbits')
1205 return random.Random.getrandbits(self, n)
1206
1207 class SubClass5(Mixin1, random.Random):
1208 pass
1209 called = set()
1210 SubClass5().randrange(42)
1211 self.assertEqual(called, {'Mixin1.random'})
1212
1213 class SubClass6(Mixin2, random.Random):
1214 pass
1215 called = set()
1216 SubClass6().randrange(42)
1217 self.assertEqual(called, {'Mixin2.getrandbits'})
1218
1219 class SubClass7(Mixin1, Mixin2, random.Random):
1220 pass
1221 called = set()
1222 SubClass7().randrange(42)
1223 self.assertEqual(called, {'Mixin1.random'})
1224
1225 class SubClass8(Mixin2, Mixin1, random.Random):
1226 pass
1227 called = set()
1228 SubClass8().randrange(42)
1229 self.assertEqual(called, {'Mixin2.getrandbits'})
1230
Wolfgang Maierba3a87a2018-04-17 17:16:17 +02001231
Raymond Hettinger40f62172002-12-29 23:03:38 +00001232class TestModule(unittest.TestCase):
1233 def testMagicConstants(self):
1234 self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141)
1235 self.assertAlmostEqual(random.TWOPI, 6.28318530718)
1236 self.assertAlmostEqual(random.LOG4, 1.38629436111989)
1237 self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627)
1238
1239 def test__all__(self):
1240 # tests validity but not completeness of the __all__ list
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001241 self.assertTrue(set(random.__all__) <= set(dir(random)))
Raymond Hettinger40f62172002-12-29 23:03:38 +00001242
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001243 @unittest.skipUnless(hasattr(os, "fork"), "fork() required")
1244 def test_after_fork(self):
1245 # Test the global Random instance gets reseeded in child
1246 r, w = os.pipe()
Victor Stinnerda5e9302017-08-09 17:59:05 +02001247 pid = os.fork()
1248 if pid == 0:
1249 # child process
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001250 try:
1251 val = random.getrandbits(128)
1252 with open(w, "w") as f:
1253 f.write(str(val))
1254 finally:
1255 os._exit(0)
1256 else:
Victor Stinnerda5e9302017-08-09 17:59:05 +02001257 # parent process
Antoine Pitrou346cbd32017-05-27 17:50:54 +02001258 os.close(w)
1259 val = random.getrandbits(128)
1260 with open(r, "r") as f:
1261 child_val = eval(f.read())
1262 self.assertNotEqual(val, child_val)
1263
Victor Stinner278c1e12020-03-31 20:08:12 +02001264 support.wait_process(pid, exitcode=0)
Victor Stinnerda5e9302017-08-09 17:59:05 +02001265
Thomas Woutersb2137042007-02-01 18:02:27 +00001266
Raymond Hettinger40f62172002-12-29 23:03:38 +00001267if __name__ == "__main__":
Ezio Melotti3e4a98b2013-04-19 05:45:27 +03001268 unittest.main()