• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import unittest
2from test import support
3
4import sys
5
6import random
7import math
8import array
9
10# SHIFT should match the value in longintrepr.h for best testing.
11SHIFT = sys.int_info.bits_per_digit
12BASE = 2 ** SHIFT
13MASK = BASE - 1
14KARATSUBA_CUTOFF = 70   # from longobject.c
15
16# Max number of base BASE digits to use in test cases.  Doubling
17# this will more than double the runtime.
18MAXDIGITS = 15
19
20# build some special values
21special = [0, 1, 2, BASE, BASE >> 1, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa]
22#  some solid strings of one bits
23p2 = 4  # 0 and 1 already added
24for i in range(2*SHIFT):
25    special.append(p2 - 1)
26    p2 = p2 << 1
27del p2
28# add complements & negations
29special += [~x for x in special] + [-x for x in special]
30
31DBL_MAX = sys.float_info.max
32DBL_MAX_EXP = sys.float_info.max_exp
33DBL_MIN_EXP = sys.float_info.min_exp
34DBL_MANT_DIG = sys.float_info.mant_dig
35DBL_MIN_OVERFLOW = 2**DBL_MAX_EXP - 2**(DBL_MAX_EXP - DBL_MANT_DIG - 1)
36
37
38# Pure Python version of correctly-rounded integer-to-float conversion.
39def int_to_float(n):
40    """
41    Correctly-rounded integer-to-float conversion.
42
43    """
44    # Constants, depending only on the floating-point format in use.
45    # We use an extra 2 bits of precision for rounding purposes.
46    PRECISION = sys.float_info.mant_dig + 2
47    SHIFT_MAX = sys.float_info.max_exp - PRECISION
48    Q_MAX = 1 << PRECISION
49    ROUND_HALF_TO_EVEN_CORRECTION = [0, -1, -2, 1, 0, -1, 2, 1]
50
51    # Reduce to the case where n is positive.
52    if n == 0:
53        return 0.0
54    elif n < 0:
55        return -int_to_float(-n)
56
57    # Convert n to a 'floating-point' number q * 2**shift, where q is an
58    # integer with 'PRECISION' significant bits.  When shifting n to create q,
59    # the least significant bit of q is treated as 'sticky'.  That is, the
60    # least significant bit of q is set if either the corresponding bit of n
61    # was already set, or any one of the bits of n lost in the shift was set.
62    shift = n.bit_length() - PRECISION
63    q = n << -shift if shift < 0 else (n >> shift) | bool(n & ~(-1 << shift))
64
65    # Round half to even (actually rounds to the nearest multiple of 4,
66    # rounding ties to a multiple of 8).
67    q += ROUND_HALF_TO_EVEN_CORRECTION[q & 7]
68
69    # Detect overflow.
70    if shift + (q == Q_MAX) > SHIFT_MAX:
71        raise OverflowError("integer too large to convert to float")
72
73    # Checks: q is exactly representable, and q**2**shift doesn't overflow.
74    assert q % 4 == 0 and q // 4 <= 2**(sys.float_info.mant_dig)
75    assert q * 2**shift <= sys.float_info.max
76
77    # Some circularity here, since float(q) is doing an int-to-float
78    # conversion.  But here q is of bounded size, and is exactly representable
79    # as a float.  In a low-level C-like language, this operation would be a
80    # simple cast (e.g., from unsigned long long to double).
81    return math.ldexp(float(q), shift)
82
83
84# pure Python version of correctly-rounded true division
85def truediv(a, b):
86    """Correctly-rounded true division for integers."""
87    negative = a^b < 0
88    a, b = abs(a), abs(b)
89
90    # exceptions:  division by zero, overflow
91    if not b:
92        raise ZeroDivisionError("division by zero")
93    if a >= DBL_MIN_OVERFLOW * b:
94        raise OverflowError("int/int too large to represent as a float")
95
96   # find integer d satisfying 2**(d - 1) <= a/b < 2**d
97    d = a.bit_length() - b.bit_length()
98    if d >= 0 and a >= 2**d * b or d < 0 and a * 2**-d >= b:
99        d += 1
100
101    # compute 2**-exp * a / b for suitable exp
102    exp = max(d, DBL_MIN_EXP) - DBL_MANT_DIG
103    a, b = a << max(-exp, 0), b << max(exp, 0)
104    q, r = divmod(a, b)
105
106    # round-half-to-even: fractional part is r/b, which is > 0.5 iff
107    # 2*r > b, and == 0.5 iff 2*r == b.
108    if 2*r > b or 2*r == b and q % 2 == 1:
109        q += 1
110
111    result = math.ldexp(q, exp)
112    return -result if negative else result
113
114
115class LongTest(unittest.TestCase):
116
117    # Get quasi-random long consisting of ndigits digits (in base BASE).
118    # quasi == the most-significant digit will not be 0, and the number
119    # is constructed to contain long strings of 0 and 1 bits.  These are
120    # more likely than random bits to provoke digit-boundary errors.
121    # The sign of the number is also random.
122
123    def getran(self, ndigits):
124        self.assertGreater(ndigits, 0)
125        nbits_hi = ndigits * SHIFT
126        nbits_lo = nbits_hi - SHIFT + 1
127        answer = 0
128        nbits = 0
129        r = int(random.random() * (SHIFT * 2)) | 1  # force 1 bits to start
130        while nbits < nbits_lo:
131            bits = (r >> 1) + 1
132            bits = min(bits, nbits_hi - nbits)
133            self.assertTrue(1 <= bits <= SHIFT)
134            nbits = nbits + bits
135            answer = answer << bits
136            if r & 1:
137                answer = answer | ((1 << bits) - 1)
138            r = int(random.random() * (SHIFT * 2))
139        self.assertTrue(nbits_lo <= nbits <= nbits_hi)
140        if random.random() < 0.5:
141            answer = -answer
142        return answer
143
144    # Get random long consisting of ndigits random digits (relative to base
145    # BASE).  The sign bit is also random.
146
147    def getran2(ndigits):
148        answer = 0
149        for i in range(ndigits):
150            answer = (answer << SHIFT) | random.randint(0, MASK)
151        if random.random() < 0.5:
152            answer = -answer
153        return answer
154
155    def check_division(self, x, y):
156        eq = self.assertEqual
157        with self.subTest(x=x, y=y):
158            q, r = divmod(x, y)
159            q2, r2 = x//y, x%y
160            pab, pba = x*y, y*x
161            eq(pab, pba, "multiplication does not commute")
162            eq(q, q2, "divmod returns different quotient than /")
163            eq(r, r2, "divmod returns different mod than %")
164            eq(x, q*y + r, "x != q*y + r after divmod")
165            if y > 0:
166                self.assertTrue(0 <= r < y, "bad mod from divmod")
167            else:
168                self.assertTrue(y < r <= 0, "bad mod from divmod")
169
170    def test_division(self):
171        digits = list(range(1, MAXDIGITS+1)) + list(range(KARATSUBA_CUTOFF,
172                                                      KARATSUBA_CUTOFF + 14))
173        digits.append(KARATSUBA_CUTOFF * 3)
174        for lenx in digits:
175            x = self.getran(lenx)
176            for leny in digits:
177                y = self.getran(leny) or 1
178                self.check_division(x, y)
179
180        # specific numbers chosen to exercise corner cases of the
181        # current long division implementation
182
183        # 30-bit cases involving a quotient digit estimate of BASE+1
184        self.check_division(1231948412290879395966702881,
185                            1147341367131428698)
186        self.check_division(815427756481275430342312021515587883,
187                       707270836069027745)
188        self.check_division(627976073697012820849443363563599041,
189                       643588798496057020)
190        self.check_division(1115141373653752303710932756325578065,
191                       1038556335171453937726882627)
192        # 30-bit cases that require the post-subtraction correction step
193        self.check_division(922498905405436751940989320930368494,
194                       949985870686786135626943396)
195        self.check_division(768235853328091167204009652174031844,
196                       1091555541180371554426545266)
197
198        # 15-bit cases involving a quotient digit estimate of BASE+1
199        self.check_division(20172188947443, 615611397)
200        self.check_division(1020908530270155025, 950795710)
201        self.check_division(128589565723112408, 736393718)
202        self.check_division(609919780285761575, 18613274546784)
203        # 15-bit cases that require the post-subtraction correction step
204        self.check_division(710031681576388032, 26769404391308)
205        self.check_division(1933622614268221, 30212853348836)
206
207
208
209    def test_karatsuba(self):
210        digits = list(range(1, 5)) + list(range(KARATSUBA_CUTOFF,
211                                                KARATSUBA_CUTOFF + 10))
212        digits.extend([KARATSUBA_CUTOFF * 10, KARATSUBA_CUTOFF * 100])
213
214        bits = [digit * SHIFT for digit in digits]
215
216        # Test products of long strings of 1 bits -- (2**x-1)*(2**y-1) ==
217        # 2**(x+y) - 2**x - 2**y + 1, so the proper result is easy to check.
218        for abits in bits:
219            a = (1 << abits) - 1
220            for bbits in bits:
221                if bbits < abits:
222                    continue
223                with self.subTest(abits=abits, bbits=bbits):
224                    b = (1 << bbits) - 1
225                    x = a * b
226                    y = ((1 << (abits + bbits)) -
227                         (1 << abits) -
228                         (1 << bbits) +
229                         1)
230                    self.assertEqual(x, y)
231
232    def check_bitop_identities_1(self, x):
233        eq = self.assertEqual
234        with self.subTest(x=x):
235            eq(x & 0, 0)
236            eq(x | 0, x)
237            eq(x ^ 0, x)
238            eq(x & -1, x)
239            eq(x | -1, -1)
240            eq(x ^ -1, ~x)
241            eq(x, ~~x)
242            eq(x & x, x)
243            eq(x | x, x)
244            eq(x ^ x, 0)
245            eq(x & ~x, 0)
246            eq(x | ~x, -1)
247            eq(x ^ ~x, -1)
248            eq(-x, 1 + ~x)
249            eq(-x, ~(x-1))
250        for n in range(2*SHIFT):
251            p2 = 2 ** n
252            with self.subTest(x=x, n=n, p2=p2):
253                eq(x << n >> n, x)
254                eq(x // p2, x >> n)
255                eq(x * p2, x << n)
256                eq(x & -p2, x >> n << n)
257                eq(x & -p2, x & ~(p2 - 1))
258
259    def check_bitop_identities_2(self, x, y):
260        eq = self.assertEqual
261        with self.subTest(x=x, y=y):
262            eq(x & y, y & x)
263            eq(x | y, y | x)
264            eq(x ^ y, y ^ x)
265            eq(x ^ y ^ x, y)
266            eq(x & y, ~(~x | ~y))
267            eq(x | y, ~(~x & ~y))
268            eq(x ^ y, (x | y) & ~(x & y))
269            eq(x ^ y, (x & ~y) | (~x & y))
270            eq(x ^ y, (x | y) & (~x | ~y))
271
272    def check_bitop_identities_3(self, x, y, z):
273        eq = self.assertEqual
274        with self.subTest(x=x, y=y, z=z):
275            eq((x & y) & z, x & (y & z))
276            eq((x | y) | z, x | (y | z))
277            eq((x ^ y) ^ z, x ^ (y ^ z))
278            eq(x & (y | z), (x & y) | (x & z))
279            eq(x | (y & z), (x | y) & (x | z))
280
281    def test_bitop_identities(self):
282        for x in special:
283            self.check_bitop_identities_1(x)
284        digits = range(1, MAXDIGITS+1)
285        for lenx in digits:
286            x = self.getran(lenx)
287            self.check_bitop_identities_1(x)
288            for leny in digits:
289                y = self.getran(leny)
290                self.check_bitop_identities_2(x, y)
291                self.check_bitop_identities_3(x, y, self.getran((lenx + leny)//2))
292
293    def slow_format(self, x, base):
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               {2: '0b', 8: '0o', 10: '', 16: '0x'}[base] + \
305               "".join("0123456789abcdef"[i] for i in digits)
306
307    def check_format_1(self, x):
308        for base, mapper in (2, bin), (8, oct), (10, str), (10, repr), (16, hex):
309            got = mapper(x)
310            with self.subTest(x=x, mapper=mapper.__name__):
311                expected = self.slow_format(x, base)
312                self.assertEqual(got, expected)
313            with self.subTest(got=got):
314                self.assertEqual(int(got, 0), x)
315
316    def test_format(self):
317        for x in special:
318            self.check_format_1(x)
319        for i in range(10):
320            for lenx in range(1, MAXDIGITS+1):
321                x = self.getran(lenx)
322                self.check_format_1(x)
323
324    def test_long(self):
325        # Check conversions from string
326        LL = [
327                ('1' + '0'*20, 10**20),
328                ('1' + '0'*100, 10**100)
329        ]
330        for s, v in LL:
331            for sign in "", "+", "-":
332                for prefix in "", " ", "\t", "  \t\t  ":
333                    ss = prefix + sign + s
334                    vv = v
335                    if sign == "-" and v is not ValueError:
336                        vv = -v
337                    try:
338                        self.assertEqual(int(ss), vv)
339                    except ValueError:
340                        pass
341
342        # trailing L should no longer be accepted...
343        self.assertRaises(ValueError, int, '123L')
344        self.assertRaises(ValueError, int, '123l')
345        self.assertRaises(ValueError, int, '0L')
346        self.assertRaises(ValueError, int, '-37L')
347        self.assertRaises(ValueError, int, '0x32L', 16)
348        self.assertRaises(ValueError, int, '1L', 21)
349        # ... but it's just a normal digit if base >= 22
350        self.assertEqual(int('1L', 22), 43)
351
352        # tests with base 0
353        self.assertEqual(int('000', 0), 0)
354        self.assertEqual(int('0o123', 0), 83)
355        self.assertEqual(int('0x123', 0), 291)
356        self.assertEqual(int('0b100', 0), 4)
357        self.assertEqual(int(' 0O123   ', 0), 83)
358        self.assertEqual(int(' 0X123  ', 0), 291)
359        self.assertEqual(int(' 0B100 ', 0), 4)
360        self.assertEqual(int('0', 0), 0)
361        self.assertEqual(int('+0', 0), 0)
362        self.assertEqual(int('-0', 0), 0)
363        self.assertEqual(int('00', 0), 0)
364        self.assertRaises(ValueError, int, '08', 0)
365        self.assertRaises(ValueError, int, '-012395', 0)
366
367        # invalid bases
368        invalid_bases = [-909,
369                          2**31-1, 2**31, -2**31, -2**31-1,
370                          2**63-1, 2**63, -2**63, -2**63-1,
371                          2**100, -2**100,
372                          ]
373        for base in invalid_bases:
374            self.assertRaises(ValueError, int, '42', base)
375
376        # Invalid unicode string
377        # See bpo-34087
378        self.assertRaises(ValueError, int, '\u3053\u3093\u306b\u3061\u306f')
379
380
381    def test_conversion(self):
382
383        class JustLong:
384            # test that __long__ no longer used in 3.x
385            def __long__(self):
386                return 42
387        self.assertRaises(TypeError, int, JustLong())
388
389        class LongTrunc:
390            # __long__ should be ignored in 3.x
391            def __long__(self):
392                return 42
393            def __trunc__(self):
394                return 1729
395        self.assertEqual(int(LongTrunc()), 1729)
396
397    def check_float_conversion(self, n):
398        # Check that int -> float conversion behaviour matches
399        # that of the pure Python version above.
400        try:
401            actual = float(n)
402        except OverflowError:
403            actual = 'overflow'
404
405        try:
406            expected = int_to_float(n)
407        except OverflowError:
408            expected = 'overflow'
409
410        msg = ("Error in conversion of integer {} to float.  "
411               "Got {}, expected {}.".format(n, actual, expected))
412        self.assertEqual(actual, expected, msg)
413
414    @support.requires_IEEE_754
415    def test_float_conversion(self):
416
417        exact_values = [0, 1, 2,
418                         2**53-3,
419                         2**53-2,
420                         2**53-1,
421                         2**53,
422                         2**53+2,
423                         2**54-4,
424                         2**54-2,
425                         2**54,
426                         2**54+4]
427        for x in exact_values:
428            self.assertEqual(float(x), x)
429            self.assertEqual(float(-x), -x)
430
431        # test round-half-even
432        for x, y in [(1, 0), (2, 2), (3, 4), (4, 4), (5, 4), (6, 6), (7, 8)]:
433            for p in range(15):
434                self.assertEqual(int(float(2**p*(2**53+x))), 2**p*(2**53+y))
435
436        for x, y in [(0, 0), (1, 0), (2, 0), (3, 4), (4, 4), (5, 4), (6, 8),
437                     (7, 8), (8, 8), (9, 8), (10, 8), (11, 12), (12, 12),
438                     (13, 12), (14, 16), (15, 16)]:
439            for p in range(15):
440                self.assertEqual(int(float(2**p*(2**54+x))), 2**p*(2**54+y))
441
442        # behaviour near extremes of floating-point range
443        int_dbl_max = int(DBL_MAX)
444        top_power = 2**DBL_MAX_EXP
445        halfway = (int_dbl_max + top_power)//2
446        self.assertEqual(float(int_dbl_max), DBL_MAX)
447        self.assertEqual(float(int_dbl_max+1), DBL_MAX)
448        self.assertEqual(float(halfway-1), DBL_MAX)
449        self.assertRaises(OverflowError, float, halfway)
450        self.assertEqual(float(1-halfway), -DBL_MAX)
451        self.assertRaises(OverflowError, float, -halfway)
452        self.assertRaises(OverflowError, float, top_power-1)
453        self.assertRaises(OverflowError, float, top_power)
454        self.assertRaises(OverflowError, float, top_power+1)
455        self.assertRaises(OverflowError, float, 2*top_power-1)
456        self.assertRaises(OverflowError, float, 2*top_power)
457        self.assertRaises(OverflowError, float, top_power*top_power)
458
459        for p in range(100):
460            x = 2**p * (2**53 + 1) + 1
461            y = 2**p * (2**53 + 2)
462            self.assertEqual(int(float(x)), y)
463
464            x = 2**p * (2**53 + 1)
465            y = 2**p * 2**53
466            self.assertEqual(int(float(x)), y)
467
468        # Compare builtin float conversion with pure Python int_to_float
469        # function above.
470        test_values = [
471            int_dbl_max-1, int_dbl_max, int_dbl_max+1,
472            halfway-1, halfway, halfway + 1,
473            top_power-1, top_power, top_power+1,
474            2*top_power-1, 2*top_power, top_power*top_power,
475        ]
476        test_values.extend(exact_values)
477        for p in range(-4, 8):
478            for x in range(-128, 128):
479                test_values.append(2**(p+53) + x)
480        for value in test_values:
481            self.check_float_conversion(value)
482            self.check_float_conversion(-value)
483
484    def test_float_overflow(self):
485        for x in -2.0, -1.0, 0.0, 1.0, 2.0:
486            self.assertEqual(float(int(x)), x)
487
488        shuge = '12345' * 120
489        huge = 1 << 30000
490        mhuge = -huge
491        namespace = {'huge': huge, 'mhuge': mhuge, 'shuge': shuge, 'math': math}
492        for test in ["float(huge)", "float(mhuge)",
493                     "complex(huge)", "complex(mhuge)",
494                     "complex(huge, 1)", "complex(mhuge, 1)",
495                     "complex(1, huge)", "complex(1, mhuge)",
496                     "1. + huge", "huge + 1.", "1. + mhuge", "mhuge + 1.",
497                     "1. - huge", "huge - 1.", "1. - mhuge", "mhuge - 1.",
498                     "1. * huge", "huge * 1.", "1. * mhuge", "mhuge * 1.",
499                     "1. // huge", "huge // 1.", "1. // mhuge", "mhuge // 1.",
500                     "1. / huge", "huge / 1.", "1. / mhuge", "mhuge / 1.",
501                     "1. ** huge", "huge ** 1.", "1. ** mhuge", "mhuge ** 1.",
502                     "math.sin(huge)", "math.sin(mhuge)",
503                     "math.sqrt(huge)", "math.sqrt(mhuge)", # should do better
504                     # math.floor() of an int returns an int now
505                     ##"math.floor(huge)", "math.floor(mhuge)",
506                     ]:
507
508            self.assertRaises(OverflowError, eval, test, namespace)
509
510        # XXX Perhaps float(shuge) can raise OverflowError on some box?
511        # The comparison should not.
512        self.assertNotEqual(float(shuge), int(shuge),
513            "float(shuge) should not equal int(shuge)")
514
515    def test_logs(self):
516        LOG10E = math.log10(math.e)
517
518        for exp in list(range(10)) + [100, 1000, 10000]:
519            value = 10 ** exp
520            log10 = math.log10(value)
521            self.assertAlmostEqual(log10, exp)
522
523            # log10(value) == exp, so log(value) == log10(value)/log10(e) ==
524            # exp/LOG10E
525            expected = exp / LOG10E
526            log = math.log(value)
527            self.assertAlmostEqual(log, expected)
528
529        for bad in -(1 << 10000), -2, 0:
530            self.assertRaises(ValueError, math.log, bad)
531            self.assertRaises(ValueError, math.log10, bad)
532
533    def test_mixed_compares(self):
534        eq = self.assertEqual
535
536        # We're mostly concerned with that mixing floats and ints does the
537        # right stuff, even when ints are too large to fit in a float.
538        # The safest way to check the results is to use an entirely different
539        # method, which we do here via a skeletal rational class (which
540        # represents all Python ints and floats exactly).
541        class Rat:
542            def __init__(self, value):
543                if isinstance(value, int):
544                    self.n = value
545                    self.d = 1
546                elif isinstance(value, float):
547                    # Convert to exact rational equivalent.
548                    f, e = math.frexp(abs(value))
549                    assert f == 0 or 0.5 <= f < 1.0
550                    # |value| = f * 2**e exactly
551
552                    # Suck up CHUNK bits at a time; 28 is enough so that we suck
553                    # up all bits in 2 iterations for all known binary double-
554                    # precision formats, and small enough to fit in an int.
555                    CHUNK = 28
556                    top = 0
557                    # invariant: |value| = (top + f) * 2**e exactly
558                    while f:
559                        f = math.ldexp(f, CHUNK)
560                        digit = int(f)
561                        assert digit >> CHUNK == 0
562                        top = (top << CHUNK) | digit
563                        f -= digit
564                        assert 0.0 <= f < 1.0
565                        e -= CHUNK
566
567                    # Now |value| = top * 2**e exactly.
568                    if e >= 0:
569                        n = top << e
570                        d = 1
571                    else:
572                        n = top
573                        d = 1 << -e
574                    if value < 0:
575                        n = -n
576                    self.n = n
577                    self.d = d
578                    assert float(n) / float(d) == value
579                else:
580                    raise TypeError("can't deal with %r" % value)
581
582            def _cmp__(self, other):
583                if not isinstance(other, Rat):
584                    other = Rat(other)
585                x, y = self.n * other.d, self.d * other.n
586                return (x > y) - (x < y)
587            def __eq__(self, other):
588                return self._cmp__(other) == 0
589            def __ge__(self, other):
590                return self._cmp__(other) >= 0
591            def __gt__(self, other):
592                return self._cmp__(other) > 0
593            def __le__(self, other):
594                return self._cmp__(other) <= 0
595            def __lt__(self, other):
596                return self._cmp__(other) < 0
597
598        cases = [0, 0.001, 0.99, 1.0, 1.5, 1e20, 1e200]
599        # 2**48 is an important boundary in the internals.  2**53 is an
600        # important boundary for IEEE double precision.
601        for t in 2.0**48, 2.0**50, 2.0**53:
602            cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0,
603                          int(t-1), int(t), int(t+1)])
604        cases.extend([0, 1, 2, sys.maxsize, float(sys.maxsize)])
605        # 1 << 20000 should exceed all double formats.  int(1e200) is to
606        # check that we get equality with 1e200 above.
607        t = int(1e200)
608        cases.extend([0, 1, 2, 1 << 20000, t-1, t, t+1])
609        cases.extend([-x for x in cases])
610        for x in cases:
611            Rx = Rat(x)
612            for y in cases:
613                Ry = Rat(y)
614                Rcmp = (Rx > Ry) - (Rx < Ry)
615                with self.subTest(x=x, y=y, Rcmp=Rcmp):
616                    xycmp = (x > y) - (x < y)
617                    eq(Rcmp, xycmp)
618                    eq(x == y, Rcmp == 0)
619                    eq(x != y, Rcmp != 0)
620                    eq(x < y, Rcmp < 0)
621                    eq(x <= y, Rcmp <= 0)
622                    eq(x > y, Rcmp > 0)
623                    eq(x >= y, Rcmp >= 0)
624
625    def test__format__(self):
626        self.assertEqual(format(123456789, 'd'), '123456789')
627        self.assertEqual(format(123456789, 'd'), '123456789')
628        self.assertEqual(format(123456789, ','), '123,456,789')
629        self.assertEqual(format(123456789, '_'), '123_456_789')
630
631        # sign and aligning are interdependent
632        self.assertEqual(format(1, "-"), '1')
633        self.assertEqual(format(-1, "-"), '-1')
634        self.assertEqual(format(1, "-3"), '  1')
635        self.assertEqual(format(-1, "-3"), ' -1')
636        self.assertEqual(format(1, "+3"), ' +1')
637        self.assertEqual(format(-1, "+3"), ' -1')
638        self.assertEqual(format(1, " 3"), '  1')
639        self.assertEqual(format(-1, " 3"), ' -1')
640        self.assertEqual(format(1, " "), ' 1')
641        self.assertEqual(format(-1, " "), '-1')
642
643        # hex
644        self.assertEqual(format(3, "x"), "3")
645        self.assertEqual(format(3, "X"), "3")
646        self.assertEqual(format(1234, "x"), "4d2")
647        self.assertEqual(format(-1234, "x"), "-4d2")
648        self.assertEqual(format(1234, "8x"), "     4d2")
649        self.assertEqual(format(-1234, "8x"), "    -4d2")
650        self.assertEqual(format(1234, "x"), "4d2")
651        self.assertEqual(format(-1234, "x"), "-4d2")
652        self.assertEqual(format(-3, "x"), "-3")
653        self.assertEqual(format(-3, "X"), "-3")
654        self.assertEqual(format(int('be', 16), "x"), "be")
655        self.assertEqual(format(int('be', 16), "X"), "BE")
656        self.assertEqual(format(-int('be', 16), "x"), "-be")
657        self.assertEqual(format(-int('be', 16), "X"), "-BE")
658        self.assertRaises(ValueError, format, 1234567890, ',x')
659        self.assertEqual(format(1234567890, '_x'), '4996_02d2')
660        self.assertEqual(format(1234567890, '_X'), '4996_02D2')
661
662        # octal
663        self.assertEqual(format(3, "o"), "3")
664        self.assertEqual(format(-3, "o"), "-3")
665        self.assertEqual(format(1234, "o"), "2322")
666        self.assertEqual(format(-1234, "o"), "-2322")
667        self.assertEqual(format(1234, "-o"), "2322")
668        self.assertEqual(format(-1234, "-o"), "-2322")
669        self.assertEqual(format(1234, " o"), " 2322")
670        self.assertEqual(format(-1234, " o"), "-2322")
671        self.assertEqual(format(1234, "+o"), "+2322")
672        self.assertEqual(format(-1234, "+o"), "-2322")
673        self.assertRaises(ValueError, format, 1234567890, ',o')
674        self.assertEqual(format(1234567890, '_o'), '111_4540_1322')
675
676        # binary
677        self.assertEqual(format(3, "b"), "11")
678        self.assertEqual(format(-3, "b"), "-11")
679        self.assertEqual(format(1234, "b"), "10011010010")
680        self.assertEqual(format(-1234, "b"), "-10011010010")
681        self.assertEqual(format(1234, "-b"), "10011010010")
682        self.assertEqual(format(-1234, "-b"), "-10011010010")
683        self.assertEqual(format(1234, " b"), " 10011010010")
684        self.assertEqual(format(-1234, " b"), "-10011010010")
685        self.assertEqual(format(1234, "+b"), "+10011010010")
686        self.assertEqual(format(-1234, "+b"), "-10011010010")
687        self.assertRaises(ValueError, format, 1234567890, ',b')
688        self.assertEqual(format(12345, '_b'), '11_0000_0011_1001')
689
690        # make sure these are errors
691        self.assertRaises(ValueError, format, 3, "1.3")  # precision disallowed
692        self.assertRaises(ValueError, format, 3, "_c")   # underscore,
693        self.assertRaises(ValueError, format, 3, ",c")   # comma, and
694        self.assertRaises(ValueError, format, 3, "+c")   # sign not allowed
695                                                         # with 'c'
696
697        self.assertRaisesRegex(ValueError, 'Cannot specify both', format, 3, '_,')
698        self.assertRaisesRegex(ValueError, 'Cannot specify both', format, 3, ',_')
699        self.assertRaisesRegex(ValueError, 'Cannot specify both', format, 3, '_,d')
700        self.assertRaisesRegex(ValueError, 'Cannot specify both', format, 3, ',_d')
701
702        self.assertRaisesRegex(ValueError, "Cannot specify ',' with 's'", format, 3, ',s')
703        self.assertRaisesRegex(ValueError, "Cannot specify '_' with 's'", format, 3, '_s')
704
705        # ensure that only int and float type specifiers work
706        for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] +
707                            [chr(x) for x in range(ord('A'), ord('Z')+1)]):
708            if not format_spec in 'bcdoxXeEfFgGn%':
709                self.assertRaises(ValueError, format, 0, format_spec)
710                self.assertRaises(ValueError, format, 1, format_spec)
711                self.assertRaises(ValueError, format, -1, format_spec)
712                self.assertRaises(ValueError, format, 2**100, format_spec)
713                self.assertRaises(ValueError, format, -(2**100), format_spec)
714
715        # ensure that float type specifiers work; format converts
716        #  the int to a float
717        for format_spec in 'eEfFgG%':
718            for value in [0, 1, -1, 100, -100, 1234567890, -1234567890]:
719                self.assertEqual(format(value, format_spec),
720                                 format(float(value), format_spec))
721
722    def test_nan_inf(self):
723        self.assertRaises(OverflowError, int, float('inf'))
724        self.assertRaises(OverflowError, int, float('-inf'))
725        self.assertRaises(ValueError, int, float('nan'))
726
727    def test_mod_division(self):
728        with self.assertRaises(ZeroDivisionError):
729            _ = 1 % 0
730
731        self.assertEqual(13 % 10, 3)
732        self.assertEqual(-13 % 10, 7)
733        self.assertEqual(13 % -10, -7)
734        self.assertEqual(-13 % -10, -3)
735
736        self.assertEqual(12 % 4, 0)
737        self.assertEqual(-12 % 4, 0)
738        self.assertEqual(12 % -4, 0)
739        self.assertEqual(-12 % -4, 0)
740
741    def test_true_division(self):
742        huge = 1 << 40000
743        mhuge = -huge
744        self.assertEqual(huge / huge, 1.0)
745        self.assertEqual(mhuge / mhuge, 1.0)
746        self.assertEqual(huge / mhuge, -1.0)
747        self.assertEqual(mhuge / huge, -1.0)
748        self.assertEqual(1 / huge, 0.0)
749        self.assertEqual(1 / huge, 0.0)
750        self.assertEqual(1 / mhuge, 0.0)
751        self.assertEqual(1 / mhuge, 0.0)
752        self.assertEqual((666 * huge + (huge >> 1)) / huge, 666.5)
753        self.assertEqual((666 * mhuge + (mhuge >> 1)) / mhuge, 666.5)
754        self.assertEqual((666 * huge + (huge >> 1)) / mhuge, -666.5)
755        self.assertEqual((666 * mhuge + (mhuge >> 1)) / huge, -666.5)
756        self.assertEqual(huge / (huge << 1), 0.5)
757        self.assertEqual((1000000 * huge) / huge, 1000000)
758
759        namespace = {'huge': huge, 'mhuge': mhuge}
760
761        for overflow in ["float(huge)", "float(mhuge)",
762                         "huge / 1", "huge / 2", "huge / -1", "huge / -2",
763                         "mhuge / 100", "mhuge / 200"]:
764            self.assertRaises(OverflowError, eval, overflow, namespace)
765
766        for underflow in ["1 / huge", "2 / huge", "-1 / huge", "-2 / huge",
767                         "100 / mhuge", "200 / mhuge"]:
768            result = eval(underflow, namespace)
769            self.assertEqual(result, 0.0,
770                             "expected underflow to 0 from %r" % underflow)
771
772        for zero in ["huge / 0", "mhuge / 0"]:
773            self.assertRaises(ZeroDivisionError, eval, zero, namespace)
774
775    def test_floordiv(self):
776        with self.assertRaises(ZeroDivisionError):
777            _ = 1 // 0
778
779        self.assertEqual(2 // 3, 0)
780        self.assertEqual(2 // -3, -1)
781        self.assertEqual(-2 // 3, -1)
782        self.assertEqual(-2 // -3, 0)
783
784        self.assertEqual(-11 // -3, 3)
785        self.assertEqual(-11 // 3, -4)
786        self.assertEqual(11 // -3, -4)
787        self.assertEqual(11 // 3, 3)
788
789        self.assertEqual(-12 // -3, 4)
790        self.assertEqual(-12 // 3, -4)
791        self.assertEqual(12 // -3, -4)
792        self.assertEqual(12 // 3, 4)
793
794    def check_truediv(self, a, b, skip_small=True):
795        """Verify that the result of a/b is correctly rounded, by
796        comparing it with a pure Python implementation of correctly
797        rounded division.  b should be nonzero."""
798
799        # skip check for small a and b: in this case, the current
800        # implementation converts the arguments to float directly and
801        # then applies a float division.  This can give doubly-rounded
802        # results on x87-using machines (particularly 32-bit Linux).
803        if skip_small and max(abs(a), abs(b)) < 2**DBL_MANT_DIG:
804            return
805
806        try:
807            # use repr so that we can distinguish between -0.0 and 0.0
808            expected = repr(truediv(a, b))
809        except OverflowError:
810            expected = 'overflow'
811        except ZeroDivisionError:
812            expected = 'zerodivision'
813
814        try:
815            got = repr(a / b)
816        except OverflowError:
817            got = 'overflow'
818        except ZeroDivisionError:
819            got = 'zerodivision'
820
821        self.assertEqual(expected, got, "Incorrectly rounded division {}/{}: "
822                         "expected {}, got {}".format(a, b, expected, got))
823
824    @support.requires_IEEE_754
825    def test_correctly_rounded_true_division(self):
826        # more stringent tests than those above, checking that the
827        # result of true division of ints is always correctly rounded.
828        # This test should probably be considered CPython-specific.
829
830        # Exercise all the code paths not involving Gb-sized ints.
831        # ... divisions involving zero
832        self.check_truediv(123, 0)
833        self.check_truediv(-456, 0)
834        self.check_truediv(0, 3)
835        self.check_truediv(0, -3)
836        self.check_truediv(0, 0)
837        # ... overflow or underflow by large margin
838        self.check_truediv(671 * 12345 * 2**DBL_MAX_EXP, 12345)
839        self.check_truediv(12345, 345678 * 2**(DBL_MANT_DIG - DBL_MIN_EXP))
840        # ... a much larger or smaller than b
841        self.check_truediv(12345*2**100, 98765)
842        self.check_truediv(12345*2**30, 98765*7**81)
843        # ... a / b near a boundary: one of 1, 2**DBL_MANT_DIG, 2**DBL_MIN_EXP,
844        #                 2**DBL_MAX_EXP, 2**(DBL_MIN_EXP-DBL_MANT_DIG)
845        bases = (0, DBL_MANT_DIG, DBL_MIN_EXP,
846                 DBL_MAX_EXP, DBL_MIN_EXP - DBL_MANT_DIG)
847        for base in bases:
848            for exp in range(base - 15, base + 15):
849                self.check_truediv(75312*2**max(exp, 0), 69187*2**max(-exp, 0))
850                self.check_truediv(69187*2**max(exp, 0), 75312*2**max(-exp, 0))
851
852        # overflow corner case
853        for m in [1, 2, 7, 17, 12345, 7**100,
854                  -1, -2, -5, -23, -67891, -41**50]:
855            for n in range(-10, 10):
856                self.check_truediv(m*DBL_MIN_OVERFLOW + n, m)
857                self.check_truediv(m*DBL_MIN_OVERFLOW + n, -m)
858
859        # check detection of inexactness in shifting stage
860        for n in range(250):
861            # (2**DBL_MANT_DIG+1)/(2**DBL_MANT_DIG) lies halfway
862            # between two representable floats, and would usually be
863            # rounded down under round-half-to-even.  The tiniest of
864            # additions to the numerator should cause it to be rounded
865            # up instead.
866            self.check_truediv((2**DBL_MANT_DIG + 1)*12345*2**200 + 2**n,
867                           2**DBL_MANT_DIG*12345)
868
869        # 1/2731 is one of the smallest division cases that's subject
870        # to double rounding on IEEE 754 machines working internally with
871        # 64-bit precision.  On such machines, the next check would fail,
872        # were it not explicitly skipped in check_truediv.
873        self.check_truediv(1, 2731)
874
875        # a particularly bad case for the old algorithm:  gives an
876        # error of close to 3.5 ulps.
877        self.check_truediv(295147931372582273023, 295147932265116303360)
878        for i in range(1000):
879            self.check_truediv(10**(i+1), 10**i)
880            self.check_truediv(10**i, 10**(i+1))
881
882        # test round-half-to-even behaviour, normal result
883        for m in [1, 2, 4, 7, 8, 16, 17, 32, 12345, 7**100,
884                  -1, -2, -5, -23, -67891, -41**50]:
885            for n in range(-10, 10):
886                self.check_truediv(2**DBL_MANT_DIG*m + n, m)
887
888        # test round-half-to-even, subnormal result
889        for n in range(-20, 20):
890            self.check_truediv(n, 2**1076)
891
892        # largeish random divisions: a/b where |a| <= |b| <=
893        # 2*|a|; |ans| is between 0.5 and 1.0, so error should
894        # always be bounded by 2**-54 with equality possible only
895        # if the least significant bit of q=ans*2**53 is zero.
896        for M in [10**10, 10**100, 10**1000]:
897            for i in range(1000):
898                a = random.randrange(1, M)
899                b = random.randrange(a, 2*a+1)
900                self.check_truediv(a, b)
901                self.check_truediv(-a, b)
902                self.check_truediv(a, -b)
903                self.check_truediv(-a, -b)
904
905        # and some (genuinely) random tests
906        for _ in range(10000):
907            a_bits = random.randrange(1000)
908            b_bits = random.randrange(1, 1000)
909            x = random.randrange(2**a_bits)
910            y = random.randrange(1, 2**b_bits)
911            self.check_truediv(x, y)
912            self.check_truediv(x, -y)
913            self.check_truediv(-x, y)
914            self.check_truediv(-x, -y)
915
916    def test_negative_shift_count(self):
917        with self.assertRaises(ValueError):
918            42 << -3
919        with self.assertRaises(ValueError):
920            42 << -(1 << 1000)
921        with self.assertRaises(ValueError):
922            42 >> -3
923        with self.assertRaises(ValueError):
924            42 >> -(1 << 1000)
925
926    def test_lshift_of_zero(self):
927        self.assertEqual(0 << 0, 0)
928        self.assertEqual(0 << 10, 0)
929        with self.assertRaises(ValueError):
930            0 << -1
931        self.assertEqual(0 << (1 << 1000), 0)
932        with self.assertRaises(ValueError):
933            0 << -(1 << 1000)
934
935    @support.cpython_only
936    def test_huge_lshift_of_zero(self):
937        # Shouldn't try to allocate memory for a huge shift. See issue #27870.
938        # Other implementations may have a different boundary for overflow,
939        # or not raise at all.
940        self.assertEqual(0 << sys.maxsize, 0)
941        self.assertEqual(0 << (sys.maxsize + 1), 0)
942
943    @support.cpython_only
944    @support.bigmemtest(sys.maxsize + 1000, memuse=2/15 * 2, dry_run=False)
945    def test_huge_lshift(self, size):
946        self.assertEqual(1 << (sys.maxsize + 1000), 1 << 1000 << sys.maxsize)
947
948    def test_huge_rshift(self):
949        self.assertEqual(42 >> (1 << 1000), 0)
950        self.assertEqual((-42) >> (1 << 1000), -1)
951
952    @support.cpython_only
953    @support.bigmemtest(sys.maxsize + 500, memuse=2/15, dry_run=False)
954    def test_huge_rshift_of_huge(self, size):
955        huge = ((1 << 500) + 11) << sys.maxsize
956        self.assertEqual(huge >> (sys.maxsize + 1), (1 << 499) + 5)
957        self.assertEqual(huge >> (sys.maxsize + 1000), 0)
958
959    def test_small_ints(self):
960        for i in range(-5, 257):
961            self.assertIs(i, i + 0)
962            self.assertIs(i, i * 1)
963            self.assertIs(i, i - 0)
964            self.assertIs(i, i // 1)
965            self.assertIs(i, i & -1)
966            self.assertIs(i, i | 0)
967            self.assertIs(i, i ^ 0)
968            self.assertIs(i, ~~i)
969            self.assertIs(i, i**1)
970            self.assertIs(i, int(str(i)))
971            self.assertIs(i, i<<2>>2, str(i))
972        # corner cases
973        i = 1 << 70
974        self.assertIs(i - i, 0)
975        self.assertIs(0 * i, 0)
976
977    def test_bit_length(self):
978        tiny = 1e-10
979        for x in range(-65000, 65000):
980            k = x.bit_length()
981            # Check equivalence with Python version
982            self.assertEqual(k, len(bin(x).lstrip('-0b')))
983            # Behaviour as specified in the docs
984            if x != 0:
985                self.assertTrue(2**(k-1) <= abs(x) < 2**k)
986            else:
987                self.assertEqual(k, 0)
988            # Alternative definition: x.bit_length() == 1 + floor(log_2(x))
989            if x != 0:
990                # When x is an exact power of 2, numeric errors can
991                # cause floor(log(x)/log(2)) to be one too small; for
992                # small x this can be fixed by adding a small quantity
993                # to the quotient before taking the floor.
994                self.assertEqual(k, 1 + math.floor(
995                        math.log(abs(x))/math.log(2) + tiny))
996
997        self.assertEqual((0).bit_length(), 0)
998        self.assertEqual((1).bit_length(), 1)
999        self.assertEqual((-1).bit_length(), 1)
1000        self.assertEqual((2).bit_length(), 2)
1001        self.assertEqual((-2).bit_length(), 2)
1002        for i in [2, 3, 15, 16, 17, 31, 32, 33, 63, 64, 234]:
1003            a = 2**i
1004            self.assertEqual((a-1).bit_length(), i)
1005            self.assertEqual((1-a).bit_length(), i)
1006            self.assertEqual((a).bit_length(), i+1)
1007            self.assertEqual((-a).bit_length(), i+1)
1008            self.assertEqual((a+1).bit_length(), i+1)
1009            self.assertEqual((-a-1).bit_length(), i+1)
1010
1011    def test_round(self):
1012        # check round-half-even algorithm. For round to nearest ten;
1013        # rounding map is invariant under adding multiples of 20
1014        test_dict = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0,
1015                     6:10, 7:10, 8:10, 9:10, 10:10, 11:10, 12:10, 13:10, 14:10,
1016                     15:20, 16:20, 17:20, 18:20, 19:20}
1017        for offset in range(-520, 520, 20):
1018            for k, v in test_dict.items():
1019                got = round(k+offset, -1)
1020                expected = v+offset
1021                self.assertEqual(got, expected)
1022                self.assertIs(type(got), int)
1023
1024        # larger second argument
1025        self.assertEqual(round(-150, -2), -200)
1026        self.assertEqual(round(-149, -2), -100)
1027        self.assertEqual(round(-51, -2), -100)
1028        self.assertEqual(round(-50, -2), 0)
1029        self.assertEqual(round(-49, -2), 0)
1030        self.assertEqual(round(-1, -2), 0)
1031        self.assertEqual(round(0, -2), 0)
1032        self.assertEqual(round(1, -2), 0)
1033        self.assertEqual(round(49, -2), 0)
1034        self.assertEqual(round(50, -2), 0)
1035        self.assertEqual(round(51, -2), 100)
1036        self.assertEqual(round(149, -2), 100)
1037        self.assertEqual(round(150, -2), 200)
1038        self.assertEqual(round(250, -2), 200)
1039        self.assertEqual(round(251, -2), 300)
1040        self.assertEqual(round(172500, -3), 172000)
1041        self.assertEqual(round(173500, -3), 174000)
1042        self.assertEqual(round(31415926535, -1), 31415926540)
1043        self.assertEqual(round(31415926535, -2), 31415926500)
1044        self.assertEqual(round(31415926535, -3), 31415927000)
1045        self.assertEqual(round(31415926535, -4), 31415930000)
1046        self.assertEqual(round(31415926535, -5), 31415900000)
1047        self.assertEqual(round(31415926535, -6), 31416000000)
1048        self.assertEqual(round(31415926535, -7), 31420000000)
1049        self.assertEqual(round(31415926535, -8), 31400000000)
1050        self.assertEqual(round(31415926535, -9), 31000000000)
1051        self.assertEqual(round(31415926535, -10), 30000000000)
1052        self.assertEqual(round(31415926535, -11), 0)
1053        self.assertEqual(round(31415926535, -12), 0)
1054        self.assertEqual(round(31415926535, -999), 0)
1055
1056        # should get correct results even for huge inputs
1057        for k in range(10, 100):
1058            got = round(10**k + 324678, -3)
1059            expect = 10**k + 325000
1060            self.assertEqual(got, expect)
1061            self.assertIs(type(got), int)
1062
1063        # nonnegative second argument: round(x, n) should just return x
1064        for n in range(5):
1065            for i in range(100):
1066                x = random.randrange(-10000, 10000)
1067                got = round(x, n)
1068                self.assertEqual(got, x)
1069                self.assertIs(type(got), int)
1070        for huge_n in 2**31-1, 2**31, 2**63-1, 2**63, 2**100, 10**100:
1071            self.assertEqual(round(8979323, huge_n), 8979323)
1072
1073        # omitted second argument
1074        for i in range(100):
1075            x = random.randrange(-10000, 10000)
1076            got = round(x)
1077            self.assertEqual(got, x)
1078            self.assertIs(type(got), int)
1079
1080        # bad second argument
1081        bad_exponents = ('brian', 2.0, 0j)
1082        for e in bad_exponents:
1083            self.assertRaises(TypeError, round, 3, e)
1084
1085    def test_to_bytes(self):
1086        def check(tests, byteorder, signed=False):
1087            for test, expected in tests.items():
1088                try:
1089                    self.assertEqual(
1090                        test.to_bytes(len(expected), byteorder, signed=signed),
1091                        expected)
1092                except Exception as err:
1093                    raise AssertionError(
1094                        "failed to convert {0} with byteorder={1} and signed={2}"
1095                        .format(test, byteorder, signed)) from err
1096
1097        # Convert integers to signed big-endian byte arrays.
1098        tests1 = {
1099            0: b'\x00',
1100            1: b'\x01',
1101            -1: b'\xff',
1102            -127: b'\x81',
1103            -128: b'\x80',
1104            -129: b'\xff\x7f',
1105            127: b'\x7f',
1106            129: b'\x00\x81',
1107            -255: b'\xff\x01',
1108            -256: b'\xff\x00',
1109            255: b'\x00\xff',
1110            256: b'\x01\x00',
1111            32767: b'\x7f\xff',
1112            -32768: b'\xff\x80\x00',
1113            65535: b'\x00\xff\xff',
1114            -65536: b'\xff\x00\x00',
1115            -8388608: b'\x80\x00\x00'
1116        }
1117        check(tests1, 'big', signed=True)
1118
1119        # Convert integers to signed little-endian byte arrays.
1120        tests2 = {
1121            0: b'\x00',
1122            1: b'\x01',
1123            -1: b'\xff',
1124            -127: b'\x81',
1125            -128: b'\x80',
1126            -129: b'\x7f\xff',
1127            127: b'\x7f',
1128            129: b'\x81\x00',
1129            -255: b'\x01\xff',
1130            -256: b'\x00\xff',
1131            255: b'\xff\x00',
1132            256: b'\x00\x01',
1133            32767: b'\xff\x7f',
1134            -32768: b'\x00\x80',
1135            65535: b'\xff\xff\x00',
1136            -65536: b'\x00\x00\xff',
1137            -8388608: b'\x00\x00\x80'
1138        }
1139        check(tests2, 'little', signed=True)
1140
1141        # Convert integers to unsigned big-endian byte arrays.
1142        tests3 = {
1143            0: b'\x00',
1144            1: b'\x01',
1145            127: b'\x7f',
1146            128: b'\x80',
1147            255: b'\xff',
1148            256: b'\x01\x00',
1149            32767: b'\x7f\xff',
1150            32768: b'\x80\x00',
1151            65535: b'\xff\xff',
1152            65536: b'\x01\x00\x00'
1153        }
1154        check(tests3, 'big', signed=False)
1155
1156        # Convert integers to unsigned little-endian byte arrays.
1157        tests4 = {
1158            0: b'\x00',
1159            1: b'\x01',
1160            127: b'\x7f',
1161            128: b'\x80',
1162            255: b'\xff',
1163            256: b'\x00\x01',
1164            32767: b'\xff\x7f',
1165            32768: b'\x00\x80',
1166            65535: b'\xff\xff',
1167            65536: b'\x00\x00\x01'
1168        }
1169        check(tests4, 'little', signed=False)
1170
1171        self.assertRaises(OverflowError, (256).to_bytes, 1, 'big', signed=False)
1172        self.assertRaises(OverflowError, (256).to_bytes, 1, 'big', signed=True)
1173        self.assertRaises(OverflowError, (256).to_bytes, 1, 'little', signed=False)
1174        self.assertRaises(OverflowError, (256).to_bytes, 1, 'little', signed=True)
1175        self.assertRaises(OverflowError, (-1).to_bytes, 2, 'big', signed=False)
1176        self.assertRaises(OverflowError, (-1).to_bytes, 2, 'little', signed=False)
1177        self.assertEqual((0).to_bytes(0, 'big'), b'')
1178        self.assertEqual((1).to_bytes(5, 'big'), b'\x00\x00\x00\x00\x01')
1179        self.assertEqual((0).to_bytes(5, 'big'), b'\x00\x00\x00\x00\x00')
1180        self.assertEqual((-1).to_bytes(5, 'big', signed=True),
1181                         b'\xff\xff\xff\xff\xff')
1182        self.assertRaises(OverflowError, (1).to_bytes, 0, 'big')
1183
1184    def test_from_bytes(self):
1185        def check(tests, byteorder, signed=False):
1186            for test, expected in tests.items():
1187                try:
1188                    self.assertEqual(
1189                        int.from_bytes(test, byteorder, signed=signed),
1190                        expected)
1191                except Exception as err:
1192                    raise AssertionError(
1193                        "failed to convert {0} with byteorder={1!r} and signed={2}"
1194                        .format(test, byteorder, signed)) from err
1195
1196        # Convert signed big-endian byte arrays to integers.
1197        tests1 = {
1198            b'': 0,
1199            b'\x00': 0,
1200            b'\x00\x00': 0,
1201            b'\x01': 1,
1202            b'\x00\x01': 1,
1203            b'\xff': -1,
1204            b'\xff\xff': -1,
1205            b'\x81': -127,
1206            b'\x80': -128,
1207            b'\xff\x7f': -129,
1208            b'\x7f': 127,
1209            b'\x00\x81': 129,
1210            b'\xff\x01': -255,
1211            b'\xff\x00': -256,
1212            b'\x00\xff': 255,
1213            b'\x01\x00': 256,
1214            b'\x7f\xff': 32767,
1215            b'\x80\x00': -32768,
1216            b'\x00\xff\xff': 65535,
1217            b'\xff\x00\x00': -65536,
1218            b'\x80\x00\x00': -8388608
1219        }
1220        check(tests1, 'big', signed=True)
1221
1222        # Convert signed little-endian byte arrays to integers.
1223        tests2 = {
1224            b'': 0,
1225            b'\x00': 0,
1226            b'\x00\x00': 0,
1227            b'\x01': 1,
1228            b'\x00\x01': 256,
1229            b'\xff': -1,
1230            b'\xff\xff': -1,
1231            b'\x81': -127,
1232            b'\x80': -128,
1233            b'\x7f\xff': -129,
1234            b'\x7f': 127,
1235            b'\x81\x00': 129,
1236            b'\x01\xff': -255,
1237            b'\x00\xff': -256,
1238            b'\xff\x00': 255,
1239            b'\x00\x01': 256,
1240            b'\xff\x7f': 32767,
1241            b'\x00\x80': -32768,
1242            b'\xff\xff\x00': 65535,
1243            b'\x00\x00\xff': -65536,
1244            b'\x00\x00\x80': -8388608
1245        }
1246        check(tests2, 'little', signed=True)
1247
1248        # Convert unsigned big-endian byte arrays to integers.
1249        tests3 = {
1250            b'': 0,
1251            b'\x00': 0,
1252            b'\x01': 1,
1253            b'\x7f': 127,
1254            b'\x80': 128,
1255            b'\xff': 255,
1256            b'\x01\x00': 256,
1257            b'\x7f\xff': 32767,
1258            b'\x80\x00': 32768,
1259            b'\xff\xff': 65535,
1260            b'\x01\x00\x00': 65536,
1261        }
1262        check(tests3, 'big', signed=False)
1263
1264        # Convert integers to unsigned little-endian byte arrays.
1265        tests4 = {
1266            b'': 0,
1267            b'\x00': 0,
1268            b'\x01': 1,
1269            b'\x7f': 127,
1270            b'\x80': 128,
1271            b'\xff': 255,
1272            b'\x00\x01': 256,
1273            b'\xff\x7f': 32767,
1274            b'\x00\x80': 32768,
1275            b'\xff\xff': 65535,
1276            b'\x00\x00\x01': 65536,
1277        }
1278        check(tests4, 'little', signed=False)
1279
1280        class myint(int):
1281            pass
1282
1283        self.assertIs(type(myint.from_bytes(b'\x00', 'big')), myint)
1284        self.assertEqual(myint.from_bytes(b'\x01', 'big'), 1)
1285        self.assertIs(
1286            type(myint.from_bytes(b'\x00', 'big', signed=False)), myint)
1287        self.assertEqual(myint.from_bytes(b'\x01', 'big', signed=False), 1)
1288        self.assertIs(type(myint.from_bytes(b'\x00', 'little')), myint)
1289        self.assertEqual(myint.from_bytes(b'\x01', 'little'), 1)
1290        self.assertIs(type(myint.from_bytes(
1291            b'\x00', 'little', signed=False)), myint)
1292        self.assertEqual(myint.from_bytes(b'\x01', 'little', signed=False), 1)
1293        self.assertEqual(
1294            int.from_bytes([255, 0, 0], 'big', signed=True), -65536)
1295        self.assertEqual(
1296            int.from_bytes((255, 0, 0), 'big', signed=True), -65536)
1297        self.assertEqual(int.from_bytes(
1298            bytearray(b'\xff\x00\x00'), 'big', signed=True), -65536)
1299        self.assertEqual(int.from_bytes(
1300            bytearray(b'\xff\x00\x00'), 'big', signed=True), -65536)
1301        self.assertEqual(int.from_bytes(
1302            array.array('B', b'\xff\x00\x00'), 'big', signed=True), -65536)
1303        self.assertEqual(int.from_bytes(
1304            memoryview(b'\xff\x00\x00'), 'big', signed=True), -65536)
1305        self.assertRaises(ValueError, int.from_bytes, [256], 'big')
1306        self.assertRaises(ValueError, int.from_bytes, [0], 'big\x00')
1307        self.assertRaises(ValueError, int.from_bytes, [0], 'little\x00')
1308        self.assertRaises(TypeError, int.from_bytes, "", 'big')
1309        self.assertRaises(TypeError, int.from_bytes, "\x00", 'big')
1310        self.assertRaises(TypeError, int.from_bytes, 0, 'big')
1311        self.assertRaises(TypeError, int.from_bytes, 0, 'big', True)
1312        self.assertRaises(TypeError, myint.from_bytes, "", 'big')
1313        self.assertRaises(TypeError, myint.from_bytes, "\x00", 'big')
1314        self.assertRaises(TypeError, myint.from_bytes, 0, 'big')
1315        self.assertRaises(TypeError, int.from_bytes, 0, 'big', True)
1316
1317        class myint2(int):
1318            def __new__(cls, value):
1319                return int.__new__(cls, value + 1)
1320
1321        i = myint2.from_bytes(b'\x01', 'big')
1322        self.assertIs(type(i), myint2)
1323        self.assertEqual(i, 2)
1324
1325        class myint3(int):
1326            def __init__(self, value):
1327                self.foo = 'bar'
1328
1329        i = myint3.from_bytes(b'\x01', 'big')
1330        self.assertIs(type(i), myint3)
1331        self.assertEqual(i, 1)
1332        self.assertEqual(getattr(i, 'foo', 'none'), 'bar')
1333
1334    def test_access_to_nonexistent_digit_0(self):
1335        # http://bugs.python.org/issue14630: A bug in _PyLong_Copy meant that
1336        # ob_digit[0] was being incorrectly accessed for instances of a
1337        # subclass of int, with value 0.
1338        class Integer(int):
1339            def __new__(cls, value=0):
1340                self = int.__new__(cls, value)
1341                self.foo = 'foo'
1342                return self
1343
1344        integers = [Integer(0) for i in range(1000)]
1345        for n in map(int, integers):
1346            self.assertEqual(n, 0)
1347
1348    def test_shift_bool(self):
1349        # Issue #21422: ensure that bool << int and bool >> int return int
1350        for value in (True, False):
1351            for shift in (0, 2):
1352                self.assertEqual(type(value << shift), int)
1353                self.assertEqual(type(value >> shift), int)
1354
1355
1356if __name__ == "__main__":
1357    unittest.main()
1358