Issue #7435: Remove duplicate int/long tests, and other

references to long in py3k.  Patch provided by flox.
This commit is contained in:
Mark Dickinson 2009-12-05 20:28:34 +00:00
parent c39aad7c27
commit 5c2db37c20
14 changed files with 64 additions and 607 deletions

View file

@ -97,7 +97,7 @@ class Random(_random.Random):
None or no argument seeds from current time or from an operating None or no argument seeds from current time or from an operating
system specific randomness source if available. system specific randomness source if available.
If a is not None or an int or long, hash(a) is used instead. If a is not None or an int, hash(a) is used instead.
""" """
if a is None: if a is None:

View file

@ -528,13 +528,6 @@ class TestMappingProtocol(BasicTestMappingProtocol):
d = self._empty_mapping() d = self._empty_mapping()
k, v = 'abc', 'def' k, v = 'abc', 'def'
# verify longs/ints get same value when key > 32 bits (for 64-bit archs)
# see SF bug #689659
x = 4503599627370496
y = 4503599627370496
h = self._full_mapping({x: 'anything', y: 'something else'})
self.assertEqual(h[x], h[y])
self.assertEqual(d.pop(k, v), v) self.assertEqual(d.pop(k, v), v)
d[k] = v d[k] = v
self.assertEqual(d.pop(k, 1), v) self.assertEqual(d.pop(k, 1), v)

View file

@ -1041,9 +1041,6 @@ class REX_five(object):
class MyInt(int): class MyInt(int):
sample = 1 sample = 1
class MyLong(int):
sample = 1
class MyFloat(float): class MyFloat(float):
sample = 1.0 sample = 1.0
@ -1065,7 +1062,7 @@ class MyList(list):
class MyDict(dict): class MyDict(dict):
sample = {"a": 1, "b": 2} sample = {"a": 1, "b": 2}
myclasses = [MyInt, MyLong, MyFloat, myclasses = [MyInt, MyFloat,
MyComplex, MyComplex,
MyStr, MyUnicode, MyStr, MyUnicode,
MyTuple, MyList, MyDict] MyTuple, MyList, MyDict]

View file

@ -1071,7 +1071,6 @@ class MixinStrUnicodeUserStringTest:
longvalue = sys.maxsize + 10 longvalue = sys.maxsize + 10
slongvalue = str(longvalue) slongvalue = str(longvalue)
if slongvalue[-1] in ("L","l"): slongvalue = slongvalue[:-1]
self.checkequal(' 42', '%3ld', '__mod__', 42) self.checkequal(' 42', '%3ld', '__mod__', 42)
self.checkequal('42', '%d', '__mod__', 42.0) self.checkequal('42', '%d', '__mod__', 42.0)
self.checkequal(slongvalue, '%d', '__mod__', longvalue) self.checkequal(slongvalue, '%d', '__mod__', longvalue)
@ -1086,7 +1085,7 @@ class MixinStrUnicodeUserStringTest:
self.checkraises(ValueError, '%(foo', '__mod__', {}) self.checkraises(ValueError, '%(foo', '__mod__', {})
self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42)) self.checkraises(TypeError, '%(foo)s %(bar)s', '__mod__', ('foo', 42))
self.checkraises(TypeError, '%d', '__mod__', "42") # not numeric self.checkraises(TypeError, '%d', '__mod__', "42") # not numeric
self.checkraises(TypeError, '%d', '__mod__', (42+0j)) # no int/long conversion provided self.checkraises(TypeError, '%d', '__mod__', (42+0j)) # no int conversion provided
# argument names with properly nested brackets are supported # argument names with properly nested brackets are supported
self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'}) self.checkequal('bar', '%((foo))s', '__mod__', {'(foo)': 'bar'})

View file

@ -11,8 +11,8 @@ def gcd(a, b):
return b return b
def isint(x): def isint(x):
"""Test whether an object is an instance of int or long.""" """Test whether an object is an instance of int."""
return isinstance(x, int) or isinstance(x, int) return isinstance(x, int)
def isnum(x): def isnum(x):
"""Test whether an object is an instance of a built-in numeric type.""" """Test whether an object is an instance of a built-in numeric type."""
@ -27,18 +27,18 @@ def isRat(x):
class Rat(object): class Rat(object):
"""Rational number implemented as a normalized pair of longs.""" """Rational number implemented as a normalized pair of ints."""
__slots__ = ['_Rat__num', '_Rat__den'] __slots__ = ['_Rat__num', '_Rat__den']
def __init__(self, num=0, den=1): def __init__(self, num=0, den=1):
"""Constructor: Rat([num[, den]]). """Constructor: Rat([num[, den]]).
The arguments must be ints or longs, and default to (0, 1).""" The arguments must be ints, and default to (0, 1)."""
if not isint(num): if not isint(num):
raise TypeError("Rat numerator must be int or long (%r)" % num) raise TypeError("Rat numerator must be int (%r)" % num)
if not isint(den): if not isint(den):
raise TypeError("Rat denominator must be int or long (%r)" % den) raise TypeError("Rat denominator must be int (%r)" % den)
# But the zero is always on # But the zero is always on
if den == 0: if den == 0:
raise ZeroDivisionError("zero denominator") raise ZeroDivisionError("zero denominator")
@ -217,9 +217,6 @@ class RatTestCase(unittest.TestCase):
self.assertTrue(gcd(-i, -j) < 0) self.assertTrue(gcd(-i, -j) < 0)
def test_constructor(self): def test_constructor(self):
a = Rat(10, 15)
self.assertEqual(a.num, 2)
self.assertEqual(a.den, 3)
a = Rat(10, 15) a = Rat(10, 15)
self.assertEqual(a.num, 2) self.assertEqual(a.num, 2)
self.assertEqual(a.den, 3) self.assertEqual(a.den, 3)

View file

