Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 1 | import unittest |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 2 | import unittest.mock |
Tim Peters | 46c04e1 | 2002-05-05 20:40:00 +0000 | [diff] [blame] | 3 | import random |
Antoine Pitrou | 346cbd3 | 2017-05-27 17:50:54 +0200 | [diff] [blame] | 4 | import os |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 5 | import time |
Raymond Hettinger | 5f078ff | 2003-06-24 20:29:04 +0000 | [diff] [blame] | 6 | import pickle |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 7 | import warnings |
Dong-hee Na | 6989af0 | 2020-06-21 18:44:58 +0900 | [diff] [blame] | 8 | import test.support |
| 9 | |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 10 | from functools import partial |
Victor Stinner | bd1b49a | 2016-10-19 10:11:37 +0200 | [diff] [blame] | 11 | from math import log, exp, pi, fsum, sin, factorial |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 12 | from test import support |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 13 | from fractions import Fraction |
masklinn | 1e27b57 | 2020-12-19 05:33:36 +0100 | [diff] [blame] | 14 | from collections import abc, Counter |
csabella | f111fd2 | 2017-05-11 11:19:35 -0400 | [diff] [blame] | 15 | |
Ezio Melotti | 3e4a98b | 2013-04-19 05:45:27 +0300 | [diff] [blame] | 16 | class TestBasicOps: |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 17 | # Superclass with tests common to all generators. |
| 18 | # Subclasses must arrange for self.gen to retrieve the Random instance |
| 19 | # to be tested. |
Tim Peters | 46c04e1 | 2002-05-05 20:40:00 +0000 | [diff] [blame] | 20 | |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 21 | def randomlist(self, n): |
| 22 | """Helper function to make a list of random numbers""" |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 23 | return [self.gen.random() for i in range(n)] |
Tim Peters | 46c04e1 | 2002-05-05 20:40:00 +0000 | [diff] [blame] | 24 | |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 25 | def test_autoseed(self): |
| 26 | self.gen.seed() |
| 27 | state1 = self.gen.getstate() |
Raymond Hettinger | 3081d59 | 2003-08-09 18:30:57 +0000 | [diff] [blame] | 28 | time.sleep(0.1) |
Mike | 53f7a7c | 2017-12-14 14:04:53 +0300 | [diff] [blame] | 29 | self.gen.seed() # different seeds at different times |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 30 | state2 = self.gen.getstate() |
| 31 | self.assertNotEqual(state1, state2) |
Tim Peters | 46c04e1 | 2002-05-05 20:40:00 +0000 | [diff] [blame] | 32 | |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 33 | 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 Dickinson | 95aeae0 | 2012-06-24 11:05:30 +0100 | [diff] [blame] | 42 | # Seed value with a negative hash. |
| 43 | class MySeed(object): |
| 44 | def __hash__(self): |
| 45 | return -1729 |
Xtreak | a06d683 | 2019-09-12 09:13:20 +0100 | [diff] [blame] | 46 | for arg in [None, 0, 1, -1, 10**20, -(10**20), |
Victor Stinner | 00d7cd8 | 2020-03-10 15:15:14 +0100 | [diff] [blame] | 47 | False, True, 3.14, 'a']: |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 48 | self.gen.seed(arg) |
Xtreak | a06d683 | 2019-09-12 09:13:20 +0100 | [diff] [blame] | 49 | |
| 50 | for arg in [1+2j, tuple('abc'), MySeed()]: |
| 51 | with self.assertWarns(DeprecationWarning): |
| 52 | self.gen.seed(arg) |
| 53 | |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 54 | for arg in [list(range(3)), dict(one=1)]: |
Xtreak | a06d683 | 2019-09-12 09:13:20 +0100 | [diff] [blame] | 55 | with self.assertWarns(DeprecationWarning): |
| 56 | self.assertRaises(TypeError, self.gen.seed, arg) |
Raymond Hettinger | f763a72 | 2010-09-07 00:38:15 +0000 | [diff] [blame] | 57 | self.assertRaises(TypeError, self.gen.seed, 1, 2, 3, 4) |
Raymond Hettinger | 5833587 | 2004-07-09 14:26:18 +0000 | [diff] [blame] | 58 | self.assertRaises(TypeError, type(self.gen), []) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 59 | |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 60 | @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 |
csabella | f111fd2 | 2017-05-11 11:19:35 -0400 | [diff] [blame] | 63 | # randomness source is not found. To test this on machines where it |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 64 | # 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 Pitrou | 5e39433 | 2012-11-04 02:10:33 +0100 | [diff] [blame] | 70 | 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 Pitrou | 5e39433 | 2012-11-04 02:10:33 +0100 | [diff] [blame] | 85 | # 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) |
csabella | f111fd2 | 2017-05-11 11:19:35 -0400 | [diff] [blame] | 101 | 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 Hettinger | 190fac9 | 2020-05-02 16:45:32 -0700 | [diff] [blame] | 108 | with self.assertWarns(DeprecationWarning): |
| 109 | shuffle(seq, mock_random) |
csabella | f111fd2 | 2017-05-11 11:19:35 -0400 | [diff] [blame] | 110 | mock_random.assert_called_with() |
Antoine Pitrou | 5e39433 | 2012-11-04 02:10:33 +0100 | [diff] [blame] | 111 | |
Raymond Hettinger | dc4872e | 2010-09-07 10:06:56 +0000 | [diff] [blame] | 112 | 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 Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 119 | 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 Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 123 | population = range(N) |
| 124 | for k in range(N+1): |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 125 | s = self.gen.sample(population, k) |
| 126 | self.assertEqual(len(s), k) |
Raymond Hettinger | a690a99 | 2003-11-16 16:17:49 +0000 | [diff] [blame] | 127 | uniq = set(s) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 128 | self.assertEqual(len(uniq), k) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 129 | self.assertTrue(uniq <= set(population)) |
Raymond Hettinger | 8ec7881 | 2003-01-04 05:55:11 +0000 | [diff] [blame] | 130 | self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0 |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 131 | # Exception raised if size of sample exceeds that of population |
| 132 | self.assertRaises(ValueError, self.gen.sample, population, N+1) |
Raymond Hettinger | bf87126 | 2016-11-21 14:34:33 -0800 | [diff] [blame] | 133 | self.assertRaises(ValueError, self.gen.sample, [], -1) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 134 | |
Raymond Hettinger | 7b0cf76 | 2003-01-17 17:23:23 +0000 | [diff] [blame] | 135 | 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 Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 141 | for k in range(n): |
Raymond Hettinger | ffdb8bb | 2004-09-27 15:29:05 +0000 | [diff] [blame] | 142 | expected = factorial(n) // factorial(n-k) |
Raymond Hettinger | 7b0cf76 | 2003-01-17 17:23:23 +0000 | [diff] [blame] | 143 | perms = {} |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 144 | for i in range(trials): |
Raymond Hettinger | 7b0cf76 | 2003-01-17 17:23:23 +0000 | [diff] [blame] | 145 | perms[tuple(self.gen.sample(pop, k))] = None |
| 146 | if len(perms) == expected: |
| 147 | break |
| 148 | else: |
| 149 | self.fail() |
| 150 | |
Raymond Hettinger | 66d09f1 | 2003-09-06 04:25:54 +0000 | [diff] [blame] | 151 | def test_sample_inputs(self): |
| 152 | # SF bug #801342 -- population can be any iterable defining __len__() |
Raymond Hettinger | 66d09f1 | 2003-09-06 04:25:54 +0000 | [diff] [blame] | 153 | self.gen.sample(range(20), 2) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 154 | self.gen.sample(range(20), 2) |
Raymond Hettinger | 66d09f1 | 2003-09-06 04:25:54 +0000 | [diff] [blame] | 155 | self.gen.sample(str('abcdefghijklmnopqrst'), 2) |
| 156 | self.gen.sample(tuple('abcdefghijklmnopqrst'), 2) |
| 157 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 158 | def test_sample_on_dicts(self): |
Raymond Hettinger | 1acde19 | 2008-01-14 01:00:53 +0000 | [diff] [blame] | 159 | self.assertRaises(TypeError, self.gen.sample, dict.fromkeys('abcdef'), 2) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 160 | |
Raymond Hettinger | 4fe0020 | 2020-04-19 00:36:42 -0700 | [diff] [blame] | 161 | 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 | |
masklinn | 1e27b57 | 2020-12-19 05:33:36 +0100 | [diff] [blame] | 166 | def test_sample_on_seqsets(self): |
| 167 | class SeqSet(abc.Sequence, abc.Set): |
| 168 | def __init__(self, items): |
| 169 | self._items = items |
| 170 | |
| 171 | def __len__(self): |
| 172 | return len(self._items) |
| 173 | |
| 174 | def __getitem__(self, index): |
| 175 | return self._items[index] |
| 176 | |
| 177 | population = SeqSet([2, 4, 1, 3]) |
| 178 | with warnings.catch_warnings(): |
| 179 | warnings.simplefilter("error", DeprecationWarning) |
| 180 | self.gen.sample(population, k=2) |
| 181 | |
Raymond Hettinger | 81a5fc3 | 2020-05-08 07:53:15 -0700 | [diff] [blame] | 182 | def test_sample_with_counts(self): |
| 183 | sample = self.gen.sample |
| 184 | |
| 185 | # General case |
| 186 | colors = ['red', 'green', 'blue', 'orange', 'black', 'brown', 'amber'] |
| 187 | counts = [500, 200, 20, 10, 5, 0, 1 ] |
| 188 | k = 700 |
| 189 | summary = Counter(sample(colors, counts=counts, k=k)) |
| 190 | self.assertEqual(sum(summary.values()), k) |
| 191 | for color, weight in zip(colors, counts): |
| 192 | self.assertLessEqual(summary[color], weight) |
| 193 | self.assertNotIn('brown', summary) |
| 194 | |
| 195 | # Case that exhausts the population |
| 196 | k = sum(counts) |
| 197 | summary = Counter(sample(colors, counts=counts, k=k)) |
| 198 | self.assertEqual(sum(summary.values()), k) |
| 199 | for color, weight in zip(colors, counts): |
| 200 | self.assertLessEqual(summary[color], weight) |
| 201 | self.assertNotIn('brown', summary) |
| 202 | |
| 203 | # Case with population size of 1 |
| 204 | summary = Counter(sample(['x'], counts=[10], k=8)) |
| 205 | self.assertEqual(summary, Counter(x=8)) |
| 206 | |
| 207 | # Case with all counts equal. |
| 208 | nc = len(colors) |
| 209 | summary = Counter(sample(colors, counts=[10]*nc, k=10*nc)) |
| 210 | self.assertEqual(summary, Counter(10*colors)) |
| 211 | |
| 212 | # Test error handling |
| 213 | with self.assertRaises(TypeError): |
| 214 | sample(['red', 'green', 'blue'], counts=10, k=10) # counts not iterable |
| 215 | with self.assertRaises(ValueError): |
| 216 | sample(['red', 'green', 'blue'], counts=[-3, -7, -8], k=2) # counts are negative |
| 217 | with self.assertRaises(ValueError): |
| 218 | sample(['red', 'green', 'blue'], counts=[0, 0, 0], k=2) # counts are zero |
| 219 | with self.assertRaises(ValueError): |
| 220 | sample(['red', 'green'], counts=[10, 10], k=21) # population too small |
| 221 | with self.assertRaises(ValueError): |
| 222 | sample(['red', 'green', 'blue'], counts=[1, 2], k=2) # too few counts |
| 223 | with self.assertRaises(ValueError): |
| 224 | sample(['red', 'green', 'blue'], counts=[1, 2, 3, 4], k=2) # too many counts |
| 225 | |
| 226 | def test_sample_counts_equivalence(self): |
| 227 | # Test the documented strong equivalence to a sample with repeated elements. |
| 228 | # We run this test on random.Random() which makes deterministic selections |
| 229 | # for a given seed value. |
| 230 | sample = random.sample |
| 231 | seed = random.seed |
| 232 | |
| 233 | colors = ['red', 'green', 'blue', 'orange', 'black', 'amber'] |
| 234 | counts = [500, 200, 20, 10, 5, 1 ] |
| 235 | k = 700 |
| 236 | seed(8675309) |
| 237 | s1 = sample(colors, counts=counts, k=k) |
| 238 | seed(8675309) |
| 239 | expanded = [color for (color, count) in zip(colors, counts) for i in range(count)] |
| 240 | self.assertEqual(len(expanded), sum(counts)) |
| 241 | s2 = sample(expanded, k=k) |
| 242 | self.assertEqual(s1, s2) |
| 243 | |
| 244 | pop = 'abcdefghi' |
| 245 | counts = [10, 9, 8, 7, 6, 5, 4, 3, 2] |
| 246 | seed(8675309) |
| 247 | s1 = ''.join(sample(pop, counts=counts, k=30)) |
| 248 | expanded = ''.join([letter for (letter, count) in zip(pop, counts) for i in range(count)]) |
| 249 | seed(8675309) |
| 250 | s2 = ''.join(sample(expanded, k=30)) |
| 251 | self.assertEqual(s1, s2) |
| 252 | |
Raymond Hettinger | 28aa4a0 | 2016-09-07 00:08:44 -0700 | [diff] [blame] | 253 | def test_choices(self): |
| 254 | choices = self.gen.choices |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 255 | data = ['red', 'green', 'blue', 'yellow'] |
| 256 | str_data = 'abcd' |
| 257 | range_data = range(4) |
| 258 | set_data = set(range(4)) |
| 259 | |
| 260 | # basic functionality |
| 261 | for sample in [ |
Raymond Hettinger | 9016f28 | 2016-09-26 21:45:57 -0700 | [diff] [blame] | 262 | choices(data, k=5), |
| 263 | choices(data, range(4), k=5), |
Raymond Hettinger | 28aa4a0 | 2016-09-07 00:08:44 -0700 | [diff] [blame] | 264 | choices(k=5, population=data, weights=range(4)), |
| 265 | choices(k=5, population=data, cum_weights=range(4)), |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 266 | ]: |
| 267 | self.assertEqual(len(sample), 5) |
| 268 | self.assertEqual(type(sample), list) |
| 269 | self.assertTrue(set(sample) <= set(data)) |
| 270 | |
| 271 | # test argument handling |
Raymond Hettinger | 28aa4a0 | 2016-09-07 00:08:44 -0700 | [diff] [blame] | 272 | with self.assertRaises(TypeError): # missing arguments |
| 273 | choices(2) |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 274 | |
Raymond Hettinger | 9016f28 | 2016-09-26 21:45:57 -0700 | [diff] [blame] | 275 | self.assertEqual(choices(data, k=0), []) # k == 0 |
| 276 | self.assertEqual(choices(data, k=-1), []) # negative k behaves like ``[0] * -1`` |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 277 | with self.assertRaises(TypeError): |
Raymond Hettinger | 9016f28 | 2016-09-26 21:45:57 -0700 | [diff] [blame] | 278 | choices(data, k=2.5) # k is a float |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 279 | |
Raymond Hettinger | 9016f28 | 2016-09-26 21:45:57 -0700 | [diff] [blame] | 280 | self.assertTrue(set(choices(str_data, k=5)) <= set(str_data)) # population is a string sequence |
| 281 | self.assertTrue(set(choices(range_data, k=5)) <= set(range_data)) # population is a range |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 282 | with self.assertRaises(TypeError): |
Raymond Hettinger | 9016f28 | 2016-09-26 21:45:57 -0700 | [diff] [blame] | 283 | choices(set_data, k=2) # population is not a sequence |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 284 | |
Raymond Hettinger | 9016f28 | 2016-09-26 21:45:57 -0700 | [diff] [blame] | 285 | self.assertTrue(set(choices(data, None, k=5)) <= set(data)) # weights is None |
| 286 | self.assertTrue(set(choices(data, weights=None, k=5)) <= set(data)) |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 287 | with self.assertRaises(ValueError): |
Raymond Hettinger | 9016f28 | 2016-09-26 21:45:57 -0700 | [diff] [blame] | 288 | choices(data, [1,2], k=5) # len(weights) != len(population) |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 289 | with self.assertRaises(TypeError): |
Raymond Hettinger | 9016f28 | 2016-09-26 21:45:57 -0700 | [diff] [blame] | 290 | choices(data, 10, k=5) # non-iterable weights |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 291 | with self.assertRaises(TypeError): |
Raymond Hettinger | 9016f28 | 2016-09-26 21:45:57 -0700 | [diff] [blame] | 292 | choices(data, [None]*4, k=5) # non-numeric weights |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 293 | for weights in [ |
| 294 | [15, 10, 25, 30], # integer weights |
| 295 | [15.1, 10.2, 25.2, 30.3], # float weights |
| 296 | [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional weights |
| 297 | [True, False, True, False] # booleans (include / exclude) |
| 298 | ]: |
Raymond Hettinger | 9016f28 | 2016-09-26 21:45:57 -0700 | [diff] [blame] | 299 | self.assertTrue(set(choices(data, weights, k=5)) <= set(data)) |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 300 | |
| 301 | with self.assertRaises(ValueError): |
Raymond Hettinger | 9016f28 | 2016-09-26 21:45:57 -0700 | [diff] [blame] | 302 | choices(data, cum_weights=[1,2], k=5) # len(weights) != len(population) |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 303 | with self.assertRaises(TypeError): |
Raymond Hettinger | 9016f28 | 2016-09-26 21:45:57 -0700 | [diff] [blame] | 304 | choices(data, cum_weights=10, k=5) # non-iterable cum_weights |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 305 | with self.assertRaises(TypeError): |
Raymond Hettinger | 9016f28 | 2016-09-26 21:45:57 -0700 | [diff] [blame] | 306 | choices(data, cum_weights=[None]*4, k=5) # non-numeric cum_weights |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 307 | with self.assertRaises(TypeError): |
Raymond Hettinger | 9016f28 | 2016-09-26 21:45:57 -0700 | [diff] [blame] | 308 | choices(data, range(4), cum_weights=range(4), k=5) # both weights and cum_weights |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 309 | for weights in [ |
| 310 | [15, 10, 25, 30], # integer cum_weights |
| 311 | [15.1, 10.2, 25.2, 30.3], # float cum_weights |
| 312 | [Fraction(1, 3), Fraction(2, 6), Fraction(3, 6), Fraction(4, 6)], # fractional cum_weights |
| 313 | ]: |
Raymond Hettinger | 9016f28 | 2016-09-26 21:45:57 -0700 | [diff] [blame] | 314 | self.assertTrue(set(choices(data, cum_weights=weights, k=5)) <= set(data)) |
Raymond Hettinger | e8f1e00 | 2016-09-06 17:15:29 -0700 | [diff] [blame] | 315 | |
Raymond Hettinger | 7b16652 | 2016-10-14 01:19:38 -0400 | [diff] [blame] | 316 | # Test weight focused on a single element of the population |
| 317 | self.assertEqual(choices('abcd', [1, 0, 0, 0]), ['a']) |
| 318 | self.assertEqual(choices('abcd', [0, 1, 0, 0]), ['b']) |
| 319 | self.assertEqual(choices('abcd', [0, 0, 1, 0]), ['c']) |
| 320 | self.assertEqual(choices('abcd', [0, 0, 0, 1]), ['d']) |
| 321 | |
| 322 | # Test consistency with random.choice() for empty population |
| 323 | with self.assertRaises(IndexError): |
| 324 | choices([], k=1) |
| 325 | with self.assertRaises(IndexError): |
| 326 | choices([], weights=[], k=1) |
| 327 | with self.assertRaises(IndexError): |
| 328 | choices([], cum_weights=[], k=5) |
| 329 | |
Raymond Hettinger | ddf7171 | 2018-06-27 01:08:31 -0700 | [diff] [blame] | 330 | def test_choices_subnormal(self): |
Min ho Kim | 96e12d5 | 2019-07-22 06:12:33 +1000 | [diff] [blame] | 331 | # Subnormal weights would occasionally trigger an IndexError |
Raymond Hettinger | ddf7171 | 2018-06-27 01:08:31 -0700 | [diff] [blame] | 332 | # in choices() when the value returned by random() was large |
| 333 | # enough to make `random() * total` round up to the total. |
| 334 | # See https://bugs.python.org/msg275594 for more detail. |
| 335 | choices = self.gen.choices |
| 336 | choices(population=[1, 2], weights=[1e-323, 1e-323], k=5000) |
| 337 | |
Raymond Hettinger | 041d8b4 | 2019-11-23 02:22:13 -0800 | [diff] [blame] | 338 | def test_choices_with_all_zero_weights(self): |
| 339 | # See issue #38881 |
| 340 | with self.assertRaises(ValueError): |
| 341 | self.gen.choices('AB', [0.0, 0.0]) |
| 342 | |
Ram Rachum | b0dfc75 | 2020-09-29 04:32:10 +0300 | [diff] [blame] | 343 | def test_choices_negative_total(self): |
| 344 | with self.assertRaises(ValueError): |
| 345 | self.gen.choices('ABC', [3, -5, 1]) |
| 346 | |
| 347 | def test_choices_infinite_total(self): |
| 348 | with self.assertRaises(ValueError): |
| 349 | self.gen.choices('A', [float('inf')]) |
| 350 | with self.assertRaises(ValueError): |
| 351 | self.gen.choices('AB', [0.0, float('inf')]) |
| 352 | with self.assertRaises(ValueError): |
| 353 | self.gen.choices('AB', [-float('inf'), 123]) |
| 354 | with self.assertRaises(ValueError): |
| 355 | self.gen.choices('AB', [0.0, float('nan')]) |
| 356 | with self.assertRaises(ValueError): |
| 357 | self.gen.choices('AB', [float('-inf'), float('inf')]) |
| 358 | |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 359 | def test_gauss(self): |
| 360 | # Ensure that the seed() method initializes all the hidden state. In |
| 361 | # particular, through 2.2.1 it failed to reset a piece of state used |
| 362 | # by (and only by) the .gauss() method. |
| 363 | |
| 364 | for seed in 1, 12, 123, 1234, 12345, 123456, 654321: |
| 365 | self.gen.seed(seed) |
| 366 | x1 = self.gen.random() |
| 367 | y1 = self.gen.gauss(0, 1) |
| 368 | |
| 369 | self.gen.seed(seed) |
| 370 | x2 = self.gen.random() |
| 371 | y2 = self.gen.gauss(0, 1) |
| 372 | |
| 373 | self.assertEqual(x1, x2) |
| 374 | self.assertEqual(y1, y2) |
| 375 | |
Antoine Pitrou | 75a3378 | 2020-04-17 19:32:14 +0200 | [diff] [blame] | 376 | def test_getrandbits(self): |
| 377 | # Verify ranges |
| 378 | for k in range(1, 1000): |
| 379 | self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k) |
| 380 | self.assertEqual(self.gen.getrandbits(0), 0) |
| 381 | |
| 382 | # Verify all bits active |
| 383 | getbits = self.gen.getrandbits |
| 384 | for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]: |
| 385 | all_bits = 2**span-1 |
| 386 | cum = 0 |
| 387 | cpl_cum = 0 |
| 388 | for i in range(100): |
| 389 | v = getbits(span) |
| 390 | cum |= v |
| 391 | cpl_cum |= all_bits ^ v |
| 392 | self.assertEqual(cum, all_bits) |
| 393 | self.assertEqual(cpl_cum, all_bits) |
| 394 | |
| 395 | # Verify argument checking |
| 396 | self.assertRaises(TypeError, self.gen.getrandbits) |
| 397 | self.assertRaises(TypeError, self.gen.getrandbits, 1, 2) |
| 398 | self.assertRaises(ValueError, self.gen.getrandbits, -1) |
| 399 | self.assertRaises(TypeError, self.gen.getrandbits, 10.1) |
| 400 | |
Raymond Hettinger | 5f078ff | 2003-06-24 20:29:04 +0000 | [diff] [blame] | 401 | def test_pickling(self): |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 402 | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 403 | state = pickle.dumps(self.gen, proto) |
| 404 | origseq = [self.gen.random() for i in range(10)] |
| 405 | newgen = pickle.loads(state) |
| 406 | restoredseq = [newgen.random() for i in range(10)] |
| 407 | self.assertEqual(origseq, restoredseq) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 408 | |
Dong-hee Na | 6989af0 | 2020-06-21 18:44:58 +0900 | [diff] [blame] | 409 | @test.support.cpython_only |
| 410 | def test_bug_41052(self): |
| 411 | # _random.Random should not be allowed to serialization |
| 412 | import _random |
| 413 | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 414 | r = _random.Random() |
| 415 | self.assertRaises(TypeError, pickle.dumps, r, proto) |
| 416 | |
AMIR | b8fde8b | 2020-12-22 03:15:50 +0330 | [diff] [blame] | 417 | @test.support.cpython_only |
| 418 | def test_bug_42008(self): |
| 419 | # _random.Random should call seed with first element of arg tuple |
| 420 | import _random |
| 421 | r1 = _random.Random() |
| 422 | r1.seed(8675309) |
| 423 | r2 = _random.Random(8675309) |
| 424 | self.assertEqual(r1.random(), r2.random()) |
| 425 | |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 426 | def test_bug_1727780(self): |
| 427 | # verify that version-2-pickles can be loaded |
| 428 | # fine, whether they are created on 32-bit or 64-bit |
| 429 | # platforms, and that version-3-pickles load fine. |
| 430 | files = [("randv2_32.pck", 780), |
| 431 | ("randv2_64.pck", 866), |
| 432 | ("randv3.pck", 343)] |
| 433 | for file, value in files: |
Serhiy Storchaka | 5b10b98 | 2019-03-05 10:06:26 +0200 | [diff] [blame] | 434 | with open(support.findfile(file),"rb") as f: |
| 435 | r = pickle.load(f) |
Raymond Hettinger | 0515661 | 2010-09-07 04:44:52 +0000 | [diff] [blame] | 436 | self.assertEqual(int(r.random()*1000), value) |
| 437 | |
| 438 | def test_bug_9025(self): |
| 439 | # Had problem with an uneven distribution in int(n*random()) |
| 440 | # Verify the fix by checking that distributions fall within expectations. |
| 441 | n = 100000 |
| 442 | randrange = self.gen.randrange |
| 443 | k = sum(randrange(6755399441055744) % 3 == 2 for i in range(n)) |
| 444 | self.assertTrue(0.30 < k/n < .37, (k/n)) |
Christian Heimes | cbf3b5c | 2007-12-03 21:02:03 +0000 | [diff] [blame] | 445 | |
Victor Stinner | 9f5fe79 | 2020-04-17 19:05:35 +0200 | [diff] [blame] | 446 | def test_randbytes(self): |
| 447 | # Verify ranges |
| 448 | for n in range(1, 10): |
| 449 | data = self.gen.randbytes(n) |
| 450 | self.assertEqual(type(data), bytes) |
| 451 | self.assertEqual(len(data), n) |
| 452 | |
| 453 | self.assertEqual(self.gen.randbytes(0), b'') |
| 454 | |
| 455 | # Verify argument checking |
| 456 | self.assertRaises(TypeError, self.gen.randbytes) |
| 457 | self.assertRaises(TypeError, self.gen.randbytes, 1, 2) |
| 458 | self.assertRaises(ValueError, self.gen.randbytes, -1) |
| 459 | self.assertRaises(TypeError, self.gen.randbytes, 1.0) |
| 460 | |
| 461 | |
Ezio Melotti | 3e4a98b | 2013-04-19 05:45:27 +0300 | [diff] [blame] | 462 | try: |
| 463 | random.SystemRandom().random() |
| 464 | except NotImplementedError: |
| 465 | SystemRandom_available = False |
| 466 | else: |
| 467 | SystemRandom_available = True |
| 468 | |
| 469 | @unittest.skipUnless(SystemRandom_available, "random.SystemRandom not available") |
| 470 | class SystemRandom_TestBasicOps(TestBasicOps, unittest.TestCase): |
Raymond Hettinger | 23f1241 | 2004-09-13 22:23:21 +0000 | [diff] [blame] | 471 | gen = random.SystemRandom() |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 472 | |
| 473 | def test_autoseed(self): |
| 474 | # Doesn't need to do anything except not fail |
| 475 | self.gen.seed() |
| 476 | |
| 477 | def test_saverestore(self): |
| 478 | self.assertRaises(NotImplementedError, self.gen.getstate) |
| 479 | self.assertRaises(NotImplementedError, self.gen.setstate, None) |
| 480 | |
| 481 | def test_seedargs(self): |
| 482 | # Doesn't need to do anything except not fail |
| 483 | self.gen.seed(100) |
| 484 | |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 485 | def test_gauss(self): |
| 486 | self.gen.gauss_next = None |
| 487 | self.gen.seed(100) |
| 488 | self.assertEqual(self.gen.gauss_next, None) |
| 489 | |
| 490 | def test_pickling(self): |
Serhiy Storchaka | bad1257 | 2014-12-15 14:03:42 +0200 | [diff] [blame] | 491 | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 492 | self.assertRaises(NotImplementedError, pickle.dumps, self.gen, proto) |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 493 | |
| 494 | def test_53_bits_per_float(self): |
| 495 | # This should pass whenever a C double has 53 bit precision. |
| 496 | span = 2 ** 53 |
| 497 | cum = 0 |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 498 | for i in range(100): |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 499 | cum |= int(self.gen.random() * span) |
| 500 | self.assertEqual(cum, span-1) |
| 501 | |
| 502 | def test_bigrand(self): |
| 503 | # The randrange routine should build-up the required number of bits |
| 504 | # in stages so that all bit positions are active. |
| 505 | span = 2 ** 500 |
| 506 | cum = 0 |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 507 | for i in range(100): |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 508 | r = self.gen.randrange(span) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 509 | self.assertTrue(0 <= r < span) |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 510 | cum |= r |
| 511 | self.assertEqual(cum, span-1) |
| 512 | |
| 513 | def test_bigrand_ranges(self): |
| 514 | for i in [40,80, 160, 200, 211, 250, 375, 512, 550]: |
Zachary Ware | a6edea5 | 2013-11-26 14:50:10 -0600 | [diff] [blame] | 515 | start = self.gen.randrange(2 ** (i-2)) |
| 516 | stop = self.gen.randrange(2 ** i) |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 517 | if stop <= start: |
Zachary Ware | a6edea5 | 2013-11-26 14:50:10 -0600 | [diff] [blame] | 518 | continue |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 519 | self.assertTrue(start <= self.gen.randrange(start, stop) < stop) |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 520 | |
| 521 | def test_rangelimits(self): |
| 522 | for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]: |
| 523 | self.assertEqual(set(range(start,stop)), |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 524 | set([self.gen.randrange(start,stop) for i in range(100)])) |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 525 | |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 526 | def test_randrange_nonunit_step(self): |
| 527 | rint = self.gen.randrange(0, 10, 2) |
| 528 | self.assertIn(rint, (0, 2, 4, 6, 8)) |
| 529 | rint = self.gen.randrange(0, 2, 2) |
| 530 | self.assertEqual(rint, 0) |
| 531 | |
| 532 | def test_randrange_errors(self): |
| 533 | raises = partial(self.assertRaises, ValueError, self.gen.randrange) |
| 534 | # Empty range |
| 535 | raises(3, 3) |
| 536 | raises(-721) |
| 537 | raises(0, 100, -12) |
| 538 | # Non-integer start/stop |
| 539 | raises(3.14159) |
| 540 | raises(0, 2.71828) |
| 541 | # Zero and non-integer step |
| 542 | raises(0, 42, 0) |
| 543 | raises(0, 42, 3.14159) |
| 544 | |
Raymond Hettinger | a9621bb | 2020-12-28 11:10:34 -0800 | [diff] [blame^] | 545 | def test_randrange_argument_handling(self): |
| 546 | randrange = self.gen.randrange |
| 547 | with self.assertWarns(DeprecationWarning): |
| 548 | randrange(10.0, 20, 2) |
| 549 | with self.assertWarns(DeprecationWarning): |
| 550 | randrange(10, 20.0, 2) |
| 551 | with self.assertWarns(DeprecationWarning): |
| 552 | randrange(10, 20, 1.0) |
| 553 | with self.assertWarns(DeprecationWarning): |
| 554 | randrange(10, 20, 2.0) |
| 555 | with self.assertWarns(DeprecationWarning): |
| 556 | with self.assertRaises(ValueError): |
| 557 | randrange(10.5) |
| 558 | with self.assertWarns(DeprecationWarning): |
| 559 | with self.assertRaises(ValueError): |
| 560 | randrange(10, 20.5) |
| 561 | with self.assertWarns(DeprecationWarning): |
| 562 | with self.assertRaises(ValueError): |
| 563 | randrange(10, 20, 1.5) |
| 564 | |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 565 | def test_randbelow_logic(self, _log=log, int=int): |
| 566 | # check bitcount transition points: 2**i and 2**(i+1)-1 |
| 567 | # show that: k = int(1.001 + _log(n, 2)) |
| 568 | # is equal to or one greater than the number of bits in n |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 569 | for i in range(1, 1000): |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 570 | n = 1 << i # check an exact power of two |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 571 | numbits = i+1 |
| 572 | k = int(1.00001 + _log(n, 2)) |
| 573 | self.assertEqual(k, numbits) |
Guido van Rossum | e61fd5b | 2007-07-11 12:20:59 +0000 | [diff] [blame] | 574 | self.assertEqual(n, 2**(k-1)) |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 575 | |
| 576 | n += n - 1 # check 1 below the next power of two |
| 577 | k = int(1.00001 + _log(n, 2)) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 578 | self.assertIn(k, [numbits, numbits+1]) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 579 | self.assertTrue(2**k > n > 2**(k-2)) |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 580 | |
| 581 | n -= n >> 15 # check a little farther below the next power of two |
| 582 | k = int(1.00001 + _log(n, 2)) |
| 583 | self.assertEqual(k, numbits) # note the stronger assertion |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 584 | self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion |
Raymond Hettinger | 356a459 | 2004-08-30 06:14:31 +0000 | [diff] [blame] | 585 | |
| 586 | |
Ezio Melotti | 3e4a98b | 2013-04-19 05:45:27 +0300 | [diff] [blame] | 587 | class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase): |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 588 | gen = random.Random() |
| 589 | |
Raymond Hettinger | f763a72 | 2010-09-07 00:38:15 +0000 | [diff] [blame] | 590 | def test_guaranteed_stable(self): |
| 591 | # These sequences are guaranteed to stay the same across versions of python |
| 592 | self.gen.seed(3456147, version=1) |
| 593 | self.assertEqual([self.gen.random().hex() for i in range(4)], |
| 594 | ['0x1.ac362300d90d2p-1', '0x1.9d16f74365005p-1', |
| 595 | '0x1.1ebb4352e4c4dp-1', '0x1.1a7422abf9c11p-1']) |
Raymond Hettinger | f763a72 | 2010-09-07 00:38:15 +0000 | [diff] [blame] | 596 | self.gen.seed("the quick brown fox", version=2) |
| 597 | self.assertEqual([self.gen.random().hex() for i in range(4)], |
Raymond Hettinger | 3fcf002 | 2010-12-08 01:13:53 +0000 | [diff] [blame] | 598 | ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4', |
| 599 | '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1']) |
Raymond Hettinger | f763a72 | 2010-09-07 00:38:15 +0000 | [diff] [blame] | 600 | |
Raymond Hettinger | c7bab7c | 2016-08-31 15:01:08 -0700 | [diff] [blame] | 601 | def test_bug_27706(self): |
| 602 | # Verify that version 1 seeds are unaffected by hash randomization |
| 603 | |
| 604 | self.gen.seed('nofar', version=1) # hash('nofar') == 5990528763808513177 |
| 605 | self.assertEqual([self.gen.random().hex() for i in range(4)], |
| 606 | ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5', |
| 607 | '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6']) |
| 608 | |
| 609 | self.gen.seed('rachel', version=1) # hash('rachel') == -9091735575445484789 |
| 610 | self.assertEqual([self.gen.random().hex() for i in range(4)], |
| 611 | ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3', |
| 612 | '0x1.3052b9c072678p-2', '0x1.578f332106574p-3']) |
| 613 | |
| 614 | self.gen.seed('', version=1) # hash('') == 0 |
| 615 | self.assertEqual([self.gen.random().hex() for i in range(4)], |
| 616 | ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1', |
| 617 | '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2']) |
| 618 | |
Oren Milman | d780b2d | 2017-09-28 10:50:01 +0300 | [diff] [blame] | 619 | def test_bug_31478(self): |
| 620 | # There shouldn't be an assertion failure in _random.Random.seed() in |
| 621 | # case the argument has a bad __abs__() method. |
| 622 | class BadInt(int): |
| 623 | def __abs__(self): |
| 624 | return None |
| 625 | try: |
| 626 | self.gen.seed(BadInt()) |
| 627 | except TypeError: |
| 628 | pass |
| 629 | |
Raymond Hettinger | 132a7d7 | 2017-09-17 09:04:30 -0700 | [diff] [blame] | 630 | def test_bug_31482(self): |
| 631 | # Verify that version 1 seeds are unaffected by hash randomization |
| 632 | # when the seeds are expressed as bytes rather than strings. |
| 633 | # The hash(b) values listed are the Python2.7 hash() values |
| 634 | # which were used for seeding. |
| 635 | |
| 636 | self.gen.seed(b'nofar', version=1) # hash('nofar') == 5990528763808513177 |
| 637 | self.assertEqual([self.gen.random().hex() for i in range(4)], |
| 638 | ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5', |
| 639 | '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6']) |
| 640 | |
| 641 | self.gen.seed(b'rachel', version=1) # hash('rachel') == -9091735575445484789 |
| 642 | self.assertEqual([self.gen.random().hex() for i in range(4)], |
| 643 | ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3', |
| 644 | '0x1.3052b9c072678p-2', '0x1.578f332106574p-3']) |
| 645 | |
| 646 | self.gen.seed(b'', version=1) # hash('') == 0 |
| 647 | self.assertEqual([self.gen.random().hex() for i in range(4)], |
| 648 | ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1', |
| 649 | '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2']) |
| 650 | |
| 651 | b = b'\x00\x20\x40\x60\x80\xA0\xC0\xE0\xF0' |
| 652 | self.gen.seed(b, version=1) # hash(b) == 5015594239749365497 |
| 653 | self.assertEqual([self.gen.random().hex() for i in range(4)], |
| 654 | ['0x1.52c2fde444d23p-1', '0x1.875174f0daea4p-2', |
| 655 | '0x1.9e9b2c50e5cd2p-1', '0x1.fa57768bd321cp-2']) |
| 656 | |
Raymond Hettinger | 5833587 | 2004-07-09 14:26:18 +0000 | [diff] [blame] | 657 | def test_setstate_first_arg(self): |
| 658 | self.assertRaises(ValueError, self.gen.setstate, (1, None, None)) |
| 659 | |
| 660 | def test_setstate_middle_arg(self): |
bladebryan | 9616a82 | 2017-04-21 23:10:46 -0700 | [diff] [blame] | 661 | start_state = self.gen.getstate() |
Raymond Hettinger | 5833587 | 2004-07-09 14:26:18 +0000 | [diff] [blame] | 662 | # Wrong type, s/b tuple |
| 663 | self.assertRaises(TypeError, self.gen.setstate, (2, None, None)) |
| 664 | # Wrong length, s/b 625 |
| 665 | self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None)) |
| 666 | # Wrong type, s/b tuple of 625 ints |
| 667 | self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None)) |
| 668 | # Last element s/b an int also |
| 669 | self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None)) |
Serhiy Storchaka | 178f0b6 | 2015-07-24 09:02:53 +0300 | [diff] [blame] | 670 | # Last element s/b between 0 and 624 |
| 671 | with self.assertRaises((ValueError, OverflowError)): |
| 672 | self.gen.setstate((2, (1,)*624+(625,), None)) |
| 673 | with self.assertRaises((ValueError, OverflowError)): |
| 674 | self.gen.setstate((2, (1,)*624+(-1,), None)) |
bladebryan | 9616a82 | 2017-04-21 23:10:46 -0700 | [diff] [blame] | 675 | # Failed calls to setstate() should not have changed the state. |
| 676 | bits100 = self.gen.getrandbits(100) |
| 677 | self.gen.setstate(start_state) |
| 678 | self.assertEqual(self.gen.getrandbits(100), bits100) |
Raymond Hettinger | 5833587 | 2004-07-09 14:26:18 +0000 | [diff] [blame] | 679 | |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 680 | # Little trick to make "tuple(x % (2**32) for x in internalstate)" |
| 681 | # raise ValueError. I cannot think of a simple way to achieve this, so |
| 682 | # I am opting for using a generator as the middle argument of setstate |
| 683 | # which attempts to cast a NaN to integer. |
| 684 | state_values = self.gen.getstate()[1] |
| 685 | state_values = list(state_values) |
| 686 | state_values[-1] = float('nan') |
| 687 | state = (int(x) for x in state_values) |
| 688 | self.assertRaises(TypeError, self.gen.setstate, (2, state, None)) |
| 689 | |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 690 | def test_referenceImplementation(self): |
| 691 | # Compare the python implementation with results from the original |
| 692 | # code. Create 2000 53-bit precision random floats. Compare only |
| 693 | # the last ten entries to show that the independent implementations |
| 694 | # are tracking. Here is the main() function needed to create the |
| 695 | # list of expected random numbers: |
| 696 | # void main(void){ |
| 697 | # int i; |
| 698 | # unsigned long init[4]={61731, 24903, 614, 42143}, length=4; |
| 699 | # init_by_array(init, length); |
| 700 | # for (i=0; i<2000; i++) { |
| 701 | # printf("%.15f ", genrand_res53()); |
| 702 | # if (i%5==4) printf("\n"); |
| 703 | # } |
| 704 | # } |
| 705 | expected = [0.45839803073713259, |
| 706 | 0.86057815201978782, |
| 707 | 0.92848331726782152, |
| 708 | 0.35932681119782461, |
| 709 | 0.081823493762449573, |
| 710 | 0.14332226470169329, |
| 711 | 0.084297823823520024, |
| 712 | 0.53814864671831453, |
| 713 | 0.089215024911993401, |
| 714 | 0.78486196105372907] |
| 715 | |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 716 | self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96)) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 717 | actual = self.randomlist(2000)[-10:] |
| 718 | for a, e in zip(actual, expected): |
| 719 | self.assertAlmostEqual(a,e,places=14) |
| 720 | |
| 721 | def test_strong_reference_implementation(self): |
| 722 | # Like test_referenceImplementation, but checks for exact bit-level |
| 723 | # equality. This should pass on any box where C double contains |
| 724 | # at least 53 bits of precision (the underlying algorithm suffers |
| 725 | # no rounding errors -- all results are exact). |
| 726 | from math import ldexp |
| 727 | |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 728 | expected = [0x0eab3258d2231f, |
| 729 | 0x1b89db315277a5, |
| 730 | 0x1db622a5518016, |
| 731 | 0x0b7f9af0d575bf, |
| 732 | 0x029e4c4db82240, |
| 733 | 0x04961892f5d673, |
| 734 | 0x02b291598e4589, |
| 735 | 0x11388382c15694, |
| 736 | 0x02dad977c9e1fe, |
| 737 | 0x191d96d4d334c6] |
| 738 | self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96)) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 739 | actual = self.randomlist(2000)[-10:] |
| 740 | for a, e in zip(actual, expected): |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 741 | self.assertEqual(int(ldexp(a, 53)), e) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 742 | |
| 743 | def test_long_seed(self): |
| 744 | # This is most interesting to run in debug mode, just to make sure |
| 745 | # nothing blows up. Under the covers, a dynamically resized array |
| 746 | # is allocated, consuming space proportional to the number of bits |
| 747 | # in the seed. Unfortunately, that's a quadratic-time algorithm, |
| 748 | # so don't make this horribly big. |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 749 | seed = (1 << (10000 * 8)) - 1 # about 10K bytes |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 750 | self.gen.seed(seed) |
| 751 | |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 752 | def test_53_bits_per_float(self): |
| 753 | # This should pass whenever a C double has 53 bit precision. |
| 754 | span = 2 ** 53 |
| 755 | cum = 0 |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 756 | for i in range(100): |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 757 | cum |= int(self.gen.random() * span) |
| 758 | self.assertEqual(cum, span-1) |
| 759 | |
| 760 | def test_bigrand(self): |
| 761 | # The randrange routine should build-up the required number of bits |
| 762 | # in stages so that all bit positions are active. |
| 763 | span = 2 ** 500 |
| 764 | cum = 0 |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 765 | for i in range(100): |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 766 | r = self.gen.randrange(span) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 767 | self.assertTrue(0 <= r < span) |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 768 | cum |= r |
| 769 | self.assertEqual(cum, span-1) |
| 770 | |
| 771 | def test_bigrand_ranges(self): |
| 772 | for i in [40,80, 160, 200, 211, 250, 375, 512, 550]: |
Zachary Ware | a6edea5 | 2013-11-26 14:50:10 -0600 | [diff] [blame] | 773 | start = self.gen.randrange(2 ** (i-2)) |
| 774 | stop = self.gen.randrange(2 ** i) |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 775 | if stop <= start: |
Zachary Ware | a6edea5 | 2013-11-26 14:50:10 -0600 | [diff] [blame] | 776 | continue |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 777 | self.assertTrue(start <= self.gen.randrange(start, stop) < stop) |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 778 | |
| 779 | def test_rangelimits(self): |
| 780 | for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]: |
Raymond Hettinger | a690a99 | 2003-11-16 16:17:49 +0000 | [diff] [blame] | 781 | self.assertEqual(set(range(start,stop)), |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 782 | set([self.gen.randrange(start,stop) for i in range(100)])) |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 783 | |
Antoine Pitrou | 75a3378 | 2020-04-17 19:32:14 +0200 | [diff] [blame] | 784 | def test_getrandbits(self): |
| 785 | super().test_getrandbits() |
| 786 | |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 787 | # Verify cross-platform repeatability |
| 788 | self.gen.seed(1234567) |
| 789 | self.assertEqual(self.gen.getrandbits(100), |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 790 | 97904845777343510404718956115) |
Raymond Hettinger | 5833587 | 2004-07-09 14:26:18 +0000 | [diff] [blame] | 791 | |
Wolfgang Maier | ba3a87a | 2018-04-17 17:16:17 +0200 | [diff] [blame] | 792 | def test_randrange_uses_getrandbits(self): |
| 793 | # Verify use of getrandbits by randrange |
| 794 | # Use same seed as in the cross-platform repeatability test |
Antoine Pitrou | 75a3378 | 2020-04-17 19:32:14 +0200 | [diff] [blame] | 795 | # in test_getrandbits above. |
Wolfgang Maier | ba3a87a | 2018-04-17 17:16:17 +0200 | [diff] [blame] | 796 | self.gen.seed(1234567) |
| 797 | # If randrange uses getrandbits, it should pick getrandbits(100) |
| 798 | # when called with a 100-bits stop argument. |
| 799 | self.assertEqual(self.gen.randrange(2**99), |
| 800 | 97904845777343510404718956115) |
| 801 | |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 802 | def test_randbelow_logic(self, _log=log, int=int): |
| 803 | # check bitcount transition points: 2**i and 2**(i+1)-1 |
| 804 | # show that: k = int(1.001 + _log(n, 2)) |
| 805 | # is equal to or one greater than the number of bits in n |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 806 | for i in range(1, 1000): |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 807 | n = 1 << i # check an exact power of two |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 808 | numbits = i+1 |
| 809 | k = int(1.00001 + _log(n, 2)) |
| 810 | self.assertEqual(k, numbits) |
Guido van Rossum | e61fd5b | 2007-07-11 12:20:59 +0000 | [diff] [blame] | 811 | self.assertEqual(n, 2**(k-1)) |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 812 | |
| 813 | n += n - 1 # check 1 below the next power of two |
| 814 | k = int(1.00001 + _log(n, 2)) |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 815 | self.assertIn(k, [numbits, numbits+1]) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 816 | self.assertTrue(2**k > n > 2**(k-2)) |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 817 | |
| 818 | n -= n >> 15 # check a little farther below the next power of two |
| 819 | k = int(1.00001 + _log(n, 2)) |
| 820 | self.assertEqual(k, numbits) # note the stronger assertion |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 821 | self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion |
Raymond Hettinger | 2f726e9 | 2003-10-05 09:09:15 +0000 | [diff] [blame] | 822 | |
Wolfgang Maier | ba3a87a | 2018-04-17 17:16:17 +0200 | [diff] [blame] | 823 | def test_randbelow_without_getrandbits(self): |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 824 | # Random._randbelow() can only use random() when the built-in one |
| 825 | # has been overridden but no new getrandbits() method was supplied. |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 826 | maxsize = 1<<random.BPF |
| 827 | with warnings.catch_warnings(): |
| 828 | warnings.simplefilter("ignore", UserWarning) |
| 829 | # Population range too large (n >= maxsize) |
Wolfgang Maier | ba3a87a | 2018-04-17 17:16:17 +0200 | [diff] [blame] | 830 | self.gen._randbelow_without_getrandbits( |
| 831 | maxsize+1, maxsize=maxsize |
| 832 | ) |
| 833 | self.gen._randbelow_without_getrandbits(5640, maxsize=maxsize) |
Raymond Hettinger | 4168f1e | 2020-05-01 10:34:19 -0700 | [diff] [blame] | 834 | # issue 33203: test that _randbelow returns zero on |
Wolfgang Maier | 091e95e | 2018-04-05 17:19:44 +0200 | [diff] [blame] | 835 | # n == 0 also in its getrandbits-independent branch. |
Raymond Hettinger | 4168f1e | 2020-05-01 10:34:19 -0700 | [diff] [blame] | 836 | x = self.gen._randbelow_without_getrandbits(0, maxsize=maxsize) |
| 837 | self.assertEqual(x, 0) |
Wolfgang Maier | ba3a87a | 2018-04-17 17:16:17 +0200 | [diff] [blame] | 838 | |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 839 | # This might be going too far to test a single line, but because of our |
| 840 | # noble aim of achieving 100% test coverage we need to write a case in |
| 841 | # which the following line in Random._randbelow() gets executed: |
| 842 | # |
| 843 | # rem = maxsize % n |
| 844 | # limit = (maxsize - rem) / maxsize |
| 845 | # r = random() |
| 846 | # while r >= limit: |
| 847 | # r = random() # <== *This line* <==< |
| 848 | # |
| 849 | # Therefore, to guarantee that the while loop is executed at least |
| 850 | # once, we need to mock random() so that it returns a number greater |
| 851 | # than 'limit' the first time it gets called. |
| 852 | |
| 853 | n = 42 |
| 854 | epsilon = 0.01 |
| 855 | limit = (maxsize - (maxsize % n)) / maxsize |
Wolfgang Maier | ba3a87a | 2018-04-17 17:16:17 +0200 | [diff] [blame] | 856 | with unittest.mock.patch.object(random.Random, 'random') as random_mock: |
| 857 | random_mock.side_effect = [limit + epsilon, limit - epsilon] |
| 858 | self.gen._randbelow_without_getrandbits(n, maxsize=maxsize) |
| 859 | self.assertEqual(random_mock.call_count, 2) |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 860 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 861 | def test_randrange_bug_1590891(self): |
| 862 | start = 1000000000000 |
| 863 | stop = -100000000000000000000 |
| 864 | step = -200 |
| 865 | x = self.gen.randrange(start, stop, step) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 866 | self.assertTrue(stop < x <= start) |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 867 | self.assertEqual((x+stop)%step, 0) |
| 868 | |
Raymond Hettinger | 30d00e5 | 2016-10-29 16:55:36 -0700 | [diff] [blame] | 869 | def test_choices_algorithms(self): |
Raymond Hettinger | 24e4239 | 2016-11-13 00:42:56 -0500 | [diff] [blame] | 870 | # The various ways of specifying weights should produce the same results |
Raymond Hettinger | 30d00e5 | 2016-10-29 16:55:36 -0700 | [diff] [blame] | 871 | choices = self.gen.choices |
Raymond Hettinger | 6023d33 | 2016-11-21 15:32:08 -0800 | [diff] [blame] | 872 | n = 104729 |
Raymond Hettinger | 30d00e5 | 2016-10-29 16:55:36 -0700 | [diff] [blame] | 873 | |
| 874 | self.gen.seed(8675309) |
| 875 | a = self.gen.choices(range(n), k=10000) |
| 876 | |
| 877 | self.gen.seed(8675309) |
| 878 | b = self.gen.choices(range(n), [1]*n, k=10000) |
| 879 | self.assertEqual(a, b) |
| 880 | |
| 881 | self.gen.seed(8675309) |
| 882 | c = self.gen.choices(range(n), cum_weights=range(1, n+1), k=10000) |
| 883 | self.assertEqual(a, c) |
| 884 | |
penguindustin | 9646630 | 2019-05-06 14:57:17 -0400 | [diff] [blame] | 885 | # American Roulette |
Raymond Hettinger | 77d574d | 2016-10-29 17:42:36 -0700 | [diff] [blame] | 886 | population = ['Red', 'Black', 'Green'] |
| 887 | weights = [18, 18, 2] |
| 888 | cum_weights = [18, 36, 38] |
| 889 | expanded_population = ['Red'] * 18 + ['Black'] * 18 + ['Green'] * 2 |
| 890 | |
| 891 | self.gen.seed(9035768) |
| 892 | a = self.gen.choices(expanded_population, k=10000) |
| 893 | |
| 894 | self.gen.seed(9035768) |
| 895 | b = self.gen.choices(population, weights, k=10000) |
| 896 | self.assertEqual(a, b) |
| 897 | |
| 898 | self.gen.seed(9035768) |
| 899 | c = self.gen.choices(population, cum_weights=cum_weights, k=10000) |
| 900 | self.assertEqual(a, c) |
| 901 | |
Victor Stinner | 9f5fe79 | 2020-04-17 19:05:35 +0200 | [diff] [blame] | 902 | def test_randbytes(self): |
| 903 | super().test_randbytes() |
| 904 | |
| 905 | # Mersenne Twister randbytes() is deterministic |
| 906 | # and does not depend on the endian and bitness. |
| 907 | seed = 8675309 |
Serhiy Storchaka | 223221b | 2020-04-17 23:51:28 +0300 | [diff] [blame] | 908 | expected = b'3\xa8\xf9f\xf4\xa4\xd06\x19\x8f\x9f\x82\x02oe\xf0' |
Victor Stinner | 9f5fe79 | 2020-04-17 19:05:35 +0200 | [diff] [blame] | 909 | |
| 910 | self.gen.seed(seed) |
| 911 | self.assertEqual(self.gen.randbytes(16), expected) |
| 912 | |
| 913 | # randbytes(0) must not consume any entropy |
| 914 | self.gen.seed(seed) |
| 915 | self.assertEqual(self.gen.randbytes(0), b'') |
| 916 | self.assertEqual(self.gen.randbytes(16), expected) |
| 917 | |
| 918 | # Four randbytes(4) calls give the same output than randbytes(16) |
| 919 | self.gen.seed(seed) |
| 920 | self.assertEqual(b''.join([self.gen.randbytes(4) for _ in range(4)]), |
| 921 | expected) |
| 922 | |
Serhiy Storchaka | 223221b | 2020-04-17 23:51:28 +0300 | [diff] [blame] | 923 | # Each randbytes(1), randbytes(2) or randbytes(3) call consumes |
| 924 | # 4 bytes of entropy |
Victor Stinner | 9f5fe79 | 2020-04-17 19:05:35 +0200 | [diff] [blame] | 925 | self.gen.seed(seed) |
Serhiy Storchaka | 223221b | 2020-04-17 23:51:28 +0300 | [diff] [blame] | 926 | expected1 = expected[3::4] |
| 927 | self.assertEqual(b''.join(self.gen.randbytes(1) for _ in range(4)), |
| 928 | expected1) |
| 929 | |
| 930 | self.gen.seed(seed) |
| 931 | expected2 = b''.join(expected[i + 2: i + 4] |
Victor Stinner | 9f5fe79 | 2020-04-17 19:05:35 +0200 | [diff] [blame] | 932 | for i in range(0, len(expected), 4)) |
| 933 | self.assertEqual(b''.join(self.gen.randbytes(2) for _ in range(4)), |
| 934 | expected2) |
| 935 | |
| 936 | self.gen.seed(seed) |
Serhiy Storchaka | 223221b | 2020-04-17 23:51:28 +0300 | [diff] [blame] | 937 | expected3 = b''.join(expected[i + 1: i + 4] |
Victor Stinner | 9f5fe79 | 2020-04-17 19:05:35 +0200 | [diff] [blame] | 938 | for i in range(0, len(expected), 4)) |
| 939 | self.assertEqual(b''.join(self.gen.randbytes(3) for _ in range(4)), |
| 940 | expected3) |
| 941 | |
Serhiy Storchaka | 223221b | 2020-04-17 23:51:28 +0300 | [diff] [blame] | 942 | def test_randbytes_getrandbits(self): |
| 943 | # There is a simple relation between randbytes() and getrandbits() |
| 944 | seed = 2849427419 |
| 945 | gen2 = random.Random() |
| 946 | self.gen.seed(seed) |
| 947 | gen2.seed(seed) |
| 948 | for n in range(9): |
| 949 | self.assertEqual(self.gen.randbytes(n), |
| 950 | gen2.getrandbits(n * 8).to_bytes(n, 'little')) |
| 951 | |
Victor Stinner | 9f5fe79 | 2020-04-17 19:05:35 +0200 | [diff] [blame] | 952 | |
Raymond Hettinger | 2d0c256 | 2009-02-19 09:53:18 +0000 | [diff] [blame] | 953 | def gamma(z, sqrt2pi=(2.0*pi)**0.5): |
| 954 | # Reflection to right half of complex plane |
| 955 | if z < 0.5: |
| 956 | return pi / sin(pi*z) / gamma(1.0-z) |
| 957 | # Lanczos approximation with g=7 |
| 958 | az = z + (7.0 - 0.5) |
| 959 | return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([ |
| 960 | 0.9999999999995183, |
| 961 | 676.5203681218835 / z, |
| 962 | -1259.139216722289 / (z+1.0), |
| 963 | 771.3234287757674 / (z+2.0), |
| 964 | -176.6150291498386 / (z+3.0), |
| 965 | 12.50734324009056 / (z+4.0), |
| 966 | -0.1385710331296526 / (z+5.0), |
| 967 | 0.9934937113930748e-05 / (z+6.0), |
| 968 | 0.1659470187408462e-06 / (z+7.0), |
| 969 | ]) |
Raymond Hettinger | 3dd990c | 2003-01-05 09:20:06 +0000 | [diff] [blame] | 970 | |
Raymond Hettinger | 15ec373 | 2003-01-05 01:08:34 +0000 | [diff] [blame] | 971 | class TestDistributions(unittest.TestCase): |
| 972 | def test_zeroinputs(self): |
| 973 | # Verify that distributions can handle a series of zero inputs' |
| 974 | g = random.Random() |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 975 | x = [g.random() for i in range(50)] + [0.0]*5 |
Raymond Hettinger | 15ec373 | 2003-01-05 01:08:34 +0000 | [diff] [blame] | 976 | g.random = x[:].pop; g.uniform(1,10) |
| 977 | g.random = x[:].pop; g.paretovariate(1.0) |
| 978 | g.random = x[:].pop; g.expovariate(1.0) |
| 979 | g.random = x[:].pop; g.weibullvariate(1.0, 1.0) |
Serhiy Storchaka | 6c22b1d | 2013-02-10 19:28:56 +0200 | [diff] [blame] | 980 | g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0) |
Raymond Hettinger | 15ec373 | 2003-01-05 01:08:34 +0000 | [diff] [blame] | 981 | g.random = x[:].pop; g.normalvariate(0.0, 1.0) |
| 982 | g.random = x[:].pop; g.gauss(0.0, 1.0) |
| 983 | g.random = x[:].pop; g.lognormvariate(0.0, 1.0) |
| 984 | g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0) |
| 985 | g.random = x[:].pop; g.gammavariate(0.01, 1.0) |
| 986 | g.random = x[:].pop; g.gammavariate(1.0, 1.0) |
| 987 | g.random = x[:].pop; g.gammavariate(200.0, 1.0) |
| 988 | g.random = x[:].pop; g.betavariate(3.0, 3.0) |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 989 | g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0) |
Raymond Hettinger | 15ec373 | 2003-01-05 01:08:34 +0000 | [diff] [blame] | 990 | |
Raymond Hettinger | 3dd990c | 2003-01-05 09:20:06 +0000 | [diff] [blame] | 991 | def test_avg_std(self): |
| 992 | # Use integration to test distribution average and standard deviation. |
| 993 | # Only works for distributions which do not consume variates in pairs |
| 994 | g = random.Random() |
| 995 | N = 5000 |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 996 | x = [i/float(N) for i in range(1,N)] |
Raymond Hettinger | 3dd990c | 2003-01-05 09:20:06 +0000 | [diff] [blame] | 997 | for variate, args, mu, sigmasqrd in [ |
| 998 | (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12), |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 999 | (g.triangular, (0.0, 1.0, 1.0/3.0), 4.0/9.0, 7.0/9.0/18.0), |
Raymond Hettinger | 3dd990c | 2003-01-05 09:20:06 +0000 | [diff] [blame] | 1000 | (g.expovariate, (1.5,), 1/1.5, 1/1.5**2), |
Serhiy Storchaka | 6c22b1d | 2013-02-10 19:28:56 +0200 | [diff] [blame] | 1001 | (g.vonmisesvariate, (1.23, 0), pi, pi**2/3), |
Raymond Hettinger | 3dd990c | 2003-01-05 09:20:06 +0000 | [diff] [blame] | 1002 | (g.paretovariate, (5.0,), 5.0/(5.0-1), |
| 1003 | 5.0/((5.0-1)**2*(5.0-2))), |
| 1004 | (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0), |
| 1005 | gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]: |
| 1006 | g.random = x[:].pop |
| 1007 | y = [] |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 1008 | for i in range(len(x)): |
Raymond Hettinger | 3dd990c | 2003-01-05 09:20:06 +0000 | [diff] [blame] | 1009 | try: |
| 1010 | y.append(variate(*args)) |
| 1011 | except IndexError: |
| 1012 | pass |
| 1013 | s1 = s2 = 0 |
| 1014 | for e in y: |
| 1015 | s1 += e |
| 1016 | s2 += (e - mu) ** 2 |
| 1017 | N = len(y) |
Serhiy Storchaka | 6c22b1d | 2013-02-10 19:28:56 +0200 | [diff] [blame] | 1018 | self.assertAlmostEqual(s1/N, mu, places=2, |
| 1019 | msg='%s%r' % (variate.__name__, args)) |
| 1020 | self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2, |
| 1021 | msg='%s%r' % (variate.__name__, args)) |
| 1022 | |
| 1023 | def test_constant(self): |
| 1024 | g = random.Random() |
| 1025 | N = 100 |
| 1026 | for variate, args, expected in [ |
| 1027 | (g.uniform, (10.0, 10.0), 10.0), |
| 1028 | (g.triangular, (10.0, 10.0), 10.0), |
Raymond Hettinger | 978c6ab | 2014-05-25 17:25:27 -0700 | [diff] [blame] | 1029 | (g.triangular, (10.0, 10.0, 10.0), 10.0), |
Serhiy Storchaka | 6c22b1d | 2013-02-10 19:28:56 +0200 | [diff] [blame] | 1030 | (g.expovariate, (float('inf'),), 0.0), |
| 1031 | (g.vonmisesvariate, (3.0, float('inf')), 3.0), |
| 1032 | (g.gauss, (10.0, 0.0), 10.0), |
| 1033 | (g.lognormvariate, (0.0, 0.0), 1.0), |
| 1034 | (g.lognormvariate, (-float('inf'), 0.0), 0.0), |
| 1035 | (g.normalvariate, (10.0, 0.0), 10.0), |
| 1036 | (g.paretovariate, (float('inf'),), 1.0), |
| 1037 | (g.weibullvariate, (10.0, float('inf')), 10.0), |
| 1038 | (g.weibullvariate, (0.0, 10.0), 0.0), |
| 1039 | ]: |
| 1040 | for i in range(N): |
| 1041 | self.assertEqual(variate(*args), expected) |
Raymond Hettinger | 3dd990c | 2003-01-05 09:20:06 +0000 | [diff] [blame] | 1042 | |
Mark Dickinson | be5f919 | 2013-02-10 14:16:10 +0000 | [diff] [blame] | 1043 | def test_von_mises_range(self): |
| 1044 | # Issue 17149: von mises variates were not consistently in the |
| 1045 | # range [0, 2*PI]. |
| 1046 | g = random.Random() |
| 1047 | N = 100 |
| 1048 | for mu in 0.0, 0.1, 3.1, 6.2: |
| 1049 | for kappa in 0.0, 2.3, 500.0: |
| 1050 | for _ in range(N): |
| 1051 | sample = g.vonmisesvariate(mu, kappa) |
| 1052 | self.assertTrue( |
| 1053 | 0 <= sample <= random.TWOPI, |
| 1054 | msg=("vonmisesvariate({}, {}) produced a result {} out" |
| 1055 | " of range [0, 2*pi]").format(mu, kappa, sample)) |
| 1056 | |
Serhiy Storchaka | 6c22b1d | 2013-02-10 19:28:56 +0200 | [diff] [blame] | 1057 | def test_von_mises_large_kappa(self): |
| 1058 | # Issue #17141: vonmisesvariate() was hang for large kappas |
| 1059 | random.vonmisesvariate(0, 1e15) |
| 1060 | random.vonmisesvariate(0, 1e100) |
| 1061 | |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 1062 | def test_gammavariate_errors(self): |
| 1063 | # Both alpha and beta must be > 0.0 |
| 1064 | self.assertRaises(ValueError, random.gammavariate, -1, 3) |
| 1065 | self.assertRaises(ValueError, random.gammavariate, 0, 2) |
| 1066 | self.assertRaises(ValueError, random.gammavariate, 2, 0) |
| 1067 | self.assertRaises(ValueError, random.gammavariate, 1, -3) |
| 1068 | |
leodema | 63d1522 | 2018-12-24 07:54:25 +0100 | [diff] [blame] | 1069 | # There are three different possibilities in the current implementation |
| 1070 | # of random.gammavariate(), depending on the value of 'alpha'. What we |
| 1071 | # are going to do here is to fix the values returned by random() to |
| 1072 | # generate test cases that provide 100% line coverage of the method. |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 1073 | @unittest.mock.patch('random.Random.random') |
leodema | 63d1522 | 2018-12-24 07:54:25 +0100 | [diff] [blame] | 1074 | def test_gammavariate_alpha_greater_one(self, random_mock): |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 1075 | |
leodema | 63d1522 | 2018-12-24 07:54:25 +0100 | [diff] [blame] | 1076 | # #1: alpha > 1.0. |
| 1077 | # We want the first random number to be outside the |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 1078 | # [1e-7, .9999999] range, so that the continue statement executes |
| 1079 | # once. The values of u1 and u2 will be 0.5 and 0.3, respectively. |
| 1080 | random_mock.side_effect = [1e-8, 0.5, 0.3] |
| 1081 | returned_value = random.gammavariate(1.1, 2.3) |
| 1082 | self.assertAlmostEqual(returned_value, 2.53) |
| 1083 | |
leodema | 63d1522 | 2018-12-24 07:54:25 +0100 | [diff] [blame] | 1084 | @unittest.mock.patch('random.Random.random') |
| 1085 | def test_gammavariate_alpha_equal_one(self, random_mock): |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 1086 | |
leodema | 63d1522 | 2018-12-24 07:54:25 +0100 | [diff] [blame] | 1087 | # #2.a: alpha == 1. |
| 1088 | # The execution body of the while loop executes once. |
| 1089 | # Then random.random() returns 0.45, |
| 1090 | # which causes while to stop looping and the algorithm to terminate. |
| 1091 | random_mock.side_effect = [0.45] |
| 1092 | returned_value = random.gammavariate(1.0, 3.14) |
| 1093 | self.assertAlmostEqual(returned_value, 1.877208182372648) |
| 1094 | |
| 1095 | @unittest.mock.patch('random.Random.random') |
| 1096 | def test_gammavariate_alpha_equal_one_equals_expovariate(self, random_mock): |
| 1097 | |
| 1098 | # #2.b: alpha == 1. |
| 1099 | # It must be equivalent of calling expovariate(1.0 / beta). |
| 1100 | beta = 3.14 |
| 1101 | random_mock.side_effect = [1e-8, 1e-8] |
| 1102 | gammavariate_returned_value = random.gammavariate(1.0, beta) |
| 1103 | expovariate_returned_value = random.expovariate(1.0 / beta) |
| 1104 | self.assertAlmostEqual(gammavariate_returned_value, expovariate_returned_value) |
| 1105 | |
| 1106 | @unittest.mock.patch('random.Random.random') |
| 1107 | def test_gammavariate_alpha_between_zero_and_one(self, random_mock): |
| 1108 | |
| 1109 | # #3: 0 < alpha < 1. |
| 1110 | # This is the most complex region of code to cover, |
R David Murray | e3e1c17 | 2013-04-02 12:47:23 -0400 | [diff] [blame] | 1111 | # as there are multiple if-else statements. Let's take a look at the |
| 1112 | # source code, and determine the values that we need accordingly: |
| 1113 | # |
| 1114 | # while 1: |
| 1115 | # u = random() |
| 1116 | # b = (_e + alpha)/_e |
| 1117 | # p = b*u |
| 1118 | # if p <= 1.0: # <=== (A) |
| 1119 | # x = p ** (1.0/alpha) |
| 1120 | # else: # <=== (B) |
| 1121 | # x = -_log((b-p)/alpha) |
| 1122 | # u1 = random() |
| 1123 | # if p > 1.0: # <=== (C) |
| 1124 | # if u1 <= x ** (alpha - 1.0): # <=== (D) |
| 1125 | # break |
| 1126 | # elif u1 <= _exp(-x): # <=== (E) |
| 1127 | # break |
| 1128 | # return x * beta |
| 1129 | # |
| 1130 | # First, we want (A) to be True. For that we need that: |
| 1131 | # b*random() <= 1.0 |
| 1132 | # r1 = random() <= 1.0 / b |
| 1133 | # |
| 1134 | # We now get to the second if-else branch, and here, since p <= 1.0, |
| 1135 | # (C) is False and we take the elif branch, (E). For it to be True, |
| 1136 | # so that the break is executed, we need that: |
| 1137 | # r2 = random() <= _exp(-x) |
| 1138 | # r2 <= _exp(-(p ** (1.0/alpha))) |
| 1139 | # r2 <= _exp(-((b*r1) ** (1.0/alpha))) |
| 1140 | |
| 1141 | _e = random._e |
| 1142 | _exp = random._exp |
| 1143 | _log = random._log |
| 1144 | alpha = 0.35 |
| 1145 | beta = 1.45 |
| 1146 | b = (_e + alpha)/_e |
| 1147 | epsilon = 0.01 |
| 1148 | |
| 1149 | r1 = 0.8859296441566 # 1.0 / b |
| 1150 | r2 = 0.3678794411714 # _exp(-((b*r1) ** (1.0/alpha))) |
| 1151 | |
| 1152 | # These four "random" values result in the following trace: |
| 1153 | # (A) True, (E) False --> [next iteration of while] |
| 1154 | # (A) True, (E) True --> [while loop breaks] |
| 1155 | random_mock.side_effect = [r1, r2 + epsilon, r1, r2] |
| 1156 | returned_value = random.gammavariate(alpha, beta) |
| 1157 | self.assertAlmostEqual(returned_value, 1.4499999999997544) |
| 1158 | |
| 1159 | # Let's now make (A) be False. If this is the case, when we get to the |
| 1160 | # second if-else 'p' is greater than 1, so (C) evaluates to True. We |
| 1161 | # now encounter a second if statement, (D), which in order to execute |
| 1162 | # must satisfy the following condition: |
| 1163 | # r2 <= x ** (alpha - 1.0) |
| 1164 | # r2 <= (-_log((b-p)/alpha)) ** (alpha - 1.0) |
| 1165 | # r2 <= (-_log((b-(b*r1))/alpha)) ** (alpha - 1.0) |
| 1166 | r1 = 0.8959296441566 # (1.0 / b) + epsilon -- so that (A) is False |
| 1167 | r2 = 0.9445400408898141 |
| 1168 | |
| 1169 | # And these four values result in the following trace: |
| 1170 | # (B) and (C) True, (D) False --> [next iteration of while] |
| 1171 | # (B) and (C) True, (D) True [while loop breaks] |
| 1172 | random_mock.side_effect = [r1, r2 + epsilon, r1, r2] |
| 1173 | returned_value = random.gammavariate(alpha, beta) |
| 1174 | self.assertAlmostEqual(returned_value, 1.5830349561760781) |
| 1175 | |
| 1176 | @unittest.mock.patch('random.Random.gammavariate') |
| 1177 | def test_betavariate_return_zero(self, gammavariate_mock): |
| 1178 | # betavariate() returns zero when the Gamma distribution |
| 1179 | # that it uses internally returns this same value. |
| 1180 | gammavariate_mock.return_value = 0.0 |
| 1181 | self.assertEqual(0.0, random.betavariate(2.71828, 3.14159)) |
Serhiy Storchaka | 6c22b1d | 2013-02-10 19:28:56 +0200 | [diff] [blame] | 1182 | |
Serhiy Storchaka | ec1622d | 2018-05-08 15:45:15 +0300 | [diff] [blame] | 1183 | |
Wolfgang Maier | ba3a87a | 2018-04-17 17:16:17 +0200 | [diff] [blame] | 1184 | class TestRandomSubclassing(unittest.TestCase): |
| 1185 | def test_random_subclass_with_kwargs(self): |
| 1186 | # SF bug #1486663 -- this used to erroneously raise a TypeError |
| 1187 | class Subclass(random.Random): |
| 1188 | def __init__(self, newarg=None): |
| 1189 | random.Random.__init__(self) |
| 1190 | Subclass(newarg=1) |
| 1191 | |
| 1192 | def test_subclasses_overriding_methods(self): |
| 1193 | # Subclasses with an overridden random, but only the original |
| 1194 | # getrandbits method should not rely on getrandbits in for randrange, |
| 1195 | # but should use a getrandbits-independent implementation instead. |
| 1196 | |
| 1197 | # subclass providing its own random **and** getrandbits methods |
| 1198 | # like random.SystemRandom does => keep relying on getrandbits for |
| 1199 | # randrange |
| 1200 | class SubClass1(random.Random): |
| 1201 | def random(self): |
Serhiy Storchaka | ec1622d | 2018-05-08 15:45:15 +0300 | [diff] [blame] | 1202 | called.add('SubClass1.random') |
| 1203 | return random.Random.random(self) |
Wolfgang Maier | ba3a87a | 2018-04-17 17:16:17 +0200 | [diff] [blame] | 1204 | |
| 1205 | def getrandbits(self, n): |
Serhiy Storchaka | ec1622d | 2018-05-08 15:45:15 +0300 | [diff] [blame] | 1206 | called.add('SubClass1.getrandbits') |
| 1207 | return random.Random.getrandbits(self, n) |
| 1208 | called = set() |
| 1209 | SubClass1().randrange(42) |
| 1210 | self.assertEqual(called, {'SubClass1.getrandbits'}) |
Wolfgang Maier | ba3a87a | 2018-04-17 17:16:17 +0200 | [diff] [blame] | 1211 | |
| 1212 | # subclass providing only random => can only use random for randrange |
| 1213 | class SubClass2(random.Random): |
| 1214 | def random(self): |
Serhiy Storchaka | ec1622d | 2018-05-08 15:45:15 +0300 | [diff] [blame] | 1215 | called.add('SubClass2.random') |
| 1216 | return random.Random.random(self) |
| 1217 | called = set() |
| 1218 | SubClass2().randrange(42) |
| 1219 | self.assertEqual(called, {'SubClass2.random'}) |
Wolfgang Maier | ba3a87a | 2018-04-17 17:16:17 +0200 | [diff] [blame] | 1220 | |
| 1221 | # subclass defining getrandbits to complement its inherited random |
| 1222 | # => can now rely on getrandbits for randrange again |
| 1223 | class SubClass3(SubClass2): |
| 1224 | def getrandbits(self, n): |
Serhiy Storchaka | ec1622d | 2018-05-08 15:45:15 +0300 | [diff] [blame] | 1225 | called.add('SubClass3.getrandbits') |
| 1226 | return random.Random.getrandbits(self, n) |
| 1227 | called = set() |
| 1228 | SubClass3().randrange(42) |
| 1229 | self.assertEqual(called, {'SubClass3.getrandbits'}) |
| 1230 | |
| 1231 | # subclass providing only random and inherited getrandbits |
| 1232 | # => random takes precedence |
| 1233 | class SubClass4(SubClass3): |
| 1234 | def random(self): |
| 1235 | called.add('SubClass4.random') |
| 1236 | return random.Random.random(self) |
| 1237 | called = set() |
| 1238 | SubClass4().randrange(42) |
| 1239 | self.assertEqual(called, {'SubClass4.random'}) |
| 1240 | |
| 1241 | # Following subclasses don't define random or getrandbits directly, |
| 1242 | # but inherit them from classes which are not subclasses of Random |
| 1243 | class Mixin1: |
| 1244 | def random(self): |
| 1245 | called.add('Mixin1.random') |
| 1246 | return random.Random.random(self) |
| 1247 | class Mixin2: |
| 1248 | def getrandbits(self, n): |
| 1249 | called.add('Mixin2.getrandbits') |
| 1250 | return random.Random.getrandbits(self, n) |
| 1251 | |
| 1252 | class SubClass5(Mixin1, random.Random): |
| 1253 | pass |
| 1254 | called = set() |
| 1255 | SubClass5().randrange(42) |
| 1256 | self.assertEqual(called, {'Mixin1.random'}) |
| 1257 | |
| 1258 | class SubClass6(Mixin2, random.Random): |
| 1259 | pass |
| 1260 | called = set() |
| 1261 | SubClass6().randrange(42) |
| 1262 | self.assertEqual(called, {'Mixin2.getrandbits'}) |
| 1263 | |
| 1264 | class SubClass7(Mixin1, Mixin2, random.Random): |
| 1265 | pass |
| 1266 | called = set() |
| 1267 | SubClass7().randrange(42) |
| 1268 | self.assertEqual(called, {'Mixin1.random'}) |
| 1269 | |
| 1270 | class SubClass8(Mixin2, Mixin1, random.Random): |
| 1271 | pass |
| 1272 | called = set() |
| 1273 | SubClass8().randrange(42) |
| 1274 | self.assertEqual(called, {'Mixin2.getrandbits'}) |
| 1275 | |
Wolfgang Maier | ba3a87a | 2018-04-17 17:16:17 +0200 | [diff] [blame] | 1276 | |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 1277 | class TestModule(unittest.TestCase): |
| 1278 | def testMagicConstants(self): |
| 1279 | self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141) |
| 1280 | self.assertAlmostEqual(random.TWOPI, 6.28318530718) |
| 1281 | self.assertAlmostEqual(random.LOG4, 1.38629436111989) |
| 1282 | self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627) |
| 1283 | |
| 1284 | def test__all__(self): |
| 1285 | # tests validity but not completeness of the __all__ list |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 1286 | self.assertTrue(set(random.__all__) <= set(dir(random))) |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 1287 | |
Antoine Pitrou | 346cbd3 | 2017-05-27 17:50:54 +0200 | [diff] [blame] | 1288 | @unittest.skipUnless(hasattr(os, "fork"), "fork() required") |
| 1289 | def test_after_fork(self): |
| 1290 | # Test the global Random instance gets reseeded in child |
| 1291 | r, w = os.pipe() |
Victor Stinner | da5e930 | 2017-08-09 17:59:05 +0200 | [diff] [blame] | 1292 | pid = os.fork() |
| 1293 | if pid == 0: |
| 1294 | # child process |
Antoine Pitrou | 346cbd3 | 2017-05-27 17:50:54 +0200 | [diff] [blame] | 1295 | try: |
| 1296 | val = random.getrandbits(128) |
| 1297 | with open(w, "w") as f: |
| 1298 | f.write(str(val)) |
| 1299 | finally: |
| 1300 | os._exit(0) |
| 1301 | else: |
Victor Stinner | da5e930 | 2017-08-09 17:59:05 +0200 | [diff] [blame] | 1302 | # parent process |
Antoine Pitrou | 346cbd3 | 2017-05-27 17:50:54 +0200 | [diff] [blame] | 1303 | os.close(w) |
| 1304 | val = random.getrandbits(128) |
| 1305 | with open(r, "r") as f: |
| 1306 | child_val = eval(f.read()) |
| 1307 | self.assertNotEqual(val, child_val) |
| 1308 | |
Victor Stinner | 278c1e1 | 2020-03-31 20:08:12 +0200 | [diff] [blame] | 1309 | support.wait_process(pid, exitcode=0) |
Victor Stinner | da5e930 | 2017-08-09 17:59:05 +0200 | [diff] [blame] | 1310 | |
Thomas Wouters | b213704 | 2007-02-01 18:02:27 +0000 | [diff] [blame] | 1311 | |
Raymond Hettinger | 40f6217 | 2002-12-29 23:03:38 +0000 | [diff] [blame] | 1312 | if __name__ == "__main__": |
Ezio Melotti | 3e4a98b | 2013-04-19 05:45:27 +0300 | [diff] [blame] | 1313 | unittest.main() |