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