@ -126,10 +126,6 @@ class BuiltinTest(unittest.TestCase):
self.assertEqual(abs(0.0), 0.0) self.assertEqual(abs(0.0), 0.0)
self.assertEqual(abs(3.14), 3.14) self.assertEqual(abs(3.14), 3.14)
self.assertEqual(abs(-3.14), 3.14) self.assertEqual(abs(-3.14), 3.14)
# long
self.assertEqual(abs(0), 0)
self.assertEqual(abs(1234), 1234)
self.assertEqual(abs(-1234), 1234)
# str # str
self.assertRaises(TypeError, abs, 'a') self.assertRaises(TypeError, abs, 'a')
@ -164,7 +160,6 @@ class BuiltinTest(unittest.TestCase):
def test_ascii(self): def test_ascii(self):
self.assertEqual(ascii(''), '\'\'') self.assertEqual(ascii(''), '\'\'')
self.assertEqual(ascii(0), '0') self.assertEqual(ascii(0), '0')
self.assertEqual(ascii(0), '0')
self.assertEqual(ascii(()), '()') self.assertEqual(ascii(()), '()')
self.assertEqual(ascii([]), '[]') self.assertEqual(ascii([]), '[]')
self.assertEqual(ascii({}), '{}') self.assertEqual(ascii({}), '{}')
@ -322,18 +317,7 @@ class BuiltinTest(unittest.TestCase):
self.assertEqual(divmod(12, -7), (-2, -2)) self.assertEqual(divmod(12, -7), (-2, -2))
self.assertEqual(divmod(-12, -7), (1, -5)) self.assertEqual(divmod(-12, -7), (1, -5))
self.assertEqual(divmod(12, 7), (1, 5)) self.assertEqual(divmod(-sys.maxsize-1, -1), (sys.maxsize+1, 0))
self.assertEqual(divmod(-12, 7), (-2, 2))
self.assertEqual(divmod(12, -7), (-2, -2))
self.assertEqual(divmod(-12, -7), (1, -5))
self.assertEqual(divmod(12, 7), (1, 5))
self.assertEqual(divmod(-12, 7), (-2, 2))
self.assertEqual(divmod(12, -7), (-2, -2))
self.assertEqual(divmod(-12, -7), (1, -5))
self.assertEqual(divmod(-sys.maxsize-1, -1),
(sys.maxsize+1, 0))
self.assertTrue(not fcmp(divmod(3.25, 1.0), (3.0, 0.25))) self.assertTrue(not fcmp(divmod(3.25, 1.0), (3.0, 0.25)))
self.assertTrue(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75))) self.assertTrue(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75)))
@ -528,10 +512,6 @@ class BuiltinTest(unittest.TestCase):
def __hash__(self): def __hash__(self):
return 2**100 return 2**100
self.assertEquals(type(hash(X())), int) self.assertEquals(type(hash(X())), int)
class Y(object):
def __hash__(self):
return 2**100
self.assertEquals(type(hash(Y())), int)
class Z(int): class Z(int):
def __hash__(self): def __hash__(self):
return self return self
@ -539,15 +519,12 @@ class BuiltinTest(unittest.TestCase):
def test_hex(self): def test_hex(self):
self.assertEqual(hex(16), '0x10') self.assertEqual(hex(16), '0x10')
self.assertEqual(hex(16), '0x10')
self.assertEqual(hex(-16), '-0x10')
self.assertEqual(hex(-16), '-0x10') self.assertEqual(hex(-16), '-0x10')
self.assertRaises(TypeError, hex, {}) self.assertRaises(TypeError, hex, {})
def test_id(self): def test_id(self):
id(None) id(None)
id(1) id(1)
id(1)
id(1.0) id(1.0)
id('spam') id('spam')
id((0,1,2,3)) id((0,1,2,3))
@ -790,8 +767,6 @@ class BuiltinTest(unittest.TestCase):
def test_oct(self): def test_oct(self):
self.assertEqual(oct(100), '0o144') self.assertEqual(oct(100), '0o144')
self.assertEqual(oct(100), '0o144')
self.assertEqual(oct(-100), '-0o144')
self.assertEqual(oct(-100), '-0o144') self.assertEqual(oct(-100), '-0o144')
self.assertRaises(TypeError, oct, ()) self.assertRaises(TypeError, oct, ())
@ -799,7 +774,6 @@ class BuiltinTest(unittest.TestCase):
# NB the first 4 lines are also used to test input, below # NB the first 4 lines are also used to test input, below
fp = open(TESTFN, 'w') fp = open(TESTFN, 'w')
try: try:
fp.write('1+1\n')
fp.write('1+1\n') fp.write('1+1\n')
fp.write('The quick brown fox jumps over the lazy dog') fp.write('The quick brown fox jumps over the lazy dog')
fp.write('.\n') fp.write('.\n')
@ -813,7 +787,6 @@ class BuiltinTest(unittest.TestCase):
self.write_testfile() self.write_testfile()
fp = open(TESTFN, 'r') fp = open(TESTFN, 'r')
try: try:
self.assertEqual(fp.readline(4), '1+1\n')
self.assertEqual(fp.readline(4), '1+1\n') self.assertEqual(fp.readline(4), '1+1\n')
self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n') self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n')
self.assertEqual(fp.readline(4), 'Dear') self.assertEqual(fp.readline(4), 'Dear')
@ -867,21 +840,6 @@ class BuiltinTest(unittest.TestCase):
self.assertEqual(pow(-2,2), 4) self.assertEqual(pow(-2,2), 4)
self.assertEqual(pow(-2,3), -8) self.assertEqual(pow(-2,3), -8)
self.assertEqual(pow(0,0), 1)
self.assertEqual(pow(0,1), 0)
self.assertEqual(pow(1,0), 1)
self.assertEqual(pow(1,1), 1)
self.assertEqual(pow(2,0), 1)
self.assertEqual(pow(2,10), 1024)
self.assertEqual(pow(2,20), 1024*1024)
self.assertEqual(pow(2,30), 1024*1024*1024)
self.assertEqual(pow(-2,0), 1)
self.assertEqual(pow(-2,1), -2)
self.assertEqual(pow(-2,2), 4)
self.assertEqual(pow(-2,3), -8)
self.assertAlmostEqual(pow(0.,0), 1.) self.assertAlmostEqual(pow(0.,0), 1.)
self.assertAlmostEqual(pow(0.,1), 0.) self.assertAlmostEqual(pow(0.,1), 0.)
self.assertAlmostEqual(pow(1.,0), 1.) self.assertAlmostEqual(pow(1.,0), 1.)
@ -897,9 +855,9 @@ class BuiltinTest(unittest.TestCase):
self.assertAlmostEqual(pow(-2.,2), 4.) self.assertAlmostEqual(pow(-2.,2), 4.)
self.assertAlmostEqual(pow(-2.,3), -8.) self.assertAlmostEqual(pow(-2.,3), -8.)
for x in 2, 2, 2.0: for x in 2, 2.0:
for y in 10, 10, 10.0: for y in 10, 10.0:
for z in 1000, 1000, 1000.0: for z in 1000, 1000.0:
if isinstance(x, float) or \ if isinstance(x, float) or \
isinstance(y, float) or \ isinstance(y, float) or \
isinstance(z, float): isinstance(z, float):
@ -910,8 +868,6 @@ class BuiltinTest(unittest.TestCase):
self.assertAlmostEqual(pow(-1, 0.5), 1j) self.assertAlmostEqual(pow(-1, 0.5), 1j)
self.assertAlmostEqual(pow(-1, 1/3), 0.5 + 0.8660254037844386j) self.assertAlmostEqual(pow(-1, 1/3), 0.5 + 0.8660254037844386j)
self.assertRaises(TypeError, pow, -1, -2, 3)
self.assertRaises(ValueError, pow, 1, 2, 0)
self.assertRaises(TypeError, pow, -1, -2, 3) self.assertRaises(TypeError, pow, -1, -2, 3)
self.assertRaises(ValueError, pow, 1, 2, 0) self.assertRaises(ValueError, pow, 1, 2, 0)
@ -943,7 +899,6 @@ class BuiltinTest(unittest.TestCase):
self.assertEqual(len(x), 4) self.assertEqual(len(x), 4)
self.assertEqual(len(list(x)), 4) self.assertEqual(len(list(x)), 4)
""" XXX(nnorwitz):
# Now test range() with longs # Now test range() with longs
self.assertEqual(list(range(-2**100)), []) self.assertEqual(list(range(-2**100)), [])
self.assertEqual(list(range(0, -2**100)), []) self.assertEqual(list(range(0, -2**100)), [])
@ -978,6 +933,7 @@ class BuiltinTest(unittest.TestCase):
self.assertRaises(ValueError, range, 1, 2, 0) self.assertRaises(ValueError, range, 1, 2, 0)
self.assertRaises(ValueError, range, a, a + 1, int(0)) self.assertRaises(ValueError, range, a, a + 1, int(0))
""" XXX(nnorwitz):
class badzero(int): class badzero(int):
def __eq__(self, other): def __eq__(self, other):
raise RuntimeError raise RuntimeError
@ -1008,7 +964,6 @@ class BuiltinTest(unittest.TestCase):
sys.stdin = fp sys.stdin = fp
sys.stdout = BitBucket() sys.stdout = BitBucket()
self.assertEqual(input(), "1+1") self.assertEqual(input(), "1+1")
self.assertEqual(input('testing\n'), "1+1")
self.assertEqual(input(), 'The quick brown fox jumps over the lazy dog.') self.assertEqual(input(), 'The quick brown fox jumps over the lazy dog.')
self.assertEqual(input('testing\n'), 'Dear John') self.assertEqual(input('testing\n'), 'Dear John')
@ -1039,7 +994,6 @@ class BuiltinTest(unittest.TestCase):
def test_repr(self): def test_repr(self):
self.assertEqual(repr(''), '\'\'') self.assertEqual(repr(''), '\'\'')
self.assertEqual(repr(0), '0') self.assertEqual(repr(0), '0')
self.assertEqual(repr(0), '0')
self.assertEqual(repr(()), '()') self.assertEqual(repr(()), '()')
self.assertEqual(repr([]), '[]') self.assertEqual(repr([]), '[]')
self.assertEqual(repr({}), '{}') self.assertEqual(repr({}), '{}')

View file

