Home | History | Annotate | Download | only in test
      1 import unittest
      2 import sys
      3 
      4 import random
      5 import math
      6 
      7 from test import test_int, test_support
      8 
      9 # Used for lazy formatting of failure messages
     10 class Frm(object):
     11     def __init__(self, format, *args):
     12         self.format = format
     13         self.args = args
     14 
     15     def __str__(self):
     16         return self.format % self.args
     17 
     18 # SHIFT should match the value in longintrepr.h for best testing.
     19 SHIFT = sys.long_info.bits_per_digit
     20 BASE = 2 ** SHIFT
     21 MASK = BASE - 1
     22 KARATSUBA_CUTOFF = 70   # from longobject.c
     23 
     24 # Max number of base BASE digits to use in test cases.  Doubling
     25 # this will more than double the runtime.
     26 MAXDIGITS = 15
     27 
     28 # build some special values
     29 special = map(long, [0, 1, 2, BASE, BASE >> 1])
     30 special.append(0x5555555555555555L)
     31 special.append(0xaaaaaaaaaaaaaaaaL)
     32 #  some solid strings of one bits
     33 p2 = 4L  # 0 and 1 already added
     34 for i in range(2*SHIFT):
     35     special.append(p2 - 1)
     36     p2 = p2 << 1
     37 del p2
     38 # add complements & negations
     39 special = special + map(lambda x: ~x, special) + \
     40                     map(lambda x: -x, special)
     41 
     42 L = [
     43         ('0', 0),
     44         ('1', 1),
     45         ('9', 9),
     46         ('10', 10),
     47         ('99', 99),
     48         ('100', 100),
     49         ('314', 314),
     50         (' 314', 314),
     51         ('314 ', 314),
     52         ('  \t\t  314  \t\t  ', 314),
     53         (repr(sys.maxint), sys.maxint),
     54         ('  1x', ValueError),
     55         ('  1  ', 1),
     56         ('  1\02  ', ValueError),
     57         ('', ValueError),
     58         (' ', ValueError),
     59         ('  \t\t  ', ValueError)
     60 ]
     61 if test_support.have_unicode:
     62     L += [
     63         (unicode('0'), 0),
     64         (unicode('1'), 1),
     65         (unicode('9'), 9),
     66         (unicode('10'), 10),
     67         (unicode('99'), 99),
     68         (unicode('100'), 100),
     69         (unicode('314'), 314),
     70         (unicode(' 314'), 314),
     71         (unicode('\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
     72         (unicode('  \t\t  314  \t\t  '), 314),
     73         (unicode('  1x'), ValueError),
     74         (unicode('  1  '), 1),
     75         (unicode('  1\02  '), ValueError),
     76         (unicode(''), ValueError),
     77         (unicode(' '), ValueError),
     78         (unicode('  \t\t  '), ValueError),
     79         (unichr(0x200), ValueError),
     80 ]
     81 
     82 class LongSubclass(long):
     83     pass
     84 
     85 class OtherLongSubclass(long):
     86     pass
     87 
     88 class LongTest(test_int.IntLongCommonTests, unittest.TestCase):
     89 
     90     ntype = long
     91 
     92     # Get quasi-random long consisting of ndigits digits (in base BASE).
     93     # quasi == the most-significant digit will not be 0, and the number
     94     # is constructed to contain long strings of 0 and 1 bits.  These are
     95     # more likely than random bits to provoke digit-boundary errors.
     96     # The sign of the number is also random.
     97 
     98     def getran(self, ndigits):
     99         self.assertGreater(ndigits, 0)
    100         nbits_hi = ndigits * SHIFT
    101         nbits_lo = nbits_hi - SHIFT + 1
    102         answer = 0L
    103         nbits = 0
    104         r = int(random.random() * (SHIFT * 2)) | 1  # force 1 bits to start
    105         while nbits < nbits_lo:
    106             bits = (r >> 1) + 1
    107             bits = min(bits, nbits_hi - nbits)
    108             self.assertTrue(1 <= bits <= SHIFT)
    109             nbits = nbits + bits
    110             answer = answer << bits
    111             if r & 1:
    112                 answer = answer | ((1 << bits) - 1)
    113             r = int(random.random() * (SHIFT * 2))
    114         self.assertTrue(nbits_lo <= nbits <= nbits_hi)
    115         if random.random() < 0.5:
    116             answer = -answer
    117         return answer
    118 
    119     # Get random long consisting of ndigits random digits (relative to base
    120     # BASE).  The sign bit is also random.
    121 
    122     def getran2(ndigits):
    123         answer = 0L
    124         for i in xrange(ndigits):
    125             answer = (answer << SHIFT) | random.randint(0, MASK)
    126         if random.random() < 0.5:
    127             answer = -answer
    128         return answer
    129 
    130     def check_division(self, x, y):
    131         eq = self.assertEqual
    132         q, r = divmod(x, y)
    133         q2, r2 = x//y, x%y
    134         pab, pba = x*y, y*x
    135         eq(pab, pba, Frm("multiplication does not commute for %r and %r", x, y))
    136         eq(q, q2, Frm("divmod returns different quotient than / for %r and %r", x, y))
    137         eq(r, r2, Frm("divmod returns different mod than %% for %r and %r", x, y))
    138         eq(x, q*y + r, Frm("x != q*y + r after divmod on x=%r, y=%r", x, y))
    139         if y > 0:
    140             self.assertTrue(0 <= r < y, Frm("bad mod from divmod on %r and %r", x, y))
    141         else:
    142             self.assertTrue(y < r <= 0, Frm("bad mod from divmod on %r and %r", x, y))
    143 
    144     def test_division(self):
    145         digits = range(1, MAXDIGITS+1) + range(KARATSUBA_CUTOFF,
    146                                                KARATSUBA_CUTOFF + 14)
    147         digits.append(KARATSUBA_CUTOFF * 3)
    148         for lenx in digits:
    149             x = self.getran(lenx)
    150             for leny in digits:
    151                 y = self.getran(leny) or 1L
    152                 self.check_division(x, y)
    153 
    154         # specific numbers chosen to exercise corner cases of the
    155         # current long division implementation
    156 
    157         # 30-bit cases involving a quotient digit estimate of BASE+1
    158         self.check_division(1231948412290879395966702881L,
    159                             1147341367131428698L)
    160         self.check_division(815427756481275430342312021515587883L,
    161                        707270836069027745L)
    162         self.check_division(627976073697012820849443363563599041L,
    163                        643588798496057020L)
    164         self.check_division(1115141373653752303710932756325578065L,
    165                        1038556335171453937726882627L)
    166         # 30-bit cases that require the post-subtraction correction step
    167         self.check_division(922498905405436751940989320930368494L,
    168                        949985870686786135626943396L)
    169         self.check_division(768235853328091167204009652174031844L,
    170                        1091555541180371554426545266L)
    171 
    172         # 15-bit cases involving a quotient digit estimate of BASE+1
    173         self.check_division(20172188947443L, 615611397L)
    174         self.check_division(1020908530270155025L, 950795710L)
    175         self.check_division(128589565723112408L, 736393718L)
    176         self.check_division(609919780285761575L, 18613274546784L)
    177         # 15-bit cases that require the post-subtraction correction step
    178         self.check_division(710031681576388032L, 26769404391308L)
    179         self.check_division(1933622614268221L, 30212853348836L)
    180 
    181 
    182 
    183     def test_karatsuba(self):
    184         digits = range(1, 5) + range(KARATSUBA_CUTOFF, KARATSUBA_CUTOFF + 10)
    185         digits.extend([KARATSUBA_CUTOFF * 10, KARATSUBA_CUTOFF * 100])
    186 
    187         bits = [digit * SHIFT for digit in digits]
    188 
    189         # Test products of long strings of 1 bits -- (2**x-1)*(2**y-1) ==
    190         # 2**(x+y) - 2**x - 2**y + 1, so the proper result is easy to check.
    191         for abits in bits:
    192             a = (1L << abits) - 1
    193             for bbits in bits:
    194                 if bbits < abits:
    195                     continue
    196                 b = (1L << bbits) - 1
    197                 x = a * b
    198                 y = ((1L << (abits + bbits)) -
    199                      (1L << abits) -
    200                      (1L << bbits) +
    201                      1)
    202                 self.assertEqual(x, y,
    203                     Frm("bad result for a*b: a=%r, b=%r, x=%r, y=%r", a, b, x, y))
    204 
    205     def test_lshift_of_zero(self):
    206         self.assertEqual(0L << 0, 0)
    207         self.assertEqual(0L << 10, 0)
    208         with self.assertRaises(ValueError):
    209             0L << -1
    210 
    211     @test_support.cpython_only
    212     def test_huge_lshift_of_zero(self):
    213         # Shouldn't try to allocate memory for a huge shift. See issue #27870.
    214         # Other implementations may have a different boundary for overflow,
    215         # or not raise at all.
    216         self.assertEqual(0L << sys.maxsize, 0)
    217         with self.assertRaises(OverflowError):
    218             0L << (sys.maxsize + 1)
    219 
    220     def check_bitop_identities_1(self, x):
    221         eq = self.assertEqual
    222         eq(x & 0, 0, Frm("x & 0 != 0 for x=%r", x))
    223         eq(x | 0, x, Frm("x | 0 != x for x=%r", x))
    224         eq(x ^ 0, x, Frm("x ^ 0 != x for x=%r", x))
    225         eq(x & -1, x, Frm("x & -1 != x for x=%r", x))
    226         eq(x | -1, -1, Frm("x | -1 != -1 for x=%r", x))
    227         eq(x ^ -1, ~x, Frm("x ^ -1 != ~x for x=%r", x))
    228         eq(x, ~~x, Frm("x != ~~x for x=%r", x))
    229         eq(x & x, x, Frm("x & x != x for x=%r", x))
    230         eq(x | x, x, Frm("x | x != x for x=%r", x))
    231         eq(x ^ x, 0, Frm("x ^ x != 0 for x=%r", x))
    232         eq(x & ~x, 0, Frm("x & ~x != 0 for x=%r", x))
    233         eq(x | ~x, -1, Frm("x | ~x != -1 for x=%r", x))
    234         eq(x ^ ~x, -1, Frm("x ^ ~x != -1 for x=%r", x))
    235         eq(-x, 1 + ~x, Frm("not -x == 1 + ~x for x=%r", x))
    236         eq(-x, ~(x-1), Frm("not -x == ~(x-1) forx =%r", x))
    237         for n in xrange(2*SHIFT):
    238             p2 = 2L ** n
    239             eq(x << n >> n, x,
    240                 Frm("x << n >> n != x for x=%r, n=%r", x, n))
    241             eq(x // p2, x >> n,
    242                 Frm("x // p2 != x >> n for x=%r n=%r p2=%r", x, n, p2))
    243             eq(x * p2, x << n,
    244                 Frm("x * p2 != x << n for x=%r n=%r p2=%r", x, n, p2))
    245             eq(x & -p2, x >> n << n,
    246                 Frm("not x & -p2 == x >> n << n for x=%r n=%r p2=%r", x, n, p2))
    247             eq(x & -p2, x & ~(p2 - 1),
    248                 Frm("not x & -p2 == x & ~(p2 - 1) for x=%r n=%r p2=%r", x, n, p2))
    249 
    250     def check_bitop_identities_2(self, x, y):
    251         eq = self.assertEqual
    252         eq(x & y, y & x, Frm("x & y != y & x for x=%r, y=%r", x, y))
    253         eq(x | y, y | x, Frm("x | y != y | x for x=%r, y=%r", x, y))
    254         eq(x ^ y, y ^ x, Frm("x ^ y != y ^ x for x=%r, y=%r", x, y))
    255         eq(x ^ y ^ x, y, Frm("x ^ y ^ x != y for x=%r, y=%r", x, y))
    256         eq(x & y, ~(~x | ~y), Frm("x & y != ~(~x | ~y) for x=%r, y=%r", x, y))
    257         eq(x | y, ~(~x & ~y), Frm("x | y != ~(~x & ~y) for x=%r, y=%r", x, y))
    258         eq(x ^ y, (x | y) & ~(x & y),
    259              Frm("x ^ y != (x | y) & ~(x & y) for x=%r, y=%r", x, y))
    260         eq(x ^ y, (x & ~y) | (~x & y),
    261              Frm("x ^ y == (x & ~y) | (~x & y) for x=%r, y=%r", x, y))
    262         eq(x ^ y, (x | y) & (~x | ~y),
    263              Frm("x ^ y == (x | y) & (~x | ~y) for x=%r, y=%r", x, y))
    264 
    265     def check_bitop_identities_3(self, x, y, z):
    266         eq = self.assertEqual
    267         eq((x & y) & z, x & (y & z),
    268              Frm("(x & y) & z != x & (y & z) for x=%r, y=%r, z=%r", x, y, z))
    269         eq((x | y) | z, x | (y | z),
    270              Frm("(x | y) | z != x | (y | z) for x=%r, y=%r, z=%r", x, y, z))
    271         eq((x ^ y) ^ z, x ^ (y ^ z),
    272              Frm("(x ^ y) ^ z != x ^ (y ^ z) for x=%r, y=%r, z=%r", x, y, z))
    273         eq(x & (y | z), (x & y) | (x & z),
    274              Frm("x & (y | z) != (x & y) | (x & z) for x=%r, y=%r, z=%r", x, y, z))
    275         eq(x | (y & z), (x | y) & (x | z),
    276              Frm("x | (y & z) != (x | y) & (x | z) for x=%r, y=%r, z=%r", x, y, z))
    277 
    278     def test_bitop_identities(self):
    279         for x in special:
    280             self.check_bitop_identities_1(x)
    281         digits = xrange(1, MAXDIGITS+1)
    282         for lenx in digits:
    283             x = self.getran(lenx)
    284             self.check_bitop_identities_1(x)
    285             for leny in digits:
    286                 y = self.getran(leny)
    287                 self.check_bitop_identities_2(x, y)
    288                 self.check_bitop_identities_3(x, y, self.getran((lenx + leny)//2))
    289 
    290     def slow_format(self, x, base):
    291         if (x, base) == (0, 8):
    292             # this is an oddball!
    293             return "0L"
    294         digits = []
    295         sign = 0
    296         if x < 0:
    297             sign, x = 1, -x
    298         while x:
    299             x, r = divmod(x, base)
    300             digits.append(int(r))
    301         digits.reverse()
    302         digits = digits or [0]
    303         return '-'[:sign] + \
    304                {8: '0', 10: '', 16: '0x'}[base] + \
    305                "".join(map(lambda i: "0123456789abcdef"[i], digits)) + "L"
    306 
    307     def check_format_1(self, x):
    308         for base, mapper in (8, oct), (10, repr), (16, hex):
    309             got = mapper(x)
    310             expected = self.slow_format(x, base)
    311             msg = Frm("%s returned %r but expected %r for %r",
    312                 mapper.__name__, got, expected, x)
    313             self.assertEqual(got, expected, msg)
    314             self.assertEqual(long(got, 0), x, Frm('long("%s", 0) != %r', got, x))
    315         # str() has to be checked a little differently since there's no
    316         # trailing "L"
    317         got = str(x)
    318         expected = self.slow_format(x, 10)[:-1]
    319         msg = Frm("%s returned %r but expected %r for %r",
    320             mapper.__name__, got, expected, x)
    321         self.assertEqual(got, expected, msg)
    322 
    323     def test_format(self):
    324         for x in special:
    325             self.check_format_1(x)
    326         for i in xrange(10):
    327             for lenx in xrange(1, MAXDIGITS+1):
    328                 x = self.getran(lenx)
    329                 self.check_format_1(x)
    330 
    331     def test_long(self):
    332         self.assertEqual(long(314), 314L)
    333         self.assertEqual(long(3.14), 3L)
    334         self.assertEqual(long(314L), 314L)
    335         # Check that long() of basic types actually returns a long
    336         self.assertEqual(type(long(314)), long)
    337         self.assertEqual(type(long(3.14)), long)
    338         self.assertEqual(type(long(314L)), long)
    339         # Check that conversion from float truncates towards zero
    340         self.assertEqual(long(-3.14), -3L)
    341         self.assertEqual(long(3.9), 3L)
    342         self.assertEqual(long(-3.9), -3L)
    343         self.assertEqual(long(3.5), 3L)
    344         self.assertEqual(long(-3.5), -3L)
    345         self.assertEqual(long("-3"), -3L)
    346         self.assertEqual(long("0b10", 2), 2L)
    347         self.assertEqual(long("0o10", 8), 8L)
    348         self.assertEqual(long("0x10", 16), 16L)
    349         if test_support.have_unicode:
    350             self.assertEqual(long(unicode("-3")), -3L)
    351         # Different base:
    352         self.assertEqual(long("10",16), 16L)
    353         if test_support.have_unicode:
    354             self.assertEqual(long(unicode("10"),16), 16L)
    355         # Check conversions from string (same test set as for int(), and then some)
    356         LL = [
    357                 ('1' + '0'*20, 10L**20),
    358                 ('1' + '0'*100, 10L**100)
    359         ]
    360         L2 = L[:]
    361         if test_support.have_unicode:
    362             L2 += [
    363                 (unicode('1') + unicode('0')*20, 10L**20),
    364                 (unicode('1') + unicode('0')*100, 10L**100),
    365         ]
    366         for s, v in L2 + LL:
    367             for sign in "", "+", "-":
    368                 for prefix in "", " ", "\t", "  \t\t  ":
    369                     ss = prefix + sign + s
    370                     vv = v
    371                     if sign == "-" and v is not ValueError:
    372                         vv = -v
    373                     try:
    374                         self.assertEqual(long(ss), long(vv))
    375                     except v:
    376                         pass
    377 
    378         self.assertRaises(ValueError, long, '123\0')
    379         self.assertRaises(ValueError, long, '53', 40)
    380         self.assertRaises(TypeError, long, 1, 12)
    381 
    382         # tests with base 0
    383         self.assertEqual(long(' 0123  ', 0), 83)
    384         self.assertEqual(long(' 0123  ', 0), 83)
    385         self.assertEqual(long('000', 0), 0)
    386         self.assertEqual(long('0o123', 0), 83)
    387         self.assertEqual(long('0x123', 0), 291)
    388         self.assertEqual(long('0b100', 0), 4)
    389         self.assertEqual(long(' 0O123   ', 0), 83)
    390         self.assertEqual(long(' 0X123  ', 0), 291)
    391         self.assertEqual(long(' 0B100 ', 0), 4)
    392         self.assertEqual(long('0', 0), 0)
    393         self.assertEqual(long('+0', 0), 0)
    394         self.assertEqual(long('-0', 0), 0)
    395         self.assertEqual(long('00', 0), 0)
    396         self.assertRaises(ValueError, long, '08', 0)
    397         self.assertRaises(ValueError, long, '-012395', 0)
    398 
    399         # SF patch #1638879: embedded NULs were not detected with
    400         # explicit base
    401         self.assertRaises(ValueError, long, '123\0', 10)
    402         self.assertRaises(ValueError, long, '123\x00 245', 20)
    403 
    404         self.assertEqual(long('100000000000000000000000000000000', 2),
    405                          4294967296)
    406         self.assertEqual(long('102002022201221111211', 3), 4294967296)
    407         self.assertEqual(long('10000000000000000', 4), 4294967296)
    408         self.assertEqual(long('32244002423141', 5), 4294967296)
    409         self.assertEqual(long('1550104015504', 6), 4294967296)
    410         self.assertEqual(long('211301422354', 7), 4294967296)
    411         self.assertEqual(long('40000000000', 8), 4294967296)
    412         self.assertEqual(long('12068657454', 9), 4294967296)
    413         self.assertEqual(long('4294967296', 10), 4294967296)
    414         self.assertEqual(long('1904440554', 11), 4294967296)
    415         self.assertEqual(long('9ba461594', 12), 4294967296)
    416         self.assertEqual(long('535a79889', 13), 4294967296)
    417         self.assertEqual(long('2ca5b7464', 14), 4294967296)
    418         self.assertEqual(long('1a20dcd81', 15), 4294967296)
    419         self.assertEqual(long('100000000', 16), 4294967296)
    420         self.assertEqual(long('a7ffda91', 17), 4294967296)
    421         self.assertEqual(long('704he7g4', 18), 4294967296)
    422         self.assertEqual(long('4f5aff66', 19), 4294967296)
    423         self.assertEqual(long('3723ai4g', 20), 4294967296)
    424         self.assertEqual(long('281d55i4', 21), 4294967296)
    425         self.assertEqual(long('1fj8b184', 22), 4294967296)
    426         self.assertEqual(long('1606k7ic', 23), 4294967296)
    427         self.assertEqual(long('mb994ag', 24), 4294967296)
    428         self.assertEqual(long('hek2mgl', 25), 4294967296)
    429         self.assertEqual(long('dnchbnm', 26), 4294967296)
    430         self.assertEqual(long('b28jpdm', 27), 4294967296)
    431         self.assertEqual(long('8pfgih4', 28), 4294967296)
    432         self.assertEqual(long('76beigg', 29), 4294967296)
    433         self.assertEqual(long('5qmcpqg', 30), 4294967296)
    434         self.assertEqual(long('4q0jto4', 31), 4294967296)
    435         self.assertEqual(long('4000000', 32), 4294967296)
    436         self.assertEqual(long('3aokq94', 33), 4294967296)
    437         self.assertEqual(long('2qhxjli', 34), 4294967296)
    438         self.assertEqual(long('2br45qb', 35), 4294967296)
    439         self.assertEqual(long('1z141z4', 36), 4294967296)
    440 
    441         self.assertEqual(long('100000000000000000000000000000001', 2),
    442                          4294967297)
    443         self.assertEqual(long('102002022201221111212', 3), 4294967297)
    444         self.assertEqual(long('10000000000000001', 4), 4294967297)
    445         self.assertEqual(long('32244002423142', 5), 4294967297)
    446         self.assertEqual(long('1550104015505', 6), 4294967297)
    447         self.assertEqual(long('211301422355', 7), 4294967297)
    448         self.assertEqual(long('40000000001', 8), 4294967297)
    449         self.assertEqual(long('12068657455', 9), 4294967297)
    450         self.assertEqual(long('4294967297', 10), 4294967297)
    451         self.assertEqual(long('1904440555', 11), 4294967297)
    452         self.assertEqual(long('9ba461595', 12), 4294967297)
    453         self.assertEqual(long('535a7988a', 13), 4294967297)
    454         self.assertEqual(long('2ca5b7465', 14), 4294967297)
    455         self.assertEqual(long('1a20dcd82', 15), 4294967297)
    456         self.assertEqual(long('100000001', 16), 4294967297)
    457         self.assertEqual(long('a7ffda92', 17), 4294967297)
    458         self.assertEqual(long('704he7g5', 18), 4294967297)
    459         self.assertEqual(long('4f5aff67', 19), 4294967297)
    460         self.assertEqual(long('3723ai4h', 20), 4294967297)
    461         self.assertEqual(long('281d55i5', 21), 4294967297)
    462         self.assertEqual(long('1fj8b185', 22), 4294967297)
    463         self.assertEqual(long('1606k7id', 23), 4294967297)
    464         self.assertEqual(long('mb994ah', 24), 4294967297)
    465         self.assertEqual(long('hek2mgm', 25), 4294967297)
    466         self.assertEqual(long('dnchbnn', 26), 4294967297)
    467         self.assertEqual(long('b28jpdn', 27), 4294967297)
    468         self.assertEqual(long('8pfgih5', 28), 4294967297)
    469         self.assertEqual(long('76beigh', 29), 4294967297)
    470         self.assertEqual(long('5qmcpqh', 30), 4294967297)
    471         self.assertEqual(long('4q0jto5', 31), 4294967297)
    472         self.assertEqual(long('4000001', 32), 4294967297)
    473         self.assertEqual(long('3aokq95', 33), 4294967297)
    474         self.assertEqual(long('2qhxjlj', 34), 4294967297)
    475         self.assertEqual(long('2br45qc', 35), 4294967297)
    476         self.assertEqual(long('1z141z5', 36), 4294967297)
    477 
    478 
    479     def test_conversion(self):
    480         # Test __long__()
    481         class ClassicMissingMethods:
    482             pass
    483         self.assertRaises(AttributeError, long, ClassicMissingMethods())
    484 
    485         class MissingMethods(object):
    486             pass
    487         self.assertRaises(TypeError, long, MissingMethods())
    488 
    489         class Foo0:
    490             def __long__(self):
    491                 return 42L
    492 
    493         class Foo1(object):
    494             def __long__(self):
    495                 return 42L
    496 
    497         class Foo2(long):
    498             def __long__(self):
    499                 return 42L
    500 
    501         class Foo3(long):
    502             def __long__(self):
    503                 return self
    504 
    505         class Foo4(long):
    506             def __long__(self):
    507                 return 42
    508 
    509         class Foo5(long):
    510             def __long__(self):
    511                 return 42.
    512 
    513         self.assertEqual(long(Foo0()), 42L)
    514         self.assertEqual(long(Foo1()), 42L)
    515         self.assertEqual(long(Foo2()), 42L)
    516         self.assertEqual(long(Foo3()), 0)
    517         self.assertEqual(long(Foo4()), 42)
    518         self.assertRaises(TypeError, long, Foo5())
    519 
    520         class Classic:
    521             pass
    522         for base in (object, Classic):
    523             class LongOverridesTrunc(base):
    524                 def __long__(self):
    525                     return 42
    526                 def __trunc__(self):
    527                     return -12
    528             self.assertEqual(long(LongOverridesTrunc()), 42)
    529 
    530             class JustTrunc(base):
    531                 def __trunc__(self):
    532                     return 42
    533             self.assertEqual(long(JustTrunc()), 42)
    534 
    535             for trunc_result_base in (object, Classic):
    536                 class Integral(trunc_result_base):
    537                     def __int__(self):
    538                         return 42
    539 
    540                 class TruncReturnsNonLong(base):
    541                     def __trunc__(self):
    542                         return Integral()
    543                 self.assertEqual(long(TruncReturnsNonLong()), 42)
    544 
    545                 class NonIntegral(trunc_result_base):
    546                     def __trunc__(self):
    547                         # Check that we avoid infinite recursion.
    548                         return NonIntegral()
    549 
    550                 class TruncReturnsNonIntegral(base):
    551                     def __trunc__(self):
    552                         return NonIntegral()
    553                 try:
    554                     long(TruncReturnsNonIntegral())
    555                 except TypeError as e:
    556                     self.assertEqual(str(e),
    557                                      "__trunc__ returned non-Integral"
    558                                      " (type NonIntegral)")
    559                 else:
    560                     self.fail("Failed to raise TypeError with %s" %
    561                               ((base, trunc_result_base),))
    562 
    563                 class TruncReturnsLongSubclass(base):
    564                     def __long__(self):
    565                         return OtherLongSubclass(42L)
    566                 good_int = TruncReturnsLongSubclass()
    567                 n = long(good_int)
    568                 self.assertEqual(n, 42L)
    569                 self.assertIs(type(n), OtherLongSubclass)
    570                 n = LongSubclass(good_int)
    571                 self.assertEqual(n, 42L)
    572                 self.assertIs(type(n), LongSubclass)
    573 
    574     def test_misc(self):
    575 
    576         # check the extremes in int<->long conversion
    577         hugepos = sys.maxint
    578         hugeneg = -hugepos - 1
    579         hugepos_aslong = long(hugepos)
    580         hugeneg_aslong = long(hugeneg)
    581         self.assertEqual(hugepos, hugepos_aslong, "long(sys.maxint) != sys.maxint")
    582         self.assertEqual(hugeneg, hugeneg_aslong,
    583             "long(-sys.maxint-1) != -sys.maxint-1")
    584 
    585         # long -> int should not fail for hugepos_aslong or hugeneg_aslong
    586         x = int(hugepos_aslong)
    587         try:
    588             self.assertEqual(x, hugepos,
    589                   "converting sys.maxint to long and back to int fails")
    590         except OverflowError:
    591             self.fail("int(long(sys.maxint)) overflowed!")
    592         if not isinstance(x, int):
    593             self.fail("int(long(sys.maxint)) should have returned int")
    594         x = int(hugeneg_aslong)
    595         try:
    596             self.assertEqual(x, hugeneg,
    597                   "converting -sys.maxint-1 to long and back to int fails")
    598         except OverflowError:
    599             self.fail("int(long(-sys.maxint-1)) overflowed!")
    600         if not isinstance(x, int):
    601             self.fail("int(long(-sys.maxint-1)) should have returned int")
    602         # but long -> int should overflow for hugepos+1 and hugeneg-1
    603         x = hugepos_aslong + 1
    604         try:
    605             y = int(x)
    606         except OverflowError:
    607             self.fail("int(long(sys.maxint) + 1) mustn't overflow")
    608         self.assertIsInstance(y, long,
    609             "int(long(sys.maxint) + 1) should have returned long")
    610 
    611         x = hugeneg_aslong - 1
    612         try:
    613             y = int(x)
    614         except OverflowError:
    615             self.fail("int(long(-sys.maxint-1) - 1) mustn't overflow")
    616         self.assertIsInstance(y, long,
    617                "int(long(-sys.maxint-1) - 1) should have returned long")
    618 
    619         class long2(long):
    620             pass
    621         x = long2(1L<<100)
    622         y = int(x)
    623         self.assertIs(type(y), long,
    624             "overflowing int conversion must return long not long subtype")
    625 
    626         # long -> Py_ssize_t conversion
    627         class X(object):
    628             def __getslice__(self, i, j):
    629                 return i, j
    630 
    631         with test_support.check_py3k_warnings():
    632             self.assertEqual(X()[-5L:7L], (-5, 7))
    633             # use the clamping effect to test the smallest and largest longs
    634             # that fit a Py_ssize_t
    635             slicemin, slicemax = X()[-2L**100:2L**100]
    636             self.assertEqual(X()[slicemin:slicemax], (slicemin, slicemax))
    637 
    638     def test_issue9869(self):
    639         # Issue 9869: Interpreter crash when initializing an instance
    640         # of a long subclass from an object whose __long__ method returns
    641         # a plain int.
    642         class BadLong(object):
    643             def __long__(self):
    644                 return 1000000
    645 
    646         class MyLong(long):
    647             pass
    648 
    649         x = MyLong(BadLong())
    650         self.assertIsInstance(x, long)
    651         self.assertEqual(x, 1000000)
    652 
    653 
    654 # ----------------------------------- tests of auto int->long conversion
    655 
    656     def test_auto_overflow(self):
    657         special = [0, 1, 2, 3, sys.maxint-1, sys.maxint, sys.maxint+1]
    658         sqrt = int(math.sqrt(sys.maxint))
    659         special.extend([sqrt-1, sqrt, sqrt+1])
    660         special.extend([-i for i in special])
    661 
    662         def checkit(*args):
    663             # Heavy use of nested scopes here!
    664             self.assertEqual(got, expected,
    665                 Frm("for %r expected %r got %r", args, expected, got))
    666 
    667         for x in special:
    668             longx = long(x)
    669 
    670             expected = -longx
    671             got = -x
    672             checkit('-', x)
    673 
    674             for y in special:
    675                 longy = long(y)
    676 
    677                 expected = longx + longy
    678                 got = x + y
    679                 checkit(x, '+', y)
    680 
    681                 expected = longx - longy
    682                 got = x - y
    683                 checkit(x, '-', y)
    684 
    685                 expected = longx * longy
    686                 got = x * y
    687                 checkit(x, '*', y)
    688 
    689                 if y:
    690                     with test_support.check_py3k_warnings():
    691                         expected = longx / longy
    692                         got = x / y
    693                     checkit(x, '/', y)
    694 
    695                     expected = longx // longy
    696                     got = x // y
    697                     checkit(x, '//', y)
    698 
    699                     expected = divmod(longx, longy)
    700                     got = divmod(longx, longy)
    701                     checkit(x, 'divmod', y)
    702 
    703                 if abs(y) < 5 and not (x == 0 and y < 0):
    704                     expected = longx ** longy
    705                     got = x ** y
    706                     checkit(x, '**', y)
    707 
    708                     for z in special:
    709                         if z != 0 :
    710                             if y >= 0:
    711                                 expected = pow(longx, longy, long(z))
    712                                 got = pow(x, y, z)
    713                                 checkit('pow', x, y, '%', z)
    714                             else:
    715                                 self.assertRaises(TypeError, pow,longx, longy, long(z))
    716 
    717     @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
    718                          "test requires IEEE 754 doubles")
    719     def test_float_conversion(self):
    720         import sys
    721         DBL_MAX = sys.float_info.max
    722         DBL_MAX_EXP = sys.float_info.max_exp
    723         DBL_MANT_DIG = sys.float_info.mant_dig
    724 
    725         exact_values = [0L, 1L, 2L,
    726                          long(2**53-3),
    727                          long(2**53-2),
    728                          long(2**53-1),
    729                          long(2**53),
    730                          long(2**53+2),
    731                          long(2**54-4),
    732                          long(2**54-2),
    733                          long(2**54),
    734                          long(2**54+4)]
    735         for x in exact_values:
    736             self.assertEqual(long(float(x)), x)
    737             self.assertEqual(long(float(-x)), -x)
    738 
    739         # test round-half-even
    740         for x, y in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]:
    741             for p in xrange(15):
    742                 self.assertEqual(long(float(2L**p*(2**53+x))), 2L**p*(2**53+y))
    743 
    744         for x, y in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8),
    745                      (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12),
    746                      (13, 12), (14, 16), (15, 16)]:
    747             for p in xrange(15):
    748                 self.assertEqual(long(float(2L**p*(2**54+x))), 2L**p*(2**54+y))
    749 
    750         # behaviour near extremes of floating-point range
    751         long_dbl_max = long(DBL_MAX)
    752         top_power = 2**DBL_MAX_EXP
    753         halfway = (long_dbl_max + top_power)//2
    754         self.assertEqual(float(long_dbl_max), DBL_MAX)
    755         self.assertEqual(float(long_dbl_max+1), DBL_MAX)
    756         self.assertEqual(float(halfway-1), DBL_MAX)
    757         self.assertRaises(OverflowError, float, halfway)
    758         self.assertEqual(float(1-halfway), -DBL_MAX)
    759         self.assertRaises(OverflowError, float, -halfway)
    760         self.assertRaises(OverflowError, float, top_power-1)
    761         self.assertRaises(OverflowError, float, top_power)
    762         self.assertRaises(OverflowError, float, top_power+1)
    763         self.assertRaises(OverflowError, float, 2*top_power-1)
    764         self.assertRaises(OverflowError, float, 2*top_power)
    765         self.assertRaises(OverflowError, float, top_power*top_power)
    766 
    767         for p in xrange(100):
    768             x = long(2**p * (2**53 + 1) + 1)
    769             y = long(2**p * (2**53+ 2))
    770             self.assertEqual(long(float(x)), y)
    771 
    772             x = long(2**p * (2**53 + 1))
    773             y = long(2**p * 2**53)
    774             self.assertEqual(long(float(x)), y)
    775 
    776     def test_float_overflow(self):
    777         for x in -2.0, -1.0, 0.0, 1.0, 2.0:
    778             self.assertEqual(float(long(x)), x)
    779 
    780         shuge = '12345' * 120
    781         huge = 1L << 30000
    782         mhuge = -huge
    783         namespace = {'huge': huge, 'mhuge': mhuge, 'shuge': shuge, 'math': math}
    784         for test in ["float(huge)", "float(mhuge)",
    785                      "complex(huge)", "complex(mhuge)",
    786                      "complex(huge, 1)", "complex(mhuge, 1)",
    787                      "complex(1, huge)", "complex(1, mhuge)",
    788                      "1. + huge", "huge + 1.", "1. + mhuge", "mhuge + 1.",
    789                      "1. - huge", "huge - 1.", "1. - mhuge", "mhuge - 1.",
    790                      "1. * huge", "huge * 1.", "1. * mhuge", "mhuge * 1.",
    791                      "1. // huge", "huge // 1.", "1. // mhuge", "mhuge // 1.",
    792                      "1. / huge", "huge / 1.", "1. / mhuge", "mhuge / 1.",
    793                      "1. ** huge", "huge ** 1.", "1. ** mhuge", "mhuge ** 1.",
    794                      "math.sin(huge)", "math.sin(mhuge)",
    795                      "math.sqrt(huge)", "math.sqrt(mhuge)", # should do better
    796                      "math.floor(huge)", "math.floor(mhuge)"]:
    797 
    798             self.assertRaises(OverflowError, eval, test, namespace)
    799 
    800             # XXX Perhaps float(shuge) can raise OverflowError on some box?
    801             # The comparison should not.
    802             self.assertNotEqual(float(shuge), int(shuge),
    803                 "float(shuge) should not equal int(shuge)")
    804 
    805     def test_logs(self):
    806         LOG10E = math.log10(math.e)
    807 
    808         for exp in range(10) + [100, 1000, 10000]:
    809             value = 10 ** exp
    810             log10 = math.log10(value)
    811             self.assertAlmostEqual(log10, exp)
    812 
    813             # log10(value) == exp, so log(value) == log10(value)/log10(e) ==
    814             # exp/LOG10E
    815             expected = exp / LOG10E
    816             log = math.log(value)
    817             self.assertAlmostEqual(log, expected)
    818 
    819         for bad in -(1L << 10000), -2L, 0L:
    820             self.assertRaises(ValueError, math.log, bad)
    821             self.assertRaises(ValueError, math.log10, bad)
    822 
    823     def test_mixed_compares(self):
    824         eq = self.assertEqual
    825 
    826         # We're mostly concerned with that mixing floats and longs does the
    827         # right stuff, even when longs are too large to fit in a float.
    828         # The safest way to check the results is to use an entirely different
    829         # method, which we do here via a skeletal rational class (which
    830         # represents all Python ints, longs and floats exactly).
    831         class Rat:
    832             def __init__(self, value):
    833                 if isinstance(value, (int, long)):
    834                     self.n = value
    835                     self.d = 1
    836                 elif isinstance(value, float):
    837                     # Convert to exact rational equivalent.
    838                     f, e = math.frexp(abs(value))
    839                     assert f == 0 or 0.5 <= f < 1.0
    840                     # |value| = f * 2**e exactly
    841 
    842                     # Suck up CHUNK bits at a time; 28 is enough so that we suck
    843                     # up all bits in 2 iterations for all known binary double-
    844                     # precision formats, and small enough to fit in an int.
    845                     CHUNK = 28
    846                     top = 0
    847                     # invariant: |value| = (top + f) * 2**e exactly
    848                     while f:
    849                         f = math.ldexp(f, CHUNK)
    850                         digit = int(f)
    851                         assert digit >> CHUNK == 0
    852                         top = (top << CHUNK) | digit
    853                         f -= digit
    854                         assert 0.0 <= f < 1.0
    855                         e -= CHUNK
    856 
    857                     # Now |value| = top * 2**e exactly.
    858                     if e >= 0:
    859                         n = top << e
    860                         d = 1
    861                     else:
    862                         n = top
    863                         d = 1 << -e
    864                     if value < 0:
    865                         n = -n
    866                     self.n = n
    867                     self.d = d
    868                     assert float(n) / float(d) == value
    869                 else:
    870                     raise TypeError("can't deal with %r" % value)
    871 
    872             def __cmp__(self, other):
    873                 if not isinstance(other, Rat):
    874                     other = Rat(other)
    875                 return cmp(self.n * other.d, self.d * other.n)
    876 
    877         cases = [0, 0.001, 0.99, 1.0, 1.5, 1e20, 1e200]
    878         # 2**48 is an important boundary in the internals.  2**53 is an
    879         # important boundary for IEEE double precision.
    880         for t in 2.0**48, 2.0**50, 2.0**53:
    881             cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0,
    882                           long(t-1), long(t), long(t+1)])
    883         cases.extend([0, 1, 2, sys.maxint, float(sys.maxint)])
    884         # 1L<<20000 should exceed all double formats.  long(1e200) is to
    885         # check that we get equality with 1e200 above.
    886         t = long(1e200)
    887         cases.extend([0L, 1L, 2L, 1L << 20000, t-1, t, t+1])
    888         cases.extend([-x for x in cases])
    889         for x in cases:
    890             Rx = Rat(x)
    891             for y in cases:
    892                 Ry = Rat(y)
    893                 Rcmp = cmp(Rx, Ry)
    894                 xycmp = cmp(x, y)
    895                 eq(Rcmp, xycmp, Frm("%r %r %d %d", x, y, Rcmp, xycmp))
    896                 eq(x == y, Rcmp == 0, Frm("%r == %r %d", x, y, Rcmp))
    897                 eq(x != y, Rcmp != 0, Frm("%r != %r %d", x, y, Rcmp))
    898                 eq(x < y, Rcmp < 0, Frm("%r < %r %d", x, y, Rcmp))
    899                 eq(x <= y, Rcmp <= 0, Frm("%r <= %r %d", x, y, Rcmp))
    900                 eq(x > y, Rcmp > 0, Frm("%r > %r %d", x, y, Rcmp))
    901                 eq(x >= y, Rcmp >= 0, Frm("%r >= %r %d", x, y, Rcmp))
    902 
    903     def test_nan_inf(self):
    904         self.assertRaises(OverflowError, long, float('inf'))
    905         self.assertRaises(OverflowError, long, float('-inf'))
    906         self.assertRaises(ValueError, long, float('nan'))
    907 
    908     def test_bit_length(self):
    909         tiny = 1e-10
    910         for x in xrange(-65000, 65000):
    911             x = long(x)
    912             k = x.bit_length()
    913             # Check equivalence with Python version
    914             self.assertEqual(k, len(bin(x).lstrip('-0b')))
    915             # Behaviour as specified in the docs
    916             if x != 0:
    917                 self.assertTrue(2**(k-1) <= abs(x) < 2**k)
    918             else:
    919                 self.assertEqual(k, 0)
    920             # Alternative definition: x.bit_length() == 1 + floor(log_2(x))
    921             if x != 0:
    922                 # When x is an exact power of 2, numeric errors can
    923                 # cause floor(log(x)/log(2)) to be one too small; for
    924                 # small x this can be fixed by adding a small quantity
    925                 # to the quotient before taking the floor.
    926                 self.assertEqual(k, 1 + math.floor(
    927                         math.log(abs(x))/math.log(2) + tiny))
    928 
    929         self.assertEqual((0L).bit_length(), 0)
    930         self.assertEqual((1L).bit_length(), 1)
    931         self.assertEqual((-1L).bit_length(), 1)
    932         self.assertEqual((2L).bit_length(), 2)
    933         self.assertEqual((-2L).bit_length(), 2)
    934         for i in [2, 3, 15, 16, 17, 31, 32, 33, 63, 64, 234]:
    935             a = 2L**i
    936             self.assertEqual((a-1).bit_length(), i)
    937             self.assertEqual((1-a).bit_length(), i)
    938             self.assertEqual((a).bit_length(), i+1)
    939             self.assertEqual((-a).bit_length(), i+1)
    940             self.assertEqual((a+1).bit_length(), i+1)
    941             self.assertEqual((-a-1).bit_length(), i+1)
    942 
    943 
    944 def test_main():
    945     test_support.run_unittest(LongTest)
    946 
    947 if __name__ == "__main__":
    948     test_main()
    949