test_random.py 55 KB

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