@ -22,7 +22,7 @@ assert len(pickle_choices) == 3
# An arbitrary collection of objects of non-datetime types, for testing # An arbitrary collection of objects of non-datetime types, for testing
# mixed-type comparisons. # mixed-type comparisons.
OTHERSTUFF = (10, 10, 34.5, "abc", {}, [], ()) OTHERSTUFF = (10, 34.5, "abc", {}, [], ())
############################################################################# #############################################################################
@ -232,8 +232,8 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
def test_disallowed_computations(self): def test_disallowed_computations(self):
a = timedelta(42) a = timedelta(42)
# Add/sub ints, longs, floats should be illegal # Add/sub ints or floats should be illegal
for i in 1, 1, 1.0: for i in 1, 1.0:
self.assertRaises(TypeError, lambda: a+i) self.assertRaises(TypeError, lambda: a+i)
self.assertRaises(TypeError, lambda: a-i) self.assertRaises(TypeError, lambda: a-i)
self.assertRaises(TypeError, lambda: i+a) self.assertRaises(TypeError, lambda: i+a)
@ -250,9 +250,9 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
# Division of int by timedelta doesn't make sense. # Division of int by timedelta doesn't make sense.
# Division by zero doesn't make sense. # Division by zero doesn't make sense.
for zero in 0, 0: zero = 0
self.assertRaises(TypeError, lambda: zero // a) self.assertRaises(TypeError, lambda: zero // a)
self.assertRaises(ZeroDivisionError, lambda: a // zero) self.assertRaises(ZeroDivisionError, lambda: a // zero)
def test_basic_attributes(self): def test_basic_attributes(self):
days, seconds, us = 1, 7, 31 days, seconds, us = 1, 7, 31
@ -685,8 +685,8 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase):
self.assertEqual(a - (a - week), week) self.assertEqual(a - (a - week), week)
self.assertEqual(a - (a - day), day) self.assertEqual(a - (a - day), day)
# Add/sub ints, longs, floats should be illegal # Add/sub ints or floats should be illegal
for i in 1, 1, 1.0: for i in 1, 1.0:
self.assertRaises(TypeError, lambda: a+i) self.assertRaises(TypeError, lambda: a+i)
self.assertRaises(TypeError, lambda: a-i) self.assertRaises(TypeError, lambda: a-i)
self.assertRaises(TypeError, lambda: i+a) self.assertRaises(TypeError, lambda: i+a)
@ -1376,8 +1376,8 @@ class TestDateTime(TestDate):
self.theclass(2002, 2, 22, 16, 5, 59, 999000)) self.theclass(2002, 2, 22, 16, 5, 59, 999000))
self.assertEqual(a - (week + day + hour + millisec), self.assertEqual(a - (week + day + hour + millisec),
(((a - week) - day) - hour) - millisec) (((a - week) - day) - hour) - millisec)
# Add/sub ints, longs, floats should be illegal # Add/sub ints or floats should be illegal
for i in 1, 1, 1.0: for i in 1, 1.0:
self.assertRaises(TypeError, lambda: a+i) self.assertRaises(TypeError, lambda: a+i)
self.assertRaises(TypeError, lambda: a-i) self.assertRaises(TypeError, lambda: a-i)
self.assertRaises(TypeError, lambda: i+a) self.assertRaises(TypeError, lambda: i+a)

View file

@ -1274,7 +1274,7 @@ class DecimalUsabilityTest(unittest.TestCase):
self.assertEqual(repr(d), "Decimal('15.32')") # repr self.assertEqual(repr(d), "Decimal('15.32')") # repr
def test_tonum_methods(self): def test_tonum_methods(self):
#Test float, int and long methods. #Test float and int methods.
d1 = Decimal('66') d1 = Decimal('66')
d2 = Decimal('15.32') d2 = Decimal('15.32')
@ -1283,10 +1283,6 @@ class DecimalUsabilityTest(unittest.TestCase):
self.assertEqual(int(d1), 66) self.assertEqual(int(d1), 66)
self.assertEqual(int(d2), 15) self.assertEqual(int(d2), 15)
#long
self.assertEqual(int(d1), 66)
self.assertEqual(int(d2), 15)
#float #float
self.assertEqual(float(d1), 66) self.assertEqual(float(d1), 66)
self.assertEqual(float(d2), 15.32) self.assertEqual(float(d2), 15.32)

View file

@ -248,10 +248,6 @@ class OperatorsTest(unittest.TestCase):
else: else:
self.fail("NotImplemented should have caused TypeError") self.fail("NotImplemented should have caused TypeError")
def test_longs(self):
# Testing long operations...
self.number_operators(100, 3)
def test_floats(self): def test_floats(self):
# Testing float operations... # Testing float operations...
self.number_operators(100.0, 3.0) self.number_operators(100.0, 3.0)
@ -259,7 +255,7 @@ class OperatorsTest(unittest.TestCase):
def test_complexes(self): def test_complexes(self):
# Testing complex operations... # Testing complex operations...
self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
'int', 'long', 'float', 'int', 'float',
'divmod', 'mod']) 'divmod', 'mod'])
class Number(complex): class Number(complex):
@ -1162,15 +1158,6 @@ order (MRO) for bases """
self.assertEqual(I(3)*2, 6) self.assertEqual(I(3)*2, 6)
self.assertEqual(I(3)*I(2), 6) self.assertEqual(I(3)*I(2), 6)
# Test handling of long*seq and seq*long
class L(int):
pass
self.assertEqual("a"*L(2), "aa")
self.assertEqual(L(2)*"a", "aa")
self.assertEqual(2*L(3), 6)
self.assertEqual(L(3)*2, 6)
self.assertEqual(L(3)*L(2), 6)
# Test comparison of classes with dynamic metaclasses # Test comparison of classes with dynamic metaclasses
class dynamicmetaclass(type): class dynamicmetaclass(type):
pass pass
@ -2231,10 +2218,7 @@ order (MRO) for bases """
class octlong(int): class octlong(int):
__slots__ = [] __slots__ = []
def __str__(self): def __str__(self):
s = oct(self) return oct(self)
if s[-1] == 'L':
s = s[:-1]
return s
def __add__(self, other): def __add__(self, other):
return self.__class__(super(octlong, self).__add__(other)) return self.__class__(super(octlong, self).__add__(other))
__radd__ = __add__ __radd__ = __add__

View file

@ -328,13 +328,6 @@ class DictTest(unittest.TestCase):
self.assertRaises(KeyError, d.pop, k) self.assertRaises(KeyError, d.pop, k)
# verify longs/ints get same value when key > 32 bits (for 64-bit archs)
# see SF bug #689659
x = 4503599627370496
y = 4503599627370496
h = {x: 'anything', y: 'something else'}
self.assertEqual(h[x], h[y])
self.assertEqual(d.pop(k, v), v) self.assertEqual(d.pop(k, v), v)
d[k] = v d[k] = v
self.assertEqual(d.pop(k, 1), v) self.assertEqual(d.pop(k, 1), v)

View file

