Home | History | Annotate | Download | only in test
      1 #!/usr/bin/env python
      2 
      3 import unittest
      4 import random
      5 import time
      6 import pickle
      7 import warnings
      8 from math import log, exp, pi, fsum, sin
      9 from functools import reduce
     10 from test import test_support
     11 
     12 class TestBasicOps(unittest.TestCase):
     13     # Superclass with tests common to all generators.
     14     # Subclasses must arrange for self.gen to retrieve the Random instance
     15     # to be tested.
     16 
     17     def randomlist(self, n):
     18         """Helper function to make a list of random numbers"""
     19         return [self.gen.random() for i in xrange(n)]
     20 
     21     def test_autoseed(self):
     22         self.gen.seed()
     23         state1 = self.gen.getstate()
     24         time.sleep(0.1)
     25         self.gen.seed()      # diffent seeds at different times
     26         state2 = self.gen.getstate()
     27         self.assertNotEqual(state1, state2)
     28 
     29     def test_saverestore(self):
     30         N = 1000
     31         self.gen.seed()
     32         state = self.gen.getstate()
     33         randseq = self.randomlist(N)
     34         self.gen.setstate(state)    # should regenerate the same sequence
     35         self.assertEqual(randseq, self.randomlist(N))
     36 
     37     def test_seedargs(self):
     38         for arg in [None, 0, 0L, 1, 1L, -1, -1L, 10**20, -(10**20),
     39                     3.14, 1+2j, 'a', tuple('abc')]:
     40             self.gen.seed(arg)
     41         for arg in [range(3), dict(one=1)]:
     42             self.assertRaises(TypeError, self.gen.seed, arg)
     43         self.assertRaises(TypeError, self.gen.seed, 1, 2)
     44         self.assertRaises(TypeError, type(self.gen), [])
     45 
     46     def test_jumpahead(self):
     47         self.gen.seed()
     48         state1 = self.gen.getstate()
     49         self.gen.jumpahead(100)
     50         state2 = self.gen.getstate()    # s/b distinct from state1
     51         self.assertNotEqual(state1, state2)
     52         self.gen.jumpahead(100)
     53         state3 = self.gen.getstate()    # s/b distinct from state2
     54         self.assertNotEqual(state2, state3)
     55 
     56         with test_support.check_py3k_warnings(quiet=True):
     57             self.assertRaises(TypeError, self.gen.jumpahead)  # needs an arg
     58             self.assertRaises(TypeError, self.gen.jumpahead, 2, 3)  # too many
     59 
     60     def test_jumpahead_produces_valid_state(self):
     61         # From http://bugs.python.org/issue14591.
     62         self.gen.seed(199210368)
     63         self.gen.jumpahead(13550674232554645900)
     64         for i in range(500):
     65             val = self.gen.random()
     66             self.assertLess(val, 1.0)
     67 
     68     def test_sample(self):
     69         # For the entire allowable range of 0 <= k <= N, validate that
     70         # the sample is of the correct length and contains only unique items
     71         N = 100
     72         population = xrange(N)
     73         for k in xrange(N+1):
     74             s = self.gen.sample(population, k)
     75             self.assertEqual(len(s), k)
     76             uniq = set(s)
     77             self.assertEqual(len(uniq), k)
     78             self.assertTrue(uniq <= set(population))
     79         self.assertEqual(self.gen.sample([], 0), [])  # test edge case N==k==0
     80 
     81     def test_sample_distribution(self):
     82         # For the entire allowable range of 0 <= k <= N, validate that
     83         # sample generates all possible permutations
     84         n = 5
     85         pop = range(n)
     86         trials = 10000  # large num prevents false negatives without slowing normal case
     87         def factorial(n):
     88             return reduce(int.__mul__, xrange(1, n), 1)
     89         for k in xrange(n):
     90             expected = factorial(n) // factorial(n-k)
     91             perms = {}
     92             for i in xrange(trials):
     93                 perms[tuple(self.gen.sample(pop, k))] = None
     94                 if len(perms) == expected:
     95                     break
     96             else:
     97                 self.fail()
     98 
     99     def test_sample_inputs(self):
    100         # SF bug #801342 -- population can be any iterable defining __len__()
    101         self.gen.sample(set(range(20)), 2)
    102         self.gen.sample(range(20), 2)
    103         self.gen.sample(xrange(20), 2)
    104         self.gen.sample(str('abcdefghijklmnopqrst'), 2)
    105         self.gen.sample(tuple('abcdefghijklmnopqrst'), 2)
    106 
    107     def test_sample_on_dicts(self):
    108         self.gen.sample(dict.fromkeys('abcdefghijklmnopqrst'), 2)
    109 
    110         # SF bug #1460340 -- random.sample can raise KeyError
    111         a = dict.fromkeys(range(10)+range(10,100,2)+range(100,110))
    112         self.gen.sample(a, 3)
    113 
    114         # A followup to bug #1460340:  sampling from a dict could return
    115         # a subset of its keys or of its values, depending on the size of
    116         # the subset requested.
    117         N = 30
    118         d = dict((i, complex(i, i)) for i in xrange(N))
    119         for k in xrange(N+1):
    120             samp = self.gen.sample(d, k)
    121             # Verify that we got ints back (keys); the values are complex.
    122             for x in samp:
    123                 self.assertTrue(type(x) is int)
    124         samp.sort()
    125         self.assertEqual(samp, range(N))
    126 
    127     def test_gauss(self):
    128         # Ensure that the seed() method initializes all the hidden state.  In
    129         # particular, through 2.2.1 it failed to reset a piece of state used
    130         # by (and only by) the .gauss() method.
    131 
    132         for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
    133             self.gen.seed(seed)
    134             x1 = self.gen.random()
    135             y1 = self.gen.gauss(0, 1)
    136 
    137             self.gen.seed(seed)
    138             x2 = self.gen.random()
    139             y2 = self.gen.gauss(0, 1)
    140 
    141             self.assertEqual(x1, x2)
    142             self.assertEqual(y1, y2)
    143 
    144     def test_pickling(self):
    145         state = pickle.dumps(self.gen)
    146         origseq = [self.gen.random() for i in xrange(10)]
    147         newgen = pickle.loads(state)
    148         restoredseq = [newgen.random() for i in xrange(10)]
    149         self.assertEqual(origseq, restoredseq)
    150 
    151     def test_bug_1727780(self):
    152         # verify that version-2-pickles can be loaded
    153         # fine, whether they are created on 32-bit or 64-bit
    154         # platforms, and that version-3-pickles load fine.
    155         files = [("randv2_32.pck", 780),
    156                  ("randv2_64.pck", 866),
    157                  ("randv3.pck", 343)]
    158         for file, value in files:
    159             f = open(test_support.findfile(file),"rb")
    160             r = pickle.load(f)
    161             f.close()
    162             self.assertEqual(r.randrange(1000), value)
    163 
    164 class WichmannHill_TestBasicOps(TestBasicOps):
    165     gen = random.WichmannHill()
    166 
    167     def test_setstate_first_arg(self):
    168         self.assertRaises(ValueError, self.gen.setstate, (2, None, None))
    169 
    170     def test_strong_jumpahead(self):
    171         # tests that jumpahead(n) semantics correspond to n calls to random()
    172         N = 1000
    173         s = self.gen.getstate()
    174         self.gen.jumpahead(N)
    175         r1 = self.gen.random()
    176         # now do it the slow way
    177         self.gen.setstate(s)
    178         for i in xrange(N):
    179             self.gen.random()
    180         r2 = self.gen.random()
    181         self.assertEqual(r1, r2)
    182 
    183     def test_gauss_with_whseed(self):
    184         # Ensure that the seed() method initializes all the hidden state.  In
    185         # particular, through 2.2.1 it failed to reset a piece of state used
    186         # by (and only by) the .gauss() method.
    187 
    188         for seed in 1, 12, 123, 1234, 12345, 123456, 654321:
    189             self.gen.whseed(seed)
    190             x1 = self.gen.random()
    191             y1 = self.gen.gauss(0, 1)
    192 
    193             self.gen.whseed(seed)
    194             x2 = self.gen.random()
    195             y2 = self.gen.gauss(0, 1)
    196 
    197             self.assertEqual(x1, x2)
    198             self.assertEqual(y1, y2)
    199 
    200     def test_bigrand(self):
    201         # Verify warnings are raised when randrange is too large for random()
    202         with warnings.catch_warnings():
    203             warnings.filterwarnings("error", "Underlying random")
    204             self.assertRaises(UserWarning, self.gen.randrange, 2**60)
    205 
    206 class SystemRandom_TestBasicOps(TestBasicOps):
    207     gen = random.SystemRandom()
    208 
    209     def test_autoseed(self):
    210         # Doesn't need to do anything except not fail
    211         self.gen.seed()
    212 
    213     def test_saverestore(self):
    214         self.assertRaises(NotImplementedError, self.gen.getstate)
    215         self.assertRaises(NotImplementedError, self.gen.setstate, None)
    216 
    217     def test_seedargs(self):
    218         # Doesn't need to do anything except not fail
    219         self.gen.seed(100)
    220 
    221     def test_jumpahead(self):
    222         # Doesn't need to do anything except not fail
    223         self.gen.jumpahead(100)
    224 
    225     def test_gauss(self):
    226         self.gen.gauss_next = None
    227         self.gen.seed(100)
    228         self.assertEqual(self.gen.gauss_next, None)
    229 
    230     def test_pickling(self):
    231         self.assertRaises(NotImplementedError, pickle.dumps, self.gen)
    232 
    233     def test_53_bits_per_float(self):
    234         # This should pass whenever a C double has 53 bit precision.
    235         span = 2 ** 53
    236         cum = 0
    237         for i in xrange(100):
    238             cum |= int(self.gen.random() * span)
    239         self.assertEqual(cum, span-1)
    240 
    241     def test_bigrand(self):
    242         # The randrange routine should build-up the required number of bits
    243         # in stages so that all bit positions are active.
    244         span = 2 ** 500
    245         cum = 0
    246         for i in xrange(100):
    247             r = self.gen.randrange(span)
    248             self.assertTrue(0 <= r < span)
    249             cum |= r
    250         self.assertEqual(cum, span-1)
    251 
    252     def test_bigrand_ranges(self):
    253         for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
    254             start = self.gen.randrange(2 ** i)
    255             stop = self.gen.randrange(2 ** (i-2))
    256             if stop <= start:
    257                 return
    258             self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
    259 
    260     def test_rangelimits(self):
    261         for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
    262             self.assertEqual(set(range(start,stop)),
    263                 set([self.gen.randrange(start,stop) for i in xrange(100)]))
    264 
    265     def test_genrandbits(self):
    266         # Verify ranges
    267         for k in xrange(1, 1000):
    268             self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
    269 
    270         # Verify all bits active
    271         getbits = self.gen.getrandbits
    272         for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
    273             cum = 0
    274             for i in xrange(100):
    275                 cum |= getbits(span)
    276             self.assertEqual(cum, 2**span-1)
    277 
    278         # Verify argument checking
    279         self.assertRaises(TypeError, self.gen.getrandbits)
    280         self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
    281         self.assertRaises(ValueError, self.gen.getrandbits, 0)
    282         self.assertRaises(ValueError, self.gen.getrandbits, -1)
    283         self.assertRaises(TypeError, self.gen.getrandbits, 10.1)
    284 
    285     def test_randbelow_logic(self, _log=log, int=int):
    286         # check bitcount transition points:  2**i and 2**(i+1)-1
    287         # show that: k = int(1.001 + _log(n, 2))
    288         # is equal to or one greater than the number of bits in n
    289         for i in xrange(1, 1000):
    290             n = 1L << i # check an exact power of two
    291             numbits = i+1
    292             k = int(1.00001 + _log(n, 2))
    293             self.assertEqual(k, numbits)
    294             self.assertTrue(n == 2**(k-1))
    295 
    296             n += n - 1      # check 1 below the next power of two
    297             k = int(1.00001 + _log(n, 2))
    298             self.assertIn(k, [numbits, numbits+1])
    299             self.assertTrue(2**k > n > 2**(k-2))
    300 
    301             n -= n >> 15     # check a little farther below the next power of two
    302             k = int(1.00001 + _log(n, 2))
    303             self.assertEqual(k, numbits)        # note the stronger assertion
    304             self.assertTrue(2**k > n > 2**(k-1))   # note the stronger assertion
    305 
    306 
    307 class MersenneTwister_TestBasicOps(TestBasicOps):
    308     gen = random.Random()
    309 
    310     def test_setstate_first_arg(self):
    311         self.assertRaises(ValueError, self.gen.setstate, (1, None, None))
    312 
    313     def test_setstate_middle_arg(self):
    314         # Wrong type, s/b tuple
    315         self.assertRaises(TypeError, self.gen.setstate, (2, None, None))
    316         # Wrong length, s/b 625
    317         self.assertRaises(ValueError, self.gen.setstate, (2, (1,2,3), None))
    318         # Wrong type, s/b tuple of 625 ints
    319         self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None))
    320         # Last element s/b an int also
    321         self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None))
    322 
    323     def test_referenceImplementation(self):
    324         # Compare the python implementation with results from the original
    325         # code.  Create 2000 53-bit precision random floats.  Compare only
    326         # the last ten entries to show that the independent implementations
    327         # are tracking.  Here is the main() function needed to create the
    328         # list of expected random numbers:
    329         #    void main(void){
    330         #         int i;
    331         #         unsigned long init[4]={61731, 24903, 614, 42143}, length=4;
    332         #         init_by_array(init, length);
    333         #         for (i=0; i<2000; i++) {
    334         #           printf("%.15f ", genrand_res53());
    335         #           if (i%5==4) printf("\n");
    336         #         }
    337         #     }
    338         expected = [0.45839803073713259,
    339                     0.86057815201978782,
    340                     0.92848331726782152,
    341                     0.35932681119782461,
    342                     0.081823493762449573,
    343                     0.14332226470169329,
    344                     0.084297823823520024,
    345                     0.53814864671831453,
    346                     0.089215024911993401,
    347                     0.78486196105372907]
    348 
    349         self.gen.seed(61731L + (24903L<<32) + (614L<<64) + (42143L<<96))
    350         actual = self.randomlist(2000)[-10:]
    351         for a, e in zip(actual, expected):
    352             self.assertAlmostEqual(a,e,places=14)
    353 
    354     def test_strong_reference_implementation(self):
    355         # Like test_referenceImplementation, but checks for exact bit-level
    356         # equality.  This should pass on any box where C double contains
    357         # at least 53 bits of precision (the underlying algorithm suffers
    358         # no rounding errors -- all results are exact).
    359         from math import ldexp
    360 
    361         expected = [0x0eab3258d2231fL,
    362                     0x1b89db315277a5L,
    363                     0x1db622a5518016L,
    364                     0x0b7f9af0d575bfL,
    365                     0x029e4c4db82240L,
    366                     0x04961892f5d673L,
    367                     0x02b291598e4589L,
    368                     0x11388382c15694L,
    369                     0x02dad977c9e1feL,
    370                     0x191d96d4d334c6L]
    371         self.gen.seed(61731L + (24903L<<32) + (614L<<64) + (42143L<<96))
    372         actual = self.randomlist(2000)[-10:]
    373         for a, e in zip(actual, expected):
    374             self.assertEqual(long(ldexp(a, 53)), e)
    375 
    376     def test_long_seed(self):
    377         # This is most interesting to run in debug mode, just to make sure
    378         # nothing blows up.  Under the covers, a dynamically resized array
    379         # is allocated, consuming space proportional to the number of bits
    380         # in the seed.  Unfortunately, that's a quadratic-time algorithm,
    381         # so don't make this horribly big.
    382         seed = (1L << (10000 * 8)) - 1  # about 10K bytes
    383         self.gen.seed(seed)
    384 
    385     def test_53_bits_per_float(self):
    386         # This should pass whenever a C double has 53 bit precision.
    387         span = 2 ** 53
    388         cum = 0
    389         for i in xrange(100):
    390             cum |= int(self.gen.random() * span)
    391         self.assertEqual(cum, span-1)
    392 
    393     def test_bigrand(self):
    394         # The randrange routine should build-up the required number of bits
    395         # in stages so that all bit positions are active.
    396         span = 2 ** 500
    397         cum = 0
    398         for i in xrange(100):
    399             r = self.gen.randrange(span)
    400             self.assertTrue(0 <= r < span)
    401             cum |= r
    402         self.assertEqual(cum, span-1)
    403 
    404     def test_bigrand_ranges(self):
    405         for i in [40,80, 160, 200, 211, 250, 375, 512, 550]:
    406             start = self.gen.randrange(2 ** i)
    407             stop = self.gen.randrange(2 ** (i-2))
    408             if stop <= start:
    409                 return
    410             self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
    411 
    412     def test_rangelimits(self):
    413         for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
    414             self.assertEqual(set(range(start,stop)),
    415                 set([self.gen.randrange(start,stop) for i in xrange(100)]))
    416 
    417     def test_genrandbits(self):
    418         # Verify cross-platform repeatability
    419         self.gen.seed(1234567)
    420         self.assertEqual(self.gen.getrandbits(100),
    421                          97904845777343510404718956115L)
    422         # Verify ranges
    423         for k in xrange(1, 1000):
    424             self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
    425 
    426         # Verify all bits active
    427         getbits = self.gen.getrandbits
    428         for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]:
    429             cum = 0
    430             for i in xrange(100):
    431                 cum |= getbits(span)
    432             self.assertEqual(cum, 2**span-1)
    433 
    434         # Verify argument checking
    435         self.assertRaises(TypeError, self.gen.getrandbits)
    436         self.assertRaises(TypeError, self.gen.getrandbits, 'a')
    437         self.assertRaises(TypeError, self.gen.getrandbits, 1, 2)
    438         self.assertRaises(ValueError, self.gen.getrandbits, 0)
    439         self.assertRaises(ValueError, self.gen.getrandbits, -1)
    440 
    441     def test_randbelow_logic(self, _log=log, int=int):
    442         # check bitcount transition points:  2**i and 2**(i+1)-1
    443         # show that: k = int(1.001 + _log(n, 2))
    444         # is equal to or one greater than the number of bits in n
    445         for i in xrange(1, 1000):
    446             n = 1L << i # check an exact power of two
    447             numbits = i+1
    448             k = int(1.00001 + _log(n, 2))
    449             self.assertEqual(k, numbits)
    450             self.assertTrue(n == 2**(k-1))
    451 
    452             n += n - 1      # check 1 below the next power of two
    453             k = int(1.00001 + _log(n, 2))
    454             self.assertIn(k, [numbits, numbits+1])
    455             self.assertTrue(2**k > n > 2**(k-2))
    456 
    457             n -= n >> 15     # check a little farther below the next power of two
    458             k = int(1.00001 + _log(n, 2))
    459             self.assertEqual(k, numbits)        # note the stronger assertion
    460             self.assertTrue(2**k > n > 2**(k-1))   # note the stronger assertion
    461 
    462     def test_randrange_bug_1590891(self):
    463         start = 1000000000000
    464         stop = -100000000000000000000
    465         step = -200
    466         x = self.gen.randrange(start, stop, step)
    467         self.assertTrue(stop < x <= start)
    468         self.assertEqual((x+stop)%step, 0)
    469 
    470 def gamma(z, sqrt2pi=(2.0*pi)**0.5):
    471     # Reflection to right half of complex plane
    472     if z < 0.5:
    473         return pi / sin(pi*z) / gamma(1.0-z)
    474     # Lanczos approximation with g=7
    475     az = z + (7.0 - 0.5)
    476     return az ** (z-0.5) / exp(az) * sqrt2pi * fsum([
    477         0.9999999999995183,
    478         676.5203681218835 / z,
    479         -1259.139216722289 / (z+1.0),
    480         771.3234287757674 / (z+2.0),
    481         -176.6150291498386 / (z+3.0),
    482         12.50734324009056 / (z+4.0),
    483         -0.1385710331296526 / (z+5.0),
    484         0.9934937113930748e-05 / (z+6.0),
    485         0.1659470187408462e-06 / (z+7.0),
    486     ])
    487 
    488 class TestDistributions(unittest.TestCase):
    489     def test_zeroinputs(self):
    490         # Verify that distributions can handle a series of zero inputs'
    491         g = random.Random()
    492         x = [g.random() for i in xrange(50)] + [0.0]*5
    493         g.random = x[:].pop; g.uniform(1,10)
    494         g.random = x[:].pop; g.paretovariate(1.0)
    495         g.random = x[:].pop; g.expovariate(1.0)
    496         g.random = x[:].pop; g.weibullvariate(1.0, 1.0)
    497         g.random = x[:].pop; g.vonmisesvariate(1.0, 1.0)
    498         g.random = x[:].pop; g.normalvariate(0.0, 1.0)
    499         g.random = x[:].pop; g.gauss(0.0, 1.0)
    500         g.random = x[:].pop; g.lognormvariate(0.0, 1.0)
    501         g.random = x[:].pop; g.vonmisesvariate(0.0, 1.0)
    502         g.random = x[:].pop; g.gammavariate(0.01, 1.0)
    503         g.random = x[:].pop; g.gammavariate(1.0, 1.0)
    504         g.random = x[:].pop; g.gammavariate(200.0, 1.0)
    505         g.random = x[:].pop; g.betavariate(3.0, 3.0)
    506         g.random = x[:].pop; g.triangular(0.0, 1.0, 1.0/3.0)
    507 
    508     def test_avg_std(self):
    509         # Use integration to test distribution average and standard deviation.
    510         # Only works for distributions which do not consume variates in pairs
    511         g = random.Random()
    512         N = 5000
    513         x = [i/float(N) for i in xrange(1,N)]
    514         for variate, args, mu, sigmasqrd in [
    515                 (g.uniform, (1.0,10.0), (10.0+1.0)/2, (10.0-1.0)**2/12),
    516                 (g.triangular, (0.0, 1.0, 1.0/3.0), 4.0/9.0, 7.0/9.0/18.0),
    517                 (g.expovariate, (1.5,), 1/1.5, 1/1.5**2),
    518                 (g.vonmisesvariate, (1.23, 0), pi, pi**2/3),
    519                 (g.paretovariate, (5.0,), 5.0/(5.0-1),
    520                                   5.0/((5.0-1)**2*(5.0-2))),
    521                 (g.weibullvariate, (1.0, 3.0), gamma(1+1/3.0),
    522                                   gamma(1+2/3.0)-gamma(1+1/3.0)**2) ]:
    523             g.random = x[:].pop
    524             y = []
    525             for i in xrange(len(x)):
    526                 try:
    527                     y.append(variate(*args))
    528                 except IndexError:
    529                     pass
    530             s1 = s2 = 0
    531             for e in y:
    532                 s1 += e
    533                 s2 += (e - mu) ** 2
    534             N = len(y)
    535             self.assertAlmostEqual(s1/N, mu, places=2,
    536                                    msg='%s%r' % (variate.__name__, args))
    537             self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2,
    538                                    msg='%s%r' % (variate.__name__, args))
    539 
    540     def test_constant(self):
    541         g = random.Random()
    542         N = 100
    543         for variate, args, expected in [
    544                 (g.uniform, (10.0, 10.0), 10.0),
    545                 (g.triangular, (10.0, 10.0), 10.0),
    546                 #(g.triangular, (10.0, 10.0, 10.0), 10.0),
    547                 (g.expovariate, (float('inf'),), 0.0),
    548                 (g.vonmisesvariate, (3.0, float('inf')), 3.0),
    549                 (g.gauss, (10.0, 0.0), 10.0),
    550                 (g.lognormvariate, (0.0, 0.0), 1.0),
    551                 (g.lognormvariate, (-float('inf'), 0.0), 0.0),
    552                 (g.normalvariate, (10.0, 0.0), 10.0),
    553                 (g.paretovariate, (float('inf'),), 1.0),
    554                 (g.weibullvariate, (10.0, float('inf')), 10.0),
    555                 (g.weibullvariate, (0.0, 10.0), 0.0),
    556             ]:
    557             for i in range(N):
    558                 self.assertEqual(variate(*args), expected)
    559 
    560     def test_von_mises_range(self):
    561         # Issue 17149: von mises variates were not consistently in the
    562         # range [0, 2*PI].
    563         g = random.Random()
    564         N = 100
    565         for mu in 0.0, 0.1, 3.1, 6.2:
    566             for kappa in 0.0, 2.3, 500.0:
    567                 for _ in range(N):
    568                     sample = g.vonmisesvariate(mu, kappa)
    569                     self.assertTrue(
    570                         0 <= sample <= random.TWOPI,
    571                         msg=("vonmisesvariate({}, {}) produced a result {} out"
    572                              " of range [0, 2*pi]").format(mu, kappa, sample))
    573 
    574     def test_von_mises_large_kappa(self):
    575         # Issue #17141: vonmisesvariate() was hang for large kappas
    576         random.vonmisesvariate(0, 1e15)
    577         random.vonmisesvariate(0, 1e100)
    578 
    579 
    580 class TestModule(unittest.TestCase):
    581     def testMagicConstants(self):
    582         self.assertAlmostEqual(random.NV_MAGICCONST, 1.71552776992141)
    583         self.assertAlmostEqual(random.TWOPI, 6.28318530718)
    584         self.assertAlmostEqual(random.LOG4, 1.38629436111989)
    585         self.assertAlmostEqual(random.SG_MAGICCONST, 2.50407739677627)
    586 
    587     def test__all__(self):
    588         # tests validity but not completeness of the __all__ list
    589         self.assertTrue(set(random.__all__) <= set(dir(random)))
    590 
    591     def test_random_subclass_with_kwargs(self):
    592         # SF bug #1486663 -- this used to erroneously raise a TypeError
    593         class Subclass(random.Random):
    594             def __init__(self, newarg=None):
    595                 random.Random.__init__(self)
    596         Subclass(newarg=1)
    597 
    598 
    599 def test_main(verbose=None):
    600     testclasses =    [WichmannHill_TestBasicOps,
    601                       MersenneTwister_TestBasicOps,
    602                       TestDistributions,
    603                       TestModule]
    604 
    605     try:
    606         random.SystemRandom().random()
    607     except NotImplementedError:
    608         pass
    609     else:
    610         testclasses.append(SystemRandom_TestBasicOps)
    611 
    612     test_support.run_unittest(*testclasses)
    613 
    614     # verify reference counting
    615     import sys
    616     if verbose and hasattr(sys, "gettotalrefcount"):
    617         counts = [None] * 5
    618         for i in xrange(len(counts)):
    619             test_support.run_unittest(*testclasses)
    620             counts[i] = sys.gettotalrefcount()
    621         print counts
    622 
    623 if __name__ == "__main__":
    624     test_main(verbose=True)
    625