@ -55,10 +55,6 @@ LLONG_MAX = 2**63-1
LLONG_MIN = -2**63 LLONG_MIN = -2**63
ULLONG_MAX = 2**64-1 ULLONG_MAX = 2**64-1
class Long:
def __int__(self):
return 99
class Int: class Int:
def __int__(self): def __int__(self):
return 99 return 99
@ -68,7 +64,6 @@ class Unsigned_TestCase(unittest.TestCase):
from _testcapi import getargs_b from _testcapi import getargs_b
# b returns 'unsigned char', and does range checking (0 ... UCHAR_MAX) # b returns 'unsigned char', and does range checking (0 ... UCHAR_MAX)
self.assertRaises(TypeError, getargs_b, 3.14) self.assertRaises(TypeError, getargs_b, 3.14)
self.assertEqual(99, getargs_b(Long()))
self.assertEqual(99, getargs_b(Int())) self.assertEqual(99, getargs_b(Int()))
self.assertRaises(OverflowError, getargs_b, -1) self.assertRaises(OverflowError, getargs_b, -1)
@ -76,7 +71,6 @@ class Unsigned_TestCase(unittest.TestCase):
self.assertEqual(UCHAR_MAX, getargs_b(UCHAR_MAX)) self.assertEqual(UCHAR_MAX, getargs_b(UCHAR_MAX))
self.assertRaises(OverflowError, getargs_b, UCHAR_MAX + 1) self.assertRaises(OverflowError, getargs_b, UCHAR_MAX + 1)
self.assertEqual(42, getargs_b(42))
self.assertEqual(42, getargs_b(42)) self.assertEqual(42, getargs_b(42))
self.assertRaises(OverflowError, getargs_b, VERY_LARGE) self.assertRaises(OverflowError, getargs_b, VERY_LARGE)
@ -84,16 +78,13 @@ class Unsigned_TestCase(unittest.TestCase):
from _testcapi import getargs_B from _testcapi import getargs_B
# B returns 'unsigned char', no range checking # B returns 'unsigned char', no range checking
self.assertRaises(TypeError, getargs_B, 3.14) self.assertRaises(TypeError, getargs_B, 3.14)
self.assertEqual(99, getargs_B(Long()))
self.assertEqual(99, getargs_B(Int())) self.assertEqual(99, getargs_B(Int()))
self.assertEqual(UCHAR_MAX, getargs_B(-1))
self.assertEqual(UCHAR_MAX, getargs_B(-1)) self.assertEqual(UCHAR_MAX, getargs_B(-1))
self.assertEqual(0, getargs_B(0)) self.assertEqual(0, getargs_B(0))
self.assertEqual(UCHAR_MAX, getargs_B(UCHAR_MAX)) self.assertEqual(UCHAR_MAX, getargs_B(UCHAR_MAX))
self.assertEqual(0, getargs_B(UCHAR_MAX+1)) self.assertEqual(0, getargs_B(UCHAR_MAX+1))
self.assertEqual(42, getargs_B(42))
self.assertEqual(42, getargs_B(42)) self.assertEqual(42, getargs_B(42))
self.assertEqual(UCHAR_MAX & VERY_LARGE, getargs_B(VERY_LARGE)) self.assertEqual(UCHAR_MAX & VERY_LARGE, getargs_B(VERY_LARGE))
@ -101,7 +92,6 @@ class Unsigned_TestCase(unittest.TestCase):
from _testcapi import getargs_H from _testcapi import getargs_H
# H returns 'unsigned short', no range checking # H returns 'unsigned short', no range checking
self.assertRaises(TypeError, getargs_H, 3.14) self.assertRaises(TypeError, getargs_H, 3.14)
self.assertEqual(99, getargs_H(Long()))
self.assertEqual(99, getargs_H(Int())) self.assertEqual(99, getargs_H(Int()))
self.assertEqual(USHRT_MAX, getargs_H(-1)) self.assertEqual(USHRT_MAX, getargs_H(-1))
@ -109,7 +99,6 @@ class Unsigned_TestCase(unittest.TestCase):
self.assertEqual(USHRT_MAX, getargs_H(USHRT_MAX)) self.assertEqual(USHRT_MAX, getargs_H(USHRT_MAX))
self.assertEqual(0, getargs_H(USHRT_MAX+1)) self.assertEqual(0, getargs_H(USHRT_MAX+1))
self.assertEqual(42, getargs_H(42))
self.assertEqual(42, getargs_H(42)) self.assertEqual(42, getargs_H(42))
self.assertEqual(VERY_LARGE & USHRT_MAX, getargs_H(VERY_LARGE)) self.assertEqual(VERY_LARGE & USHRT_MAX, getargs_H(VERY_LARGE))
@ -118,7 +107,6 @@ class Unsigned_TestCase(unittest.TestCase):
from _testcapi import getargs_I from _testcapi import getargs_I
# I returns 'unsigned int', no range checking # I returns 'unsigned int', no range checking
self.assertRaises(TypeError, getargs_I, 3.14) self.assertRaises(TypeError, getargs_I, 3.14)
self.assertEqual(99, getargs_I(Long()))
self.assertEqual(99, getargs_I(Int())) self.assertEqual(99, getargs_I(Int()))
self.assertEqual(UINT_MAX, getargs_I(-1)) self.assertEqual(UINT_MAX, getargs_I(-1))
@ -126,7 +114,6 @@ class Unsigned_TestCase(unittest.TestCase):
self.assertEqual(UINT_MAX, getargs_I(UINT_MAX)) self.assertEqual(UINT_MAX, getargs_I(UINT_MAX))
self.assertEqual(0, getargs_I(UINT_MAX+1)) self.assertEqual(0, getargs_I(UINT_MAX+1))
self.assertEqual(42, getargs_I(42))
self.assertEqual(42, getargs_I(42)) self.assertEqual(42, getargs_I(42))
self.assertEqual(VERY_LARGE & UINT_MAX, getargs_I(VERY_LARGE)) self.assertEqual(VERY_LARGE & UINT_MAX, getargs_I(VERY_LARGE))
@ -136,7 +123,6 @@ class Unsigned_TestCase(unittest.TestCase):
# k returns 'unsigned long', no range checking # k returns 'unsigned long', no range checking
# it does not accept float, or instances with __int__ # it does not accept float, or instances with __int__
self.assertRaises(TypeError, getargs_k, 3.14) self.assertRaises(TypeError, getargs_k, 3.14)
self.assertRaises(TypeError, getargs_k, Long())
self.assertRaises(TypeError, getargs_k, Int()) self.assertRaises(TypeError, getargs_k, Int())
self.assertEqual(ULONG_MAX, getargs_k(-1)) self.assertEqual(ULONG_MAX, getargs_k(-1))
@ -144,7 +130,6 @@ class Unsigned_TestCase(unittest.TestCase):
self.assertEqual(ULONG_MAX, getargs_k(ULONG_MAX)) self.assertEqual(ULONG_MAX, getargs_k(ULONG_MAX))
self.assertEqual(0, getargs_k(ULONG_MAX+1)) self.assertEqual(0, getargs_k(ULONG_MAX+1))
self.assertEqual(42, getargs_k(42))
self.assertEqual(42, getargs_k(42)) self.assertEqual(42, getargs_k(42))
self.assertEqual(VERY_LARGE & ULONG_MAX, getargs_k(VERY_LARGE)) self.assertEqual(VERY_LARGE & ULONG_MAX, getargs_k(VERY_LARGE))
@ -154,7 +139,6 @@ class Signed_TestCase(unittest.TestCase):
from _testcapi import getargs_i from _testcapi import getargs_i
# i returns 'int', and does range checking (INT_MIN ... INT_MAX) # i returns 'int', and does range checking (INT_MIN ... INT_MAX)
self.assertRaises(TypeError, getargs_i, 3.14) self.assertRaises(TypeError, getargs_i, 3.14)
self.assertEqual(99, getargs_i(Long()))
self.assertEqual(99, getargs_i(Int())) self.assertEqual(99, getargs_i(Int()))
self.assertRaises(OverflowError, getargs_i, INT_MIN-1) self.assertRaises(OverflowError, getargs_i, INT_MIN-1)
@ -162,7 +146,6 @@ class Signed_TestCase(unittest.TestCase):
self.assertEqual(INT_MAX, getargs_i(INT_MAX)) self.assertEqual(INT_MAX, getargs_i(INT_MAX))
self.assertRaises(OverflowError, getargs_i, INT_MAX+1) self.assertRaises(OverflowError, getargs_i, INT_MAX+1)
self.assertEqual(42, getargs_i(42))
self.assertEqual(42, getargs_i(42)) self.assertEqual(42, getargs_i(42))
self.assertRaises(OverflowError, getargs_i, VERY_LARGE) self.assertRaises(OverflowError, getargs_i, VERY_LARGE)
@ -170,7 +153,6 @@ class Signed_TestCase(unittest.TestCase):
from _testcapi import getargs_l from _testcapi import getargs_l
# l returns 'long', and does range checking (LONG_MIN ... LONG_MAX) # l returns 'long', and does range checking (LONG_MIN ... LONG_MAX)
self.assertRaises(TypeError, getargs_l, 3.14) self.assertRaises(TypeError, getargs_l, 3.14)
self.assertEqual(99, getargs_l(Long()))
self.assertEqual(99, getargs_l(Int())) self.assertEqual(99, getargs_l(Int()))
self.assertRaises(OverflowError, getargs_l, LONG_MIN-1) self.assertRaises(OverflowError, getargs_l, LONG_MIN-1)
@ -178,7 +160,6 @@ class Signed_TestCase(unittest.TestCase):
self.assertEqual(LONG_MAX, getargs_l(LONG_MAX)) self.assertEqual(LONG_MAX, getargs_l(LONG_MAX))
self.assertRaises(OverflowError, getargs_l, LONG_MAX+1) self.assertRaises(OverflowError, getargs_l, LONG_MAX+1)
self.assertEqual(42, getargs_l(42))
self.assertEqual(42, getargs_l(42)) self.assertEqual(42, getargs_l(42))
self.assertRaises(OverflowError, getargs_l, VERY_LARGE) self.assertRaises(OverflowError, getargs_l, VERY_LARGE)
@ -187,7 +168,6 @@ class Signed_TestCase(unittest.TestCase):
# n returns 'Py_ssize_t', and does range checking # n returns 'Py_ssize_t', and does range checking
# (PY_SSIZE_T_MIN ... PY_SSIZE_T_MAX) # (PY_SSIZE_T_MIN ... PY_SSIZE_T_MAX)
self.assertRaises(TypeError, getargs_n, 3.14) self.assertRaises(TypeError, getargs_n, 3.14)
self.assertRaises(TypeError, getargs_n, Long())
self.assertRaises(TypeError, getargs_n, Int()) self.assertRaises(TypeError, getargs_n, Int())
self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MIN-1) self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MIN-1)
@ -195,7 +175,6 @@ class Signed_TestCase(unittest.TestCase):
self.assertEqual(PY_SSIZE_T_MAX, getargs_n(PY_SSIZE_T_MAX)) self.assertEqual(PY_SSIZE_T_MAX, getargs_n(PY_SSIZE_T_MAX))
self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MAX+1) self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MAX+1)
self.assertEqual(42, getargs_n(42))
self.assertEqual(42, getargs_n(42)) self.assertEqual(42, getargs_n(42))
self.assertRaises(OverflowError, getargs_n, VERY_LARGE) self.assertRaises(OverflowError, getargs_n, VERY_LARGE)
@ -206,7 +185,6 @@ class LongLong_TestCase(unittest.TestCase):
# L returns 'long long', and does range checking (LLONG_MIN ... LLONG_MAX) # L returns 'long long', and does range checking (LLONG_MIN ... LLONG_MAX)
self.assertRaises(TypeError, getargs_L, "Hello") self.assertRaises(TypeError, getargs_L, "Hello")
self.assertEqual(3, getargs_L(3.14)) self.assertEqual(3, getargs_L(3.14))
self.assertEqual(99, getargs_L(Long()))
self.assertEqual(99, getargs_L(Int())) self.assertEqual(99, getargs_L(Int()))
self.assertRaises(OverflowError, getargs_L, LLONG_MIN-1) self.assertRaises(OverflowError, getargs_L, LLONG_MIN-1)
@ -214,7 +192,6 @@ class LongLong_TestCase(unittest.TestCase):
self.assertEqual(LLONG_MAX, getargs_L(LLONG_MAX)) self.assertEqual(LLONG_MAX, getargs_L(LLONG_MAX))
self.assertRaises(OverflowError, getargs_L, LLONG_MAX+1) self.assertRaises(OverflowError, getargs_L, LLONG_MAX+1)
self.assertEqual(42, getargs_L(42))
self.assertEqual(42, getargs_L(42)) self.assertEqual(42, getargs_L(42))
self.assertRaises(OverflowError, getargs_L, VERY_LARGE) self.assertRaises(OverflowError, getargs_L, VERY_LARGE)
@ -222,13 +199,11 @@ class LongLong_TestCase(unittest.TestCase):
from _testcapi import getargs_K from _testcapi import getargs_K
# K return 'unsigned long long', no range checking # K return 'unsigned long long', no range checking
self.assertRaises(TypeError, getargs_K, 3.14) self.assertRaises(TypeError, getargs_K, 3.14)
self.assertRaises(TypeError, getargs_K, Long())
self.assertRaises(TypeError, getargs_K, Int()) self.assertRaises(TypeError, getargs_K, Int())
self.assertEqual(ULLONG_MAX, getargs_K(ULLONG_MAX)) self.assertEqual(ULLONG_MAX, getargs_K(ULLONG_MAX))
self.assertEqual(0, getargs_K(0)) self.assertEqual(0, getargs_K(0))
self.assertEqual(0, getargs_K(ULLONG_MAX+1)) self.assertEqual(0, getargs_K(ULLONG_MAX+1))
self.assertEqual(42, getargs_K(42))
self.assertEqual(42, getargs_K(42)) self.assertEqual(42, getargs_K(42))
self.assertEqual(VERY_LARGE & ULLONG_MAX, getargs_K(VERY_LARGE)) self.assertEqual(VERY_LARGE & ULLONG_MAX, getargs_K(VERY_LARGE))

View file

@ -34,6 +34,7 @@ class IntTestCases(unittest.TestCase):
self.assertEqual(int(-3.9), -3) self.assertEqual(int(-3.9), -3)
self.assertEqual(int(3.5), 3) self.assertEqual(int(3.5), 3)
self.assertEqual(int(-3.5), -3) self.assertEqual(int(-3.5), -3)
self.assertEqual(int("-3"), -3)
# Different base: # Different base:
self.assertEqual(int("10",16), 16) self.assertEqual(int("10",16), 16)
# Test conversion from strings and various anomalies # Test conversion from strings and various anomalies

View file

@ -35,27 +35,6 @@ del p2
# add complements & negations # add complements & negations
special += [~x for x in special] + [-x for x in special] special += [~x for x in special] + [-x for x in special]
L = [
('0', 0),
('1', 1),
('9', 9),
('10', 10),
('99', 99),
('100', 100),
('314', 314),
(' 314', 314),
('314 ', 314),
(' \t\t 314 \t\t ', 314),
(repr(sys.maxsize), sys.maxsize),
(' 1x', ValueError),
(' 1 ', 1),
(' 1\02 ', ValueError),
('', ValueError),
(' ', ValueError),
(' \t\t ', ValueError)
]
class LongTest(unittest.TestCase): class LongTest(unittest.TestCase):
# Get quasi-random long consisting of ndigits digits (in base BASE). # Get quasi-random long consisting of ndigits digits (in base BASE).
@ -263,7 +242,7 @@ class LongTest(unittest.TestCase):
msg = Frm("%s returned %r but expected %r for %r", msg = Frm("%s returned %r but expected %r for %r",
mapper.__name__, got, expected, x) mapper.__name__, got, expected, x)
self.assertEqual(got, expected, msg) self.assertEqual(got, expected, msg)
self.assertEqual(int(got, 0), x, Frm('long("%s", 0) != %r', got, x)) self.assertEqual(int(got, 0), x, Frm('int("%s", 0) != %r', got, x))
# str() has to be checked a little differently since there's no # str() has to be checked a little differently since there's no
# trailing "L" # trailing "L"
got = str(x) got = str(x)
@ -281,25 +260,12 @@ class LongTest(unittest.TestCase):
self.check_format_1(x) self.check_format_1(x)
def test_long(self): def test_long(self):
self.assertEqual(int(314), 314) # Check conversions from string
self.assertEqual(int(3.14), 3)
self.assertEqual(int(314), 314)
# Check that conversion from float truncates towards zero
self.assertEqual(int(-3.14), -3)
self.assertEqual(int(3.9), 3)
self.assertEqual(int(-3.9), -3)
self.assertEqual(int(3.5), 3)
self.assertEqual(int(-3.5), -3)
self.assertEqual(int("-3"), -3)
# Different base:
self.assertEqual(int("10",16), 16)
# Check conversions from string (same test set as for int(), and then some)
LL = [ LL = [
('1' + '0'*20, 10**20), ('1' + '0'*20, 10**20),
('1' + '0'*100, 10**100) ('1' + '0'*100, 10**100)
] ]
L2 = L[:] for s, v in LL:
for s, v in L2 + LL:
for sign in "", "+", "-": for sign in "", "+", "-":
for prefix in "", " ", "\t", " \t\t ": for prefix in "", " ", "\t", " \t\t ":
ss = prefix + sign + s ss = prefix + sign + s
@ -307,12 +273,10 @@ class LongTest(unittest.TestCase):
if sign == "-" and v is not ValueError: if sign == "-" and v is not ValueError:
vv = -v vv = -v
try: try:
self.assertEqual(int(ss), int(vv)) self.assertEqual(int(ss), vv)
except ValueError: except ValueError:
pass pass
self.assertRaises(ValueError, int, '123\0')
self.assertRaises(ValueError, int, '53', 40)
# trailing L should no longer be accepted... # trailing L should no longer be accepted...
self.assertRaises(ValueError, int, '123L') self.assertRaises(ValueError, int, '123L')
self.assertRaises(ValueError, int, '123l') self.assertRaises(ValueError, int, '123l')
@ -323,302 +287,21 @@ class LongTest(unittest.TestCase):
# ... but it's just a normal digit if base >= 22 # ... but it's just a normal digit if base >= 22
self.assertEqual(int('1L', 22), 43) self.assertEqual(int('1L', 22), 43)
self.assertRaises(TypeError, int, 1, 12)
# SF patch #1638879: embedded NULs were not detected with
# explicit base
self.assertRaises(ValueError, int, '123\0', 10)
self.assertRaises(ValueError, int, '123\x00 245', 20)
self.assertEqual(int('100000000000000000000000000000000', 2),
4294967296)
self.assertEqual(int('102002022201221111211', 3), 4294967296)
self.assertEqual(int('10000000000000000', 4), 4294967296)
self.assertEqual(int('32244002423141', 5), 4294967296)
self.assertEqual(int('1550104015504', 6), 4294967296)
self.assertEqual(int('211301422354', 7), 4294967296)
self.assertEqual(int('40000000000', 8), 4294967296)
self.assertEqual(int('12068657454', 9), 4294967296)
self.assertEqual(int('4294967296', 10), 4294967296)
self.assertEqual(int('1904440554', 11), 4294967296)
self.assertEqual(int('9ba461594', 12), 4294967296)
self.assertEqual(int('535a79889', 13), 4294967296)
self.assertEqual(int('2ca5b7464', 14), 4294967296)
self.assertEqual(int('1a20dcd81', 15), 4294967296)
self.assertEqual(int('100000000', 16), 4294967296)
self.assertEqual(int('a7ffda91', 17), 4294967296)
self.assertEqual(int('704he7g4', 18), 4294967296)
self.assertEqual(int('4f5aff66', 19), 4294967296)
self.assertEqual(int('3723ai4g', 20), 4294967296)
self.assertEqual(int('281d55i4', 21), 4294967296)
self.assertEqual(int('1fj8b184', 22), 4294967296)
self.assertEqual(int('1606k7ic', 23), 4294967296)
self.assertEqual(int('mb994ag', 24), 4294967296)
self.assertEqual(int('hek2mgl', 25), 4294967296)
self.assertEqual(int('dnchbnm', 26), 4294967296)
self.assertEqual(int('b28jpdm', 27), 4294967296)
self.assertEqual(int('8pfgih4', 28), 4294967296)
self.assertEqual(int('76beigg', 29), 4294967296)
self.assertEqual(int('5qmcpqg', 30), 4294967296)
self.assertEqual(int('4q0jto4', 31), 4294967296)
self.assertEqual(int('4000000', 32), 4294967296)
self.assertEqual(int('3aokq94', 33), 4294967296)
self.assertEqual(int('2qhxjli', 34), 4294967296)
self.assertEqual(int('2br45qb', 35), 4294967296)
self.assertEqual(int('1z141z4', 36), 4294967296)
self.assertEqual(int('100000000000000000000000000000001', 2),
4294967297)
self.assertEqual(int('102002022201221111212', 3), 4294967297)
self.assertEqual(int('10000000000000001', 4), 4294967297)
self.assertEqual(int('32244002423142', 5), 4294967297)
self.assertEqual(int('1550104015505', 6), 4294967297)
self.assertEqual(int('211301422355', 7), 4294967297)
self.assertEqual(int('40000000001', 8), 4294967297)
self.assertEqual(int('12068657455', 9), 4294967297)
self.assertEqual(int('4294967297', 10), 4294967297)
self.assertEqual(int('1904440555', 11), 4294967297)
self.assertEqual(int('9ba461595', 12), 4294967297)
self.assertEqual(int('535a7988a', 13), 4294967297)
self.assertEqual(int('2ca5b7465', 14), 4294967297)
self.assertEqual(int('1a20dcd82', 15), 4294967297)
self.assertEqual(int('100000001', 16), 4294967297)
self.assertEqual(int('a7ffda92', 17), 4294967297)
self.assertEqual(int('704he7g5', 18), 4294967297)
self.assertEqual(int('4f5aff67', 19), 4294967297)
self.assertEqual(int('3723ai4h', 20), 4294967297)
self.assertEqual(int('281d55i5', 21), 4294967297)
self.assertEqual(int('1fj8b185', 22), 4294967297)
self.assertEqual(int('1606k7id', 23), 4294967297)
self.assertEqual(int('mb994ah', 24), 4294967297)
self.assertEqual(int('hek2mgm', 25), 4294967297)
self.assertEqual(int('dnchbnn', 26), 4294967297)
self.assertEqual(int('b28jpdn', 27), 4294967297)
self.assertEqual(int('8pfgih5', 28), 4294967297)
self.assertEqual(int('76beigh', 29), 4294967297)
self.assertEqual(int('5qmcpqh', 30), 4294967297)
self.assertEqual(int('4q0jto5', 31), 4294967297)
self.assertEqual(int('4000001', 32), 4294967297)
self.assertEqual(int('3aokq95', 33), 4294967297)
self.assertEqual(int('2qhxjlj', 34), 4294967297)
self.assertEqual(int('2br45qc', 35), 4294967297)
self.assertEqual(int('1z141z5', 36), 4294967297)
def test_conversion(self): def test_conversion(self):
# Test __int__()
class ClassicMissingMethods:
pass
self.assertRaises(TypeError, int, ClassicMissingMethods())
class MissingMethods(object): class JustLong:
pass # test that __long__ no longer used in 3.x
self.assertRaises(TypeError, int, MissingMethods()) def __long__(self):
class Foo0:
def __int__(self):
return 42 return 42
self.assertRaises(TypeError, int, JustLong())
class Foo1(object): class LongTrunc:
def __int__(self): # __long__ should be ignored in 3.x
def __long__(self):
return 42 return 42
def __trunc__(self):
class Foo2(int): return 1729
def __int__(self): self.assertEqual(int(LongTrunc()), 1729)
return 42
class Foo3(int):
def __int__(self):
return self
class Foo4(int):
def __int__(self):
return 42
class Foo5(int):
def __int__(self):
return 42.
self.assertEqual(int(Foo0()), 42)
self.assertEqual(int(Foo1()), 42)
self.assertEqual(int(Foo2()), 42)
self.assertEqual(int(Foo3()), 0)
self.assertEqual(int(Foo4()), 42)
self.assertRaises(TypeError, int, Foo5())
class Classic:
pass
for base in (object, Classic):
class IntOverridesTrunc(base):
def __int__(self):
return 42
def __trunc__(self):
return -12
self.assertEqual(int(IntOverridesTrunc()), 42)
class JustTrunc(base):
def __trunc__(self):
return 42
self.assertEqual(int(JustTrunc()), 42)
class JustLong(base):
# test that __long__ no longer used in 3.x
def __long__(self):
return 42
self.assertRaises(TypeError, int, JustLong())
class LongTrunc(base):
# __long__ should be ignored in 3.x
def __long__(self):
return 42
def __trunc__(self):
return 1729
self.assertEqual(int(LongTrunc()), 1729)
for trunc_result_base in (object, Classic):
class Integral(trunc_result_base):
def __int__(self):
return 42
class TruncReturnsNonLong(base):
def __trunc__(self):
return Integral()
self.assertEqual(int(TruncReturnsNonLong()), 42)
class NonIntegral(trunc_result_base):
def __trunc__(self):
# Check that we avoid infinite recursion.
return NonIntegral()
class TruncReturnsNonIntegral(base):
def __trunc__(self):
return NonIntegral()
try:
int(TruncReturnsNonIntegral())
except TypeError as e:
self.assertEquals(str(e),
"__trunc__ returned non-Integral"
" (type NonIntegral)")
else:
self.fail("Failed to raise TypeError with %s" %
((base, trunc_result_base),))
def test_misc(self):
# check the extremes in int<->long conversion
hugepos = sys.maxsize
hugeneg = -hugepos - 1
hugepos_aslong = int(hugepos)
hugeneg_aslong = int(hugeneg)
self.assertEqual(hugepos, hugepos_aslong, "long(sys.maxsize) != sys.maxsize")
self.assertEqual(hugeneg, hugeneg_aslong,
"long(-sys.maxsize-1) != -sys.maxsize-1")
# long -> int should not fail for hugepos_aslong or hugeneg_aslong
x = int(hugepos_aslong)
try:
self.assertEqual(x, hugepos,
"converting sys.maxsize to long and back to int fails")
except OverflowError:
self.fail("int(long(sys.maxsize)) overflowed!")
if not isinstance(x, int):
raise TestFailed("int(long(sys.maxsize)) should have returned int")
x = int(hugeneg_aslong)
try:
self.assertEqual(x, hugeneg,
"converting -sys.maxsize-1 to long and back to int fails")
except OverflowError:
self.fail("int(long(-sys.maxsize-1)) overflowed!")
if not isinstance(x, int):
raise TestFailed("int(long(-sys.maxsize-1)) should have "
"returned int")
# but long -> int should overflow for hugepos+1 and hugeneg-1
x = hugepos_aslong + 1
try:
y = int(x)
except OverflowError:
self.fail("int(long(sys.maxsize) + 1) mustn't overflow")
self.assertTrue(isinstance(y, int),
"int(long(sys.maxsize) + 1) should have returned long")
x = hugeneg_aslong - 1
try:
y = int(x)
except OverflowError:
self.fail("int(long(-sys.maxsize-1) - 1) mustn't overflow")
self.assertTrue(isinstance(y, int),
"int(long(-sys.maxsize-1) - 1) should have returned long")
class long2(int):
pass
x = long2(1<<100)
y = int(x)
self.assertTrue(type(y) is int,
"overflowing int conversion must return long not long subtype")
# ----------------------------------- tests of auto int->long conversion
def test_auto_overflow(self):
import math, sys
special = [0, 1, 2, 3, sys.maxsize-1, sys.maxsize, sys.maxsize+1]
sqrt = int(math.sqrt(sys.maxsize))
special.extend([sqrt-1, sqrt, sqrt+1])
special.extend([-i for i in special])
def checkit(*args):
# Heavy use of nested scopes here!
self.assertEqual(got, expected,
Frm("for %r expected %r got %r", args, expected, got))
for x in special:
longx = int(x)
expected = -longx
got = -x
checkit('-', x)
for y in special:
longy = int(y)
expected = longx + longy
got = x + y
checkit(x, '+', y)
expected = longx - longy
got = x - y
checkit(x, '-', y)
expected = longx * longy
got = x * y
checkit(x, '*', y)
if y:
expected = longx / longy
got = x / y
checkit(x, '/', y)
expected = longx // longy
got = x // y
checkit(x, '//', y)
expected = divmod(longx, longy)
got = divmod(longx, longy)
checkit(x, 'divmod', y)
if abs(y) < 5 and not (x == 0 and y < 0):
expected = longx ** longy
got = x ** y
checkit(x, '**', y)
for z in special:
if z != 0 :
if y >= 0:
expected = pow(longx, longy, int(z))
got = pow(x, y, z)
checkit('pow', x, y, '%', z)
else:
self.assertRaises(TypeError, pow,longx, longy, int(z))
@unittest.skipUnless(float.__getformat__("double").startswith("IEEE"), @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
"test requires IEEE 754 doubles") "test requires IEEE 754 doubles")
@ -707,10 +390,10 @@ class LongTest(unittest.TestCase):
self.assertRaises(OverflowError, eval, test, namespace) self.assertRaises(OverflowError, eval, test, namespace)
# XXX Perhaps float(shuge) can raise OverflowError on some box? # XXX Perhaps float(shuge) can raise OverflowError on some box?
# The comparison should not. # The comparison should not.
self.assertNotEqual(float(shuge), int(shuge), self.assertNotEqual(float(shuge), int(shuge),
"float(shuge) should not equal int(shuge)") "float(shuge) should not equal int(shuge)")
def test_logs(self): def test_logs(self):
import math import math
@ -807,7 +490,7 @@ class LongTest(unittest.TestCase):
cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0, cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0,
int(t-1), int(t), int(t+1)]) int(t-1), int(t), int(t+1)])
cases.extend([0, 1, 2, sys.maxsize, float(sys.maxsize)]) cases.extend([0, 1, 2, sys.maxsize, float(sys.maxsize)])
# 1L<<20000 should exceed all double formats. long(1e200) is to # 1 << 20000 should exceed all double formats. int(1e200) is to
# check that we get equality with 1e200 above. # check that we get equality with 1e200 above.
t = int(1e200) t = int(1e200)
cases.extend([0, 1, 2, 1 << 20000, t-1, t, t+1]) cases.extend([0, 1, 2, 1 << 20000, t-1, t, t+1])

View file

@ -10,11 +10,9 @@ class TypesTests(unittest.TestCase):
def test_truth_values(self): def test_truth_values(self):
if None: self.fail('None is true instead of false') if None: self.fail('None is true instead of false')
if 0: self.fail('0 is true instead of false') if 0: self.fail('0 is true instead of false')
if 0: self.fail('0L is true instead of false')
if 0.0: self.fail('0.0 is true instead of false') if 0.0: self.fail('0.0 is true instead of false')
if '': self.fail('\'\' is true instead of false') if '': self.fail('\'\' is true instead of false')
if not 1: self.fail('1 is false instead of true') if not 1: self.fail('1 is false instead of true')
if not 1: self.fail('1L is false instead of true')
if not 1.0: self.fail('1.0 is false instead of true') if not 1.0: self.fail('1.0 is false instead of true')
if not 'x': self.fail('\'x\' is false instead of true') if not 'x': self.fail('\'x\' is false instead of true')
if not {'x': 1}: self.fail('{\'x\': 1} is false instead of true') if not {'x': 1}: self.fail('{\'x\': 1} is false instead of true')
@ -36,8 +34,6 @@ class TypesTests(unittest.TestCase):
def test_comparisons(self): def test_comparisons(self):
if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass
else: self.fail('int comparisons failed') else: self.fail('int comparisons failed')
if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass
else: self.fail('long int comparisons failed')
if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass
else: self.fail('float comparisons failed') else: self.fail('float comparisons failed')
if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass
@ -75,18 +71,13 @@ class TypesTests(unittest.TestCase):
else: self.fail("5 % 0 didn't raise ZeroDivisionError") else: self.fail("5 % 0 didn't raise ZeroDivisionError")
def test_numeric_types(self): def test_numeric_types(self):
if 0 != 0 or 0 != 0.0 or 0 != 0.0: self.fail('mixed comparisons') if 0 != 0.0 or 1 != 1.0 or -1 != -1.0:
if 1 != 1 or 1 != 1.0 or 1 != 1.0: self.fail('mixed comparisons') self.fail('int/float value not equal')
if -1 != -1 or -1 != -1.0 or -1 != -1.0:
self.fail('int/long/float value not equal')
# calling built-in types without argument must return 0 # calling built-in types without argument must return 0
if int() != 0: self.fail('int() does not return 0') if int() != 0: self.fail('int() does not return 0')
if int() != 0: self.fail('long() does not return 0')
if float() != 0.0: self.fail('float() does not return 0.0') if float() != 0.0: self.fail('float() does not return 0.0')
if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass
else: self.fail('int() does not round properly') else: self.fail('int() does not round properly')
if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass
else: self.fail('long() does not round properly')
if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass
else: self.fail('float() does not work properly') else: self.fail('float() does not work properly')
@ -141,58 +132,38 @@ class TypesTests(unittest.TestCase):
if type(prod) is not int: if type(prod) is not int:
self.fail("expected type(prod) to be int, not %r" % self.fail("expected type(prod) to be int, not %r" %
type(prod)) type(prod))
# Check for expected * overflow to long. # Check for unified integral type
for divisor in 1, 2, 4, 8, 16, 32: for divisor in 1, 2, 4, 8, 16, 32:
j = m // divisor - 1 j = m // divisor - 1
prod = divisor * j prod = divisor * j
if type(prod) is not int: if type(prod) is not int:
self.fail("expected type(%r) to be long, not %r" % self.fail("expected type(%r) to be int, not %r" %
(prod, type(prod))) (prod, type(prod)))
# Check for expected * overflow to long. # Check for unified integral type
m = sys.maxsize m = sys.maxsize
for divisor in 1, 2, 4, 8, 16, 32: for divisor in 1, 2, 4, 8, 16, 32:
j = m // divisor + 1 j = m // divisor + 1
prod = divisor * j prod = divisor * j
if type(prod) is not int: if type(prod) is not int:
self.fail("expected type(%r) to be long, not %r" % self.fail("expected type(%r) to be int, not %r" %
(prod, type(prod))) (prod, type(prod)))
def test_long_integers(self):
if 12 + 24 != 36: self.fail('long op')
if 12 + (-24) != -12: self.fail('long op')
if (-12) + 24 != 12: self.fail('long op')
if (-12) + (-24) != -36: self.fail('long op')
if not 12 < 24: self.fail('long op')
if not -24 < -12: self.fail('long op')
x = sys.maxsize x = sys.maxsize
if int(int(x)) != x: self.fail('long op') self.assertTrue(isinstance(x + 1, int),
try: y = int(int(x)+1) "(sys.maxsize + 1) should have returned int")
except OverflowError: self.fail('long op') self.assertTrue(isinstance(-x - 1, int),
if not isinstance(y, int): self.fail('long op') "(-sys.maxsize - 1) should have returned int")
x = -x self.assertTrue(isinstance(-x - 2, int),
if int(int(x)) != x: self.fail('long op') "(-sys.maxsize - 2) should have returned int")
x = x-1
if int(int(x)) != x: self.fail('long op')
try: y = int(int(x)-1)
except OverflowError: self.fail('long op')
if not isinstance(y, int): self.fail('long op')
try: 5 << -5 try: 5 << -5
except ValueError: pass except ValueError: pass
else: self.fail('int negative shift <<') else: self.fail('int negative shift <<')
try: 5 << -5
except ValueError: pass
else: self.fail('long negative shift <<')
try: 5 >> -5 try: 5 >> -5
except ValueError: pass except ValueError: pass
else: self.fail('int negative shift >>') else: self.fail('int negative shift >>')
try: 5 >> -5
except ValueError: pass
else: self.fail('long negative shift >>')
def test_floats(self): def test_floats(self):
if 12.0 + 24.0 != 36.0: self.fail('float op') if 12.0 + 24.0 != 36.0: self.fail('float op')
if 12.0 + (-24.0) != -12.0: self.fail('float op') if 12.0 + (-24.0) != -12.0: self.fail('float op')
@ -232,7 +203,7 @@ class TypesTests(unittest.TestCase):
def test_int__format__(self): def test_int__format__(self):
def test(i, format_spec, result): def test(i, format_spec, result):
# just make sure I'm not accidentally checking longs # just make sure we have the unified type for integers
assert type(i) == int assert type(i) == int
assert type(format_spec) == str assert type(format_spec) == str
self.assertEqual(i.__format__(format_spec), result) self.assertEqual(i.__format__(format_spec), result)
@ -353,6 +324,10 @@ class TypesTests(unittest.TestCase):
# issue 5782, commas with no specifier type # issue 5782, commas with no specifier type
test(1234, '010,', '00,001,234') test(1234, '010,', '00,001,234')
# Unified type for integers
test(10**100, 'd', '1' + '0' * 100)
test(10**100+100, 'd', '1' + '0' * 97 + '100')
# make sure these are errors # make sure these are errors
# precision disallowed # precision disallowed
@ -382,96 +357,6 @@ class TypesTests(unittest.TestCase):
self.assertEqual(value.__format__(format_spec), self.assertEqual(value.__format__(format_spec),
float(value).__format__(format_spec)) float(value).__format__(format_spec))
def test_long__format__(self):
def test(i, format_spec, result):
# make sure we're not accidentally checking ints
assert type(i) == int
assert type(format_spec) == str
self.assertEqual(i.__format__(format_spec), result)
test(10**100, 'd', '1' + '0' * 100)
test(10**100+100, 'd', '1' + '0' * 97 + '100')
test(123456789, 'd', '123456789')
test(123456789, 'd', '123456789')
# sign and aligning are interdependent
test(1, "-", '1')
test(-1, "-", '-1')
test(1, "-3", ' 1')
test(-1, "-3", ' -1')
test(1, "+3", ' +1')
test(-1, "+3", ' -1')
test(1, " 3", ' 1')
test(-1, " 3", ' -1')
test(1, " ", ' 1')
test(-1, " ", '-1')
test(1, 'c', '\01')
# hex
test(3, "x", "3")
test(3, "X", "3")
test(1234, "x", "4d2")
test(-1234, "x", "-4d2")
test(1234, "8x", " 4d2")
test(-1234, "8x", " -4d2")
test(1234, "x", "4d2")
test(-1234, "x", "-4d2")
test(-3, "x", "-3")
test(-3, "X", "-3")
# octal
test(3, "o", "3")
test(-3, "o", "-3")
test(65, "o", "101")
test(-65, "o", "-101")
test(1234, "o", "2322")
test(-1234, "o", "-2322")
test(1234, "-o", "2322")
test(-1234, "-o", "-2322")
test(1234, " o", " 2322")
test(-1234, " o", "-2322")
test(1234, "+o", "+2322")
test(-1234, "+o", "-2322")
# binary
test(3, "b", "11")
test(-3, "b", "-11")
test(1234, "b", "10011010010")
test(-1234, "b", "-10011010010")
test(1234, "-b", "10011010010")
test(-1234, "-b", "-10011010010")
test(1234, " b", " 10011010010")
test(-1234, " b", "-10011010010")
test(1234, "+b", "+10011010010")
test(-1234, "+b", "-10011010010")
# make sure these are errors
# precision disallowed
self.assertRaises(ValueError, 3 .__format__, "1.3")
# sign not allowed with 'c'
self.assertRaises(ValueError, 3 .__format__, "+c")
# format spec must be string
self.assertRaises(TypeError, 3 .__format__, None)
self.assertRaises(TypeError, 3 .__format__, 0)
# ensure that only int and float type specifiers work
for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] +
[chr(x) for x in range(ord('A'), ord('Z')+1)]):
if not format_spec in 'bcdoxXeEfFgGn%':
self.assertRaises(ValueError, 0 .__format__, format_spec)
self.assertRaises(ValueError, 1 .__format__, format_spec)
self.assertRaises(ValueError, (-1) .__format__, format_spec)
# ensure that float type specifiers work; format converts
# the long to a float
for format_spec in 'eEfFgG%':
for value in [0, 1, -1, 100, -100, 1234567890, -1234567890]:
self.assertEqual(value.__format__(format_spec),
float(value).__format__(format_spec))
@run_with_locale('LC_NUMERIC', 'en_US.UTF8') @run_with_locale('LC_NUMERIC', 'en_US.UTF8')
def test_float__format__locale(self): def test_float__format__locale(self):
# test locale support for __format__ code 'n' # test locale support for __format__ code 'n'