From 919497ea743174665958520a5647ab0ae87ecb0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Walter=20D=C3=B6rwald?= Date: Sun, 19 Jan 2003 16:23:59 +0000 Subject: [PATCH] Combine test_b1.py and test_b2.py into test_builtin.py, port the tests to PyUnit and add many tests for error cases. This increases code coverage in Python/bltinmodule.c from 75% to 92%. (From SF patch #662807, with assert_(not fcmp(x, y)) replaced with assertAlmostEqual(x, y) where possible) --- Lib/test/output/test_builtin | 53 -- Lib/test/test_b1.py | 673 --------------------- Lib/test/test_b2.py | 369 ------------ Lib/test/test_builtin.py | 1084 +++++++++++++++++++++++++++++++++- 4 files changed, 1075 insertions(+), 1104 deletions(-) delete mode 100644 Lib/test/output/test_builtin delete mode 100644 Lib/test/test_b1.py delete mode 100644 Lib/test/test_b2.py diff --git a/Lib/test/output/test_builtin b/Lib/test/output/test_builtin deleted file mode 100644 index 6c1b9aa81cd..00000000000 --- a/Lib/test/output/test_builtin +++ /dev/null @@ -1,53 +0,0 @@ -test_builtin -4. Built-in functions -test_b1 -__import__ -abs -apply -callable -chr -cmp -coerce -compile -complex -delattr -dir -divmod -eval -execfile -filter -float -getattr -hasattr -hash -hex -id -int -isinstance -issubclass -len -list -long -map -max -min -test_b2 -oct -open -ord -pow -range -input and raw_input -testing -testing -reduce -reload -repr -round -setattr -str -tuple -type -vars -xrange -zip diff --git a/Lib/test/test_b1.py b/Lib/test/test_b1.py deleted file mode 100644 index 3033667d96c..00000000000 --- a/Lib/test/test_b1.py +++ /dev/null @@ -1,673 +0,0 @@ -# Python test set -- part 4a, built-in functions a-m - -import warnings -warnings.filterwarnings("ignore", "hex../oct.. of negative int", - FutureWarning, __name__) - -from test.test_support import TestFailed, fcmp, have_unicode, TESTFN, unlink - -print '__import__' -__import__('sys') -__import__('time') -__import__('string') -try: __import__('spamspam') -except ImportError: pass -else: raise TestFailed, "__import__('spamspam') should fail" - -print 'abs' -if abs(0) != 0: raise TestFailed, 'abs(0)' -if abs(1234) != 1234: raise TestFailed, 'abs(1234)' -if abs(-1234) != 1234: raise TestFailed, 'abs(-1234)' -# -if abs(0.0) != 0.0: raise TestFailed, 'abs(0.0)' -if abs(3.14) != 3.14: raise TestFailed, 'abs(3.14)' -if abs(-3.14) != 3.14: raise TestFailed, 'abs(-3.14)' -# -if abs(0L) != 0L: raise TestFailed, 'abs(0L)' -if abs(1234L) != 1234L: raise TestFailed, 'abs(1234L)' -if abs(-1234L) != 1234L: raise TestFailed, 'abs(-1234L)' - -try: abs('a') -except TypeError: pass -else: raise TestFailed, 'abs("a")' - -print 'apply' -def f0(*args): - if args != (): raise TestFailed, 'f0 called with ' + `args` -def f1(a1): - if a1 != 1: raise TestFailed, 'f1 called with ' + `a1` -def f2(a1, a2): - if a1 != 1 or a2 != 2: - raise TestFailed, 'f2 called with ' + `a1, a2` -def f3(a1, a2, a3): - if a1 != 1 or a2 != 2 or a3 != 3: - raise TestFailed, 'f3 called with ' + `a1, a2, a3` -apply(f0, ()) -apply(f1, (1,)) -apply(f2, (1, 2)) -apply(f3, (1, 2, 3)) - -# A PyCFunction that takes only positional parameters should allow an -# empty keyword dictionary to pass without a complaint, but raise a -# TypeError if the dictionary is non-empty. -apply(id, (1,), {}) -try: - apply(id, (1,), {"foo": 1}) -except TypeError: - pass -else: - raise TestFailed, 'expected TypeError; no exception raised' - -print 'callable' -if not callable(len):raise TestFailed, 'callable(len)' -def f(): pass -if not callable(f): raise TestFailed, 'callable(f)' -class C: - def meth(self): pass -if not callable(C): raise TestFailed, 'callable(C)' -x = C() -if not callable(x.meth): raise TestFailed, 'callable(x.meth)' -if callable(x): raise TestFailed, 'callable(x)' -class D(C): - def __call__(self): pass -y = D() -if not callable(y): raise TestFailed, 'callable(y)' -y() - -print 'chr' -if chr(32) != ' ': raise TestFailed, 'chr(32)' -if chr(65) != 'A': raise TestFailed, 'chr(65)' -if chr(97) != 'a': raise TestFailed, 'chr(97)' - -# cmp -print 'cmp' -if cmp(-1, 1) != -1: raise TestFailed, 'cmp(-1, 1)' -if cmp(1, -1) != 1: raise TestFailed, 'cmp(1, -1)' -if cmp(1, 1) != 0: raise TestFailed, 'cmp(1, 1)' -# verify that circular objects are handled -a = []; a.append(a) -b = []; b.append(b) -from UserList import UserList -c = UserList(); c.append(c) -if cmp(a, b) != 0: raise TestFailed, "cmp(%s, %s)" % (a, b) -if cmp(b, c) != 0: raise TestFailed, "cmp(%s, %s)" % (b, c) -if cmp(c, a) != 0: raise TestFailed, "cmp(%s, %s)" % (c, a) -if cmp(a, c) != 0: raise TestFailed, "cmp(%s, %s)" % (a, c) -# okay, now break the cycles -a.pop(); b.pop(); c.pop() - -print 'coerce' -if fcmp(coerce(1, 1.1), (1.0, 1.1)): raise TestFailed, 'coerce(1, 1.1)' -if coerce(1, 1L) != (1L, 1L): raise TestFailed, 'coerce(1, 1L)' -if fcmp(coerce(1L, 1.1), (1.0, 1.1)): raise TestFailed, 'coerce(1L, 1.1)' - -print 'compile' -compile('print 1\n', '', 'exec') - -print 'complex' -class OS: - def __complex__(self): return 1+10j -class NS(object): - def __complex__(self): return 1+10j -if complex(OS()) != 1+10j: raise TestFailed, '__complex__ in old style class' -if complex(NS()) != 1+10j: raise TestFailed, '__complex__ in new style class' -if complex("1+10j") != 1+10j: raise TestFailed, 'complex("1+10j")' -if complex(10) != 10+0j: raise TestFailed, 'complex(10)' -if complex(10.0) != 10+0j: raise TestFailed, 'complex(10.0)' -if complex(10L) != 10+0j: raise TestFailed, 'complex(10L)' -if complex(10+0j) != 10+0j: raise TestFailed, 'complex(10+0j)' -if complex(1,10) != 1+10j: raise TestFailed, 'complex(1,10)' -if complex(1,10L) != 1+10j: raise TestFailed, 'complex(1,10L)' -if complex(1,10.0) != 1+10j: raise TestFailed, 'complex(1,10.0)' -if complex(1L,10) != 1+10j: raise TestFailed, 'complex(1L,10)' -if complex(1L,10L) != 1+10j: raise TestFailed, 'complex(1L,10L)' -if complex(1L,10.0) != 1+10j: raise TestFailed, 'complex(1L,10.0)' -if complex(1.0,10) != 1+10j: raise TestFailed, 'complex(1.0,10)' -if complex(1.0,10L) != 1+10j: raise TestFailed, 'complex(1.0,10L)' -if complex(1.0,10.0) != 1+10j: raise TestFailed, 'complex(1.0,10.0)' -if complex(3.14+0j) != 3.14+0j: raise TestFailed, 'complex(3.14)' -if complex(3.14) != 3.14+0j: raise TestFailed, 'complex(3.14)' -if complex(314) != 314.0+0j: raise TestFailed, 'complex(314)' -if complex(314L) != 314.0+0j: raise TestFailed, 'complex(314L)' -if complex(3.14+0j, 0j) != 3.14+0j: raise TestFailed, 'complex(3.14, 0j)' -if complex(3.14, 0.0) != 3.14+0j: raise TestFailed, 'complex(3.14, 0.0)' -if complex(314, 0) != 314.0+0j: raise TestFailed, 'complex(314, 0)' -if complex(314L, 0L) != 314.0+0j: raise TestFailed, 'complex(314L, 0L)' -if complex(0j, 3.14j) != -3.14+0j: raise TestFailed, 'complex(0j, 3.14j)' -if complex(0.0, 3.14j) != -3.14+0j: raise TestFailed, 'complex(0.0, 3.14j)' -if complex(0j, 3.14) != 3.14j: raise TestFailed, 'complex(0j, 3.14)' -if complex(0.0, 3.14) != 3.14j: raise TestFailed, 'complex(0.0, 3.14)' -if complex("1") != 1+0j: raise TestFailed, 'complex("1")' -if complex("1j") != 1j: raise TestFailed, 'complex("1j")' - -c = 3.14 + 1j -if complex(c) is not c: raise TestFailed, 'complex(3.14+1j) changed identity' -del c - -try: complex("1", "1") -except TypeError: pass -else: raise TestFailed, 'complex("1", "1")' - -try: complex(1, "1") -except TypeError: pass -else: raise TestFailed, 'complex(1, "1")' - -if complex(" 3.14+J ") != 3.14+1j: raise TestFailed, 'complex(" 3.14+J )"' -if have_unicode: - if complex(unicode(" 3.14+J ")) != 3.14+1j: - raise TestFailed, 'complex(u" 3.14+J )"' - -# SF bug 543840: complex(string) accepts strings with \0 -# Fixed in 2.3. -try: - complex('1+1j\0j') -except ValueError: - pass -else: - raise TestFailed("complex('1+1j\0j') should have raised ValueError") - -class Z: - def __complex__(self): return 3.14j -z = Z() -if complex(z) != 3.14j: raise TestFailed, 'complex(classinstance)' - -print 'delattr' -import sys -sys.spam = 1 -delattr(sys, 'spam') - -print 'dir' -x = 1 -if 'x' not in dir(): raise TestFailed, 'dir()' -import sys -if 'modules' not in dir(sys): raise TestFailed, 'dir(sys)' - -print 'divmod' -if divmod(12, 7) != (1, 5): raise TestFailed, 'divmod(12, 7)' -if divmod(-12, 7) != (-2, 2): raise TestFailed, 'divmod(-12, 7)' -if divmod(12, -7) != (-2, -2): raise TestFailed, 'divmod(12, -7)' -if divmod(-12, -7) != (1, -5): raise TestFailed, 'divmod(-12, -7)' -# -if divmod(12L, 7L) != (1L, 5L): raise TestFailed, 'divmod(12L, 7L)' -if divmod(-12L, 7L) != (-2L, 2L): raise TestFailed, 'divmod(-12L, 7L)' -if divmod(12L, -7L) != (-2L, -2L): raise TestFailed, 'divmod(12L, -7L)' -if divmod(-12L, -7L) != (1L, -5L): raise TestFailed, 'divmod(-12L, -7L)' -# -if divmod(12, 7L) != (1, 5L): raise TestFailed, 'divmod(12, 7L)' -if divmod(-12, 7L) != (-2, 2L): raise TestFailed, 'divmod(-12, 7L)' -if divmod(12L, -7) != (-2L, -2): raise TestFailed, 'divmod(12L, -7)' -if divmod(-12L, -7) != (1L, -5): raise TestFailed, 'divmod(-12L, -7)' -# -if fcmp(divmod(3.25, 1.0), (3.0, 0.25)): - raise TestFailed, 'divmod(3.25, 1.0)' -if fcmp(divmod(-3.25, 1.0), (-4.0, 0.75)): - raise TestFailed, 'divmod(-3.25, 1.0)' -if fcmp(divmod(3.25, -1.0), (-4.0, -0.75)): - raise TestFailed, 'divmod(3.25, -1.0)' -if fcmp(divmod(-3.25, -1.0), (3.0, -0.25)): - raise TestFailed, 'divmod(-3.25, -1.0)' - -print 'eval' -if eval('1+1') != 2: raise TestFailed, 'eval(\'1+1\')' -if eval(' 1+1\n') != 2: raise TestFailed, 'eval(\' 1+1\\n\')' -globals = {'a': 1, 'b': 2} -locals = {'b': 200, 'c': 300} -if eval('a', globals) != 1: - raise TestFailed, "eval(1) == %s" % eval('a', globals) -if eval('a', globals, locals) != 1: - raise TestFailed, "eval(2)" -if eval('b', globals, locals) != 200: - raise TestFailed, "eval(3)" -if eval('c', globals, locals) != 300: - raise TestFailed, "eval(4)" -if have_unicode: - if eval(unicode('1+1')) != 2: raise TestFailed, 'eval(u\'1+1\')' - if eval(unicode(' 1+1\n')) != 2: raise TestFailed, 'eval(u\' 1+1\\n\')' -globals = {'a': 1, 'b': 2} -locals = {'b': 200, 'c': 300} -if have_unicode: - if eval(unicode('a'), globals) != 1: - raise TestFailed, "eval(1) == %s" % eval(unicode('a'), globals) - if eval(unicode('a'), globals, locals) != 1: - raise TestFailed, "eval(2)" - if eval(unicode('b'), globals, locals) != 200: - raise TestFailed, "eval(3)" - if eval(unicode('c'), globals, locals) != 300: - raise TestFailed, "eval(4)" - -print 'execfile' -z = 0 -f = open(TESTFN, 'w') -f.write('z = z+1\n') -f.write('z = z*2\n') -f.close() -execfile(TESTFN) -if z != 2: raise TestFailed, "execfile(1)" -globals['z'] = 0 -execfile(TESTFN, globals) -if globals['z'] != 2: raise TestFailed, "execfile(1)" -locals['z'] = 0 -execfile(TESTFN, globals, locals) -if locals['z'] != 2: raise TestFailed, "execfile(1)" -unlink(TESTFN) - -print 'filter' -if filter(lambda c: 'a' <= c <= 'z', 'Hello World') != 'elloorld': - raise TestFailed, 'filter (filter a string)' -if filter(None, [1, 'hello', [], [3], '', None, 9, 0]) != [1, 'hello', [3], 9]: - raise TestFailed, 'filter (remove false values)' -if filter(lambda x: x > 0, [1, -3, 9, 0, 2]) != [1, 9, 2]: - raise TestFailed, 'filter (keep positives)' -class Squares: - def __init__(self, max): - self.max = max - self.sofar = [] - def __len__(self): return len(self.sofar) - def __getitem__(self, i): - if not 0 <= i < self.max: raise IndexError - n = len(self.sofar) - while n <= i: - self.sofar.append(n*n) - n = n+1 - return self.sofar[i] -if filter(None, Squares(10)) != [1, 4, 9, 16, 25, 36, 49, 64, 81]: - raise TestFailed, 'filter(None, Squares(10))' -if filter(lambda x: x%2, Squares(10)) != [1, 9, 25, 49, 81]: - raise TestFailed, 'filter(oddp, Squares(10))' -class StrSquares: - def __init__(self, max): - self.max = max - self.sofar = [] - def __len__(self): - return len(self.sofar) - def __getitem__(self, i): - if not 0 <= i < self.max: - raise IndexError - n = len(self.sofar) - while n <= i: - self.sofar.append(str(n*n)) - n = n+1 - return self.sofar[i] -def identity(item): - return 1 -filter(identity, Squares(5)) - -print 'float' -if float(3.14) != 3.14: raise TestFailed, 'float(3.14)' -if float(314) != 314.0: raise TestFailed, 'float(314)' -if float(314L) != 314.0: raise TestFailed, 'float(314L)' -if float(" 3.14 ") != 3.14: raise TestFailed, 'float(" 3.14 ")' -if have_unicode: - if float(unicode(" 3.14 ")) != 3.14: - raise TestFailed, 'float(u" 3.14 ")' - if float(unicode(" \u0663.\u0661\u0664 ",'raw-unicode-escape')) != 3.14: - raise TestFailed, 'float(u" \u0663.\u0661\u0664 ")' - -print 'getattr' -import sys -if getattr(sys, 'stdout') is not sys.stdout: raise TestFailed, 'getattr' -try: - getattr(sys, 1) -except TypeError: - pass -else: - raise TestFailed, "getattr(sys, 1) should raise an exception" -try: - getattr(sys, 1, "foo") -except TypeError: - pass -else: - raise TestFailed, 'getattr(sys, 1, "foo") should raise an exception' - -print 'hasattr' -import sys -if not hasattr(sys, 'stdout'): raise TestFailed, 'hasattr' -try: - hasattr(sys, 1) -except TypeError: - pass -else: - raise TestFailed, "hasattr(sys, 1) should raise an exception" - -print 'hash' -hash(None) -if not hash(1) == hash(1L) == hash(1.0): raise TestFailed, 'numeric hash()' -hash('spam') -hash((0,1,2,3)) -def f(): pass -try: hash([]) -except TypeError: pass -else: raise TestFailed, "hash([]) should raise an exception" -try: hash({}) -except TypeError: pass -else: raise TestFailed, "hash({}) should raise an exception" - -print 'hex' -if hex(16) != '0x10': raise TestFailed, 'hex(16)' -if hex(16L) != '0x10L': raise TestFailed, 'hex(16L)' -if len(hex(-1)) != len(hex(sys.maxint)): raise TestFailed, 'len(hex(-1))' -if hex(-16) not in ('0xfffffff0', '0xfffffffffffffff0'): - raise TestFailed, 'hex(-16)' -if hex(-16L) != '-0x10L': raise TestFailed, 'hex(-16L)' - -print 'id' -id(None) -id(1) -id(1L) -id(1.0) -id('spam') -id((0,1,2,3)) -id([0,1,2,3]) -id({'spam': 1, 'eggs': 2, 'ham': 3}) - -# Test input() later, together with raw_input - -print 'int' -if int(314) != 314: raise TestFailed, 'int(314)' -if int(3.14) != 3: raise TestFailed, 'int(3.14)' -if int(314L) != 314: raise TestFailed, 'int(314L)' -# Check that conversion from float truncates towards zero -if int(-3.14) != -3: raise TestFailed, 'int(-3.14)' -if int(3.9) != 3: raise TestFailed, 'int(3.9)' -if int(-3.9) != -3: raise TestFailed, 'int(-3.9)' -if int(3.5) != 3: raise TestFailed, 'int(3.5)' -if int(-3.5) != -3: raise TestFailed, 'int(-3.5)' -# Different base: -if int("10",16) != 16L: raise TestFailed, 'int("10",16)' -if have_unicode: - if int(unicode("10"),16) != 16L: - raise TestFailed, 'int(u"10",16)' -# Test conversion from strings and various anomalies -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), - (`sys.maxint`, sys.maxint), - (' 1x', ValueError), - (' 1 ', 1), - (' 1\02 ', ValueError), - ('', ValueError), - (' ', ValueError), - (' \t\t ', ValueError) -] -if have_unicode: - L += [ - (unicode('0'), 0), - (unicode('1'), 1), - (unicode('9'), 9), - (unicode('10'), 10), - (unicode('99'), 99), - (unicode('100'), 100), - (unicode('314'), 314), - (unicode(' 314'), 314), - (unicode('\u0663\u0661\u0664 ','raw-unicode-escape'), 314), - (unicode(' \t\t 314 \t\t '), 314), - (unicode(' 1x'), ValueError), - (unicode(' 1 '), 1), - (unicode(' 1\02 '), ValueError), - (unicode(''), ValueError), - (unicode(' '), ValueError), - (unicode(' \t\t '), ValueError), -] -for s, v in L: - for sign in "", "+", "-": - for prefix in "", " ", "\t", " \t\t ": - ss = prefix + sign + s - vv = v - if sign == "-" and v is not ValueError: - vv = -v - try: - if int(ss) != vv: - raise TestFailed, "int(%s)" % `ss` - except v: - pass - except ValueError, e: - raise TestFailed, "int(%s) raised ValueError: %s" % (`ss`, e) -s = `-1-sys.maxint` -if int(s)+1 != -sys.maxint: - raise TestFailed, "int(%s)" % `s` -try: - int(s[1:]) -except: - raise TestFailed, "int(%s)" % `s[1:]` + " should return long" -try: - x = int(1e100) -except OverflowError: - raise TestFailed("int(1e100) mustn't raise OverflowError") -else: - if not isinstance(x, long): - raise TestFailed("int(1e100) should have returned long") -try: - x = int(-1e100) -except OverflowError: - raise TestFailed("int(-1e100) mustn't raise OverflowError") -else: - if not isinstance(x, long): - raise TestFailed("int(-1e100) should have returned long") - - -# SF bug 434186: 0x80000000/2 != 0x80000000>>1. -# Worked by accident in Windows release build, but failed in debug build. -# Failed in all Linux builds. -x = -1-sys.maxint -if x >> 1 != x//2: - raise TestFailed("x >> 1 != x/2 when x == -1-sys.maxint") - -try: int('123\0') -except ValueError: pass -else: raise TestFailed("int('123\0') didn't raise exception") - -try: int('53', 40) -except ValueError: pass -else: raise TestFailed("int('53', 40) didn't raise ValueError") - -try: int('1' * 600) -except: raise TestFailed("int('1' * 600) didn't return long") - -if have_unicode: - try: int(unichr(0x661) * 600) - except: raise TestFailed("int('\\u0661' * 600) didn't return long") - -try: int(1, 12) -except TypeError: pass -else: raise TestFailed("int(1, 12) didn't raise TypeError") - -if int('0123', 0) != 83: - raise TestFailed("int('0123', 0) != 83") - -print 'isinstance' -class C: - pass -class D(C): - pass -class E: - pass -c = C() -d = D() -e = E() -if not isinstance(c, C): raise TestFailed, 'isinstance(c, C)' -if not isinstance(d, C): raise TestFailed, 'isinstance(d, C)' -if isinstance(e, C): raise TestFailed, 'isinstance(e, C)' -if isinstance(c, D): raise TestFailed, 'isinstance(c, D)' -if isinstance('foo', E): raise TestFailed, 'isinstance("Foo", E)' -try: - isinstance(E, 'foo') - raise TestFailed, 'isinstance(E, "foo")' -except TypeError: - pass - -print 'issubclass' -if not issubclass(D, C): raise TestFailed, 'issubclass(D, C)' -if not issubclass(C, C): raise TestFailed, 'issubclass(C, C)' -if issubclass(C, D): raise TestFailed, 'issubclass(C, D)' -try: - issubclass('foo', E) - raise TestFailed, 'issubclass("foo", E)' -except TypeError: - pass -try: - issubclass(E, 'foo') - raise TestFailed, 'issubclass(E, "foo")' -except TypeError: - pass - -print 'len' -if len('123') != 3: raise TestFailed, 'len(\'123\')' -if len(()) != 0: raise TestFailed, 'len(())' -if len((1, 2, 3, 4)) != 4: raise TestFailed, 'len((1, 2, 3, 4))' -if len([1, 2, 3, 4]) != 4: raise TestFailed, 'len([1, 2, 3, 4])' -if len({}) != 0: raise TestFailed, 'len({})' -if len({'a':1, 'b': 2}) != 2: raise TestFailed, 'len({\'a\':1, \'b\': 2})' - -print 'list' -if list([]) != []: raise TestFailed, 'list([])' -l0_3 = [0, 1, 2, 3] -l0_3_bis = list(l0_3) -if l0_3 != l0_3_bis or l0_3 is l0_3_bis: raise TestFailed, 'list([0, 1, 2, 3])' -if list(()) != []: raise TestFailed, 'list(())' -if list((0, 1, 2, 3)) != [0, 1, 2, 3]: raise TestFailed, 'list((0, 1, 2, 3))' -if list('') != []: raise TestFailed, 'list('')' -if list('spam') != ['s', 'p', 'a', 'm']: raise TestFailed, "list('spam')" - -if sys.maxint == 0x7fffffff: - # This test can currently only work on 32-bit machines. - # XXX If/when PySequence_Length() returns a ssize_t, it should be - # XXX re-enabled. - try: - # Verify clearing of bug #556025. - # This assumes that the max data size (sys.maxint) == max - # address size this also assumes that the address size is at - # least 4 bytes with 8 byte addresses, the bug is not well - # tested - # - # Note: This test is expected to SEGV under Cygwin 1.3.12 or - # earlier due to a newlib bug. See the following mailing list - # thread for the details: - - # http://sources.redhat.com/ml/newlib/2002/msg00369.html - list(xrange(sys.maxint // 2)) - except MemoryError: - pass - else: - raise TestFailed, 'list(xrange(sys.maxint / 4))' - -print 'long' -if long(314) != 314L: raise TestFailed, 'long(314)' -if long(3.14) != 3L: raise TestFailed, 'long(3.14)' -if long(314L) != 314L: raise TestFailed, 'long(314L)' -# Check that conversion from float truncates towards zero -if long(-3.14) != -3L: raise TestFailed, 'long(-3.14)' -if long(3.9) != 3L: raise TestFailed, 'long(3.9)' -if long(-3.9) != -3L: raise TestFailed, 'long(-3.9)' -if long(3.5) != 3L: raise TestFailed, 'long(3.5)' -if long(-3.5) != -3L: raise TestFailed, 'long(-3.5)' -if long("-3") != -3L: raise TestFailed, 'long("-3")' -if have_unicode: - if long(unicode("-3")) != -3L: - raise TestFailed, 'long(u"-3")' -# Different base: -if long("10",16) != 16L: raise TestFailed, 'long("10",16)' -if have_unicode: - if long(unicode("10"),16) != 16L: - raise TestFailed, 'long(u"10",16)' -# Check conversions from string (same test set as for int(), and then some) -LL = [ - ('1' + '0'*20, 10L**20), - ('1' + '0'*100, 10L**100) -] -if have_unicode: - L+=[ - (unicode('1') + unicode('0')*20, 10L**20), - (unicode('1') + unicode('0')*100, 10L**100), -] -for s, v in L + LL: - for sign in "", "+", "-": - for prefix in "", " ", "\t", " \t\t ": - ss = prefix + sign + s - vv = v - if sign == "-" and v is not ValueError: - vv = -v - try: - if long(ss) != long(vv): - raise TestFailed, "long(%s)" % `ss` - except v: - pass - except ValueError, e: - raise TestFailed, "long(%s) raised ValueError: %s" % (`ss`, e) - -try: long('123\0') -except ValueError: pass -else: raise TestFailed("long('123\0') didn't raise exception") - -try: long('53', 40) -except ValueError: pass -else: raise TestFailed("long('53', 40) didn't raise ValueError") - -try: long(1, 12) -except TypeError: pass -else: raise TestFailed("long(1, 12) didn't raise TypeError") - -print 'map' -if map(None, 'hello world') != ['h','e','l','l','o',' ','w','o','r','l','d']: - raise TestFailed, 'map(None, \'hello world\')' -if map(None, 'abcd', 'efg') != \ - [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', None)]: - raise TestFailed, 'map(None, \'abcd\', \'efg\')' -if map(None, range(10)) != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: - raise TestFailed, 'map(None, range(10))' -if map(lambda x: x*x, range(1,4)) != [1, 4, 9]: - raise TestFailed, 'map(lambda x: x*x, range(1,4))' -try: - from math import sqrt -except ImportError: - def sqrt(x): - return pow(x, 0.5) -if map(lambda x: map(sqrt,x), [[16, 4], [81, 9]]) != [[4.0, 2.0], [9.0, 3.0]]: - raise TestFailed, 'map(lambda x: map(sqrt,x), [[16, 4], [81, 9]])' -if map(lambda x, y: x+y, [1,3,2], [9,1,4]) != [10, 4, 6]: - raise TestFailed, 'map(lambda x,y: x+y, [1,3,2], [9,1,4])' -def plus(*v): - accu = 0 - for i in v: accu = accu + i - return accu -if map(plus, [1, 3, 7]) != [1, 3, 7]: - raise TestFailed, 'map(plus, [1, 3, 7])' -if map(plus, [1, 3, 7], [4, 9, 2]) != [1+4, 3+9, 7+2]: - raise TestFailed, 'map(plus, [1, 3, 7], [4, 9, 2])' -if map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0]) != [1+4+1, 3+9+1, 7+2+0]: - raise TestFailed, 'map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])' -if map(None, Squares(10)) != [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]: - raise TestFailed, 'map(None, Squares(10))' -if map(int, Squares(10)) != [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]: - raise TestFailed, 'map(int, Squares(10))' -if map(None, Squares(3), Squares(2)) != [(0,0), (1,1), (4,None)]: - raise TestFailed, 'map(None, Squares(3), Squares(2))' -if map(max, Squares(3), Squares(2)) != [0, 1, 4]: - raise TestFailed, 'map(max, Squares(3), Squares(2))' - -print 'max' -if max('123123') != '3': raise TestFailed, 'max(\'123123\')' -if max(1, 2, 3) != 3: raise TestFailed, 'max(1, 2, 3)' -if max((1, 2, 3, 1, 2, 3)) != 3: raise TestFailed, 'max((1, 2, 3, 1, 2, 3))' -if max([1, 2, 3, 1, 2, 3]) != 3: raise TestFailed, 'max([1, 2, 3, 1, 2, 3])' -# -if max(1, 2L, 3.0) != 3.0: raise TestFailed, 'max(1, 2L, 3.0)' -if max(1L, 2.0, 3) != 3: raise TestFailed, 'max(1L, 2.0, 3)' -if max(1.0, 2, 3L) != 3L: raise TestFailed, 'max(1.0, 2, 3L)' - -print 'min' -if min('123123') != '1': raise TestFailed, 'min(\'123123\')' -if min(1, 2, 3) != 1: raise TestFailed, 'min(1, 2, 3)' -if min((1, 2, 3, 1, 2, 3)) != 1: raise TestFailed, 'min((1, 2, 3, 1, 2, 3))' -if min([1, 2, 3, 1, 2, 3]) != 1: raise TestFailed, 'min([1, 2, 3, 1, 2, 3])' -# -if min(1, 2L, 3.0) != 1: raise TestFailed, 'min(1, 2L, 3.0)' -if min(1L, 2.0, 3) != 1L: raise TestFailed, 'min(1L, 2.0, 3)' -if min(1.0, 2, 3L) != 1.0: raise TestFailed, 'min(1.0, 2, 3L)' diff --git a/Lib/test/test_b2.py b/Lib/test/test_b2.py deleted file mode 100644 index d59e9052bf9..00000000000 --- a/Lib/test/test_b2.py +++ /dev/null @@ -1,369 +0,0 @@ -# Python test set -- part 4b, built-in functions n-z - -import warnings -warnings.filterwarnings("ignore", "hex../oct.. of negative int", - FutureWarning, __name__) - -from test.test_support import TestFailed, fcmp, TESTFN, unlink, vereq - -print 'oct' -if oct(100) != '0144': raise TestFailed, 'oct(100)' -if oct(100L) != '0144L': raise TestFailed, 'oct(100L)' -if oct(-100) not in ('037777777634', '01777777777777777777634'): - raise TestFailed, 'oct(-100)' -if oct(-100L) != '-0144L': raise TestFailed, 'oct(-100L)' - -print 'open' -# NB the first 4 lines are also used to test input and raw_input, below -fp = open(TESTFN, 'w') -try: - fp.write('1+1\n') - fp.write('1+1\n') - fp.write('The quick brown fox jumps over the lazy dog') - fp.write('.\n') - fp.write('Dear John\n') - fp.write('XXX'*100) - fp.write('YYY'*100) -finally: - fp.close() -# -fp = open(TESTFN, 'r') -try: - if fp.readline(4) != '1+1\n': raise TestFailed, 'readline(4) # exact' - if fp.readline(4) != '1+1\n': raise TestFailed, 'readline(4) # exact' - if fp.readline() != 'The quick brown fox jumps over the lazy dog.\n': - raise TestFailed, 'readline() # default' - if fp.readline(4) != 'Dear': raise TestFailed, 'readline(4) # short' - if fp.readline(100) != ' John\n': raise TestFailed, 'readline(100)' - if fp.read(300) != 'XXX'*100: raise TestFailed, 'read(300)' - if fp.read(1000) != 'YYY'*100: raise TestFailed, 'read(1000) # truncate' -finally: - fp.close() - -print 'ord' -if ord(' ') != 32: raise TestFailed, 'ord(\' \')' -if ord('A') != 65: raise TestFailed, 'ord(\'A\')' -if ord('a') != 97: raise TestFailed, 'ord(\'a\')' - -print 'pow' -if pow(0,0) != 1: raise TestFailed, 'pow(0,0)' -if pow(0,1) != 0: raise TestFailed, 'pow(0,1)' -if pow(1,0) != 1: raise TestFailed, 'pow(1,0)' -if pow(1,1) != 1: raise TestFailed, 'pow(1,1)' -# -if pow(2,0) != 1: raise TestFailed, 'pow(2,0)' -if pow(2,10) != 1024: raise TestFailed, 'pow(2,10)' -if pow(2,20) != 1024*1024: raise TestFailed, 'pow(2,20)' -if pow(2,30) != 1024*1024*1024: raise TestFailed, 'pow(2,30)' -# -if pow(-2,0) != 1: raise TestFailed, 'pow(-2,0)' -if pow(-2,1) != -2: raise TestFailed, 'pow(-2,1)' -if pow(-2,2) != 4: raise TestFailed, 'pow(-2,2)' -if pow(-2,3) != -8: raise TestFailed, 'pow(-2,3)' -# -if pow(0L,0) != 1: raise TestFailed, 'pow(0L,0)' -if pow(0L,1) != 0: raise TestFailed, 'pow(0L,1)' -if pow(1L,0) != 1: raise TestFailed, 'pow(1L,0)' -if pow(1L,1) != 1: raise TestFailed, 'pow(1L,1)' -# -if pow(2L,0) != 1: raise TestFailed, 'pow(2L,0)' -if pow(2L,10) != 1024: raise TestFailed, 'pow(2L,10)' -if pow(2L,20) != 1024*1024: raise TestFailed, 'pow(2L,20)' -if pow(2L,30) != 1024*1024*1024: raise TestFailed, 'pow(2L,30)' -# -if pow(-2L,0) != 1: raise TestFailed, 'pow(-2L,0)' -if pow(-2L,1) != -2: raise TestFailed, 'pow(-2L,1)' -if pow(-2L,2) != 4: raise TestFailed, 'pow(-2L,2)' -if pow(-2L,3) != -8: raise TestFailed, 'pow(-2L,3)' -# -if fcmp(pow(0.,0), 1.): raise TestFailed, 'pow(0.,0)' -if fcmp(pow(0.,1), 0.): raise TestFailed, 'pow(0.,1)' -if fcmp(pow(1.,0), 1.): raise TestFailed, 'pow(1.,0)' -if fcmp(pow(1.,1), 1.): raise TestFailed, 'pow(1.,1)' -# -if fcmp(pow(2.,0), 1.): raise TestFailed, 'pow(2.,0)' -if fcmp(pow(2.,10), 1024.): raise TestFailed, 'pow(2.,10)' -if fcmp(pow(2.,20), 1024.*1024.): raise TestFailed, 'pow(2.,20)' -if fcmp(pow(2.,30), 1024.*1024.*1024.): raise TestFailed, 'pow(2.,30)' -# -if fcmp(pow(-2.,0), 1.): raise TestFailed, 'pow(-2.,0)' -if fcmp(pow(-2.,1), -2.): raise TestFailed, 'pow(-2.,1)' -if fcmp(pow(-2.,2), 4.): raise TestFailed, 'pow(-2.,2)' -if fcmp(pow(-2.,3), -8.): raise TestFailed, 'pow(-2.,3)' - -from types import FloatType -for x in 2, 2L, 2.0: - for y in 10, 10L, 10.0: - for z in 1000, 1000L, 1000.0: - if isinstance(x, FloatType) or \ - isinstance(y, FloatType) or \ - isinstance(z, FloatType): - try: - pow(x, y, z) - except TypeError: - pass - else: - raise TestFailed("3-arg float pow(%s, %s, %s) should " - "have raised TypeError" % (x, y, z)) - else: - if fcmp(pow(x, y, z), 24.0): - raise TestFailed, 'pow(%s, %s, %s)' % (x, y, z) - -try: pow(-1, -2, 3) -except TypeError: pass -else: raise TestFailed, 'pow(1, -2, 3) should raise TypeError' - -try: pow(1, 2, 0) -except ValueError: pass -else: raise TestFailed, 'pow(1, 2, 0) should raise ValueError' - -try: pow(-1L, -2L, 3L) -except TypeError: pass -else: raise TestFailed, 'pow(1L, -2L, 3L) should raise TypeError' - -try: pow(1L, 2L, 0L) -except ValueError: pass -else: raise TestFailed, 'pow(1L, 2L, 0L) should raise ValueError' - -try: pow(-342.43, 0.234) -except ValueError: pass -else: raise TestFailed, 'pow(-342.43, 0.234) should raise ValueError' - -print 'range' -if range(3) != [0, 1, 2]: raise TestFailed, 'range(3)' -if range(1, 5) != [1, 2, 3, 4]: raise TestFailed, 'range(1, 5)' -if range(0) != []: raise TestFailed, 'range(0)' -if range(-3) != []: raise TestFailed, 'range(-3)' -if range(1, 10, 3) != [1, 4, 7]: raise TestFailed, 'range(1, 10, 3)' -if range(5, -5, -3) != [5, 2, -1, -4]: raise TestFailed, 'range(5, -5, -3)' - -print 'input and raw_input' -import sys -fp = open(TESTFN, 'r') -savestdin = sys.stdin -try: - sys.stdin = fp - if input() != 2: raise TestFailed, 'input()' - if input('testing\n') != 2: raise TestFailed, 'input()' - if raw_input() != 'The quick brown fox jumps over the lazy dog.': - raise TestFailed, 'raw_input()' - if raw_input('testing\n') != 'Dear John': - raise TestFailed, 'raw_input(\'testing\\n\')' -finally: - sys.stdin = savestdin - fp.close() - -print 'reduce' -if reduce(lambda x, y: x+y, ['a', 'b', 'c'], '') != 'abc': - raise TestFailed, 'reduce(): implode a string' -if reduce(lambda x, y: x+y, - [['a', 'c'], [], ['d', 'w']], []) != ['a','c','d','w']: - raise TestFailed, 'reduce(): append' -if reduce(lambda x, y: x*y, range(2,8), 1) != 5040: - raise TestFailed, 'reduce(): compute 7!' -if reduce(lambda x, y: x*y, range(2,21), 1L) != 2432902008176640000L: - raise TestFailed, 'reduce(): compute 20!, use long' -class Squares: - def __init__(self, max): - self.max = max - self.sofar = [] - def __len__(self): return len(self.sofar) - def __getitem__(self, i): - if not 0 <= i < self.max: raise IndexError - n = len(self.sofar) - while n <= i: - self.sofar.append(n*n) - n = n+1 - return self.sofar[i] -if reduce(lambda x, y: x+y, Squares(10)) != 285: - raise TestFailed, 'reduce(<+>, Squares(10))' -if reduce(lambda x, y: x+y, Squares(10), 0) != 285: - raise TestFailed, 'reduce(<+>, Squares(10), 0)' -if reduce(lambda x, y: x+y, Squares(0), 0) != 0: - raise TestFailed, 'reduce(<+>, Squares(0), 0)' - - -print 'reload' -import marshal -reload(marshal) -import string -reload(string) -## import sys -## try: reload(sys) -## except ImportError: pass -## else: raise TestFailed, 'reload(sys) should fail' - -print 'repr' -if repr('') != '\'\'': raise TestFailed, 'repr(\'\')' -if repr(0) != '0': raise TestFailed, 'repr(0)' -if repr(0L) != '0L': raise TestFailed, 'repr(0L)' -if repr(()) != '()': raise TestFailed, 'repr(())' -if repr([]) != '[]': raise TestFailed, 'repr([])' -if repr({}) != '{}': raise TestFailed, 'repr({})' - -print 'round' -if round(0.0) != 0.0: raise TestFailed, 'round(0.0)' -if round(1.0) != 1.0: raise TestFailed, 'round(1.0)' -if round(10.0) != 10.0: raise TestFailed, 'round(10.0)' -if round(1000000000.0) != 1000000000.0: - raise TestFailed, 'round(1000000000.0)' -if round(1e20) != 1e20: raise TestFailed, 'round(1e20)' - -if round(-1.0) != -1.0: raise TestFailed, 'round(-1.0)' -if round(-10.0) != -10.0: raise TestFailed, 'round(-10.0)' -if round(-1000000000.0) != -1000000000.0: - raise TestFailed, 'round(-1000000000.0)' -if round(-1e20) != -1e20: raise TestFailed, 'round(-1e20)' - -if round(0.1) != 0.0: raise TestFailed, 'round(0.0)' -if round(1.1) != 1.0: raise TestFailed, 'round(1.0)' -if round(10.1) != 10.0: raise TestFailed, 'round(10.0)' -if round(1000000000.1) != 1000000000.0: - raise TestFailed, 'round(1000000000.0)' - -if round(-1.1) != -1.0: raise TestFailed, 'round(-1.0)' -if round(-10.1) != -10.0: raise TestFailed, 'round(-10.0)' -if round(-1000000000.1) != -1000000000.0: - raise TestFailed, 'round(-1000000000.0)' - -if round(0.9) != 1.0: raise TestFailed, 'round(0.9)' -if round(9.9) != 10.0: raise TestFailed, 'round(9.9)' -if round(999999999.9) != 1000000000.0: - raise TestFailed, 'round(999999999.9)' - -if round(-0.9) != -1.0: raise TestFailed, 'round(-0.9)' -if round(-9.9) != -10.0: raise TestFailed, 'round(-9.9)' -if round(-999999999.9) != -1000000000.0: - raise TestFailed, 'round(-999999999.9)' - -print 'setattr' -import sys -setattr(sys, 'spam', 1) -if sys.spam != 1: raise TestFailed, 'setattr(sys, \'spam\', 1)' -try: - setattr(sys, 1, 'spam') -except TypeError: - pass -else: - raise TestFailed, "setattr(sys, 1, 'spam') should raise exception" - -print 'str' -if str('') != '': raise TestFailed, 'str(\'\')' -if str(0) != '0': raise TestFailed, 'str(0)' -if str(0L) != '0': raise TestFailed, 'str(0L)' -if str(()) != '()': raise TestFailed, 'str(())' -if str([]) != '[]': raise TestFailed, 'str([])' -if str({}) != '{}': raise TestFailed, 'str({})' - -print 'tuple' -if tuple(()) != (): raise TestFailed, 'tuple(())' -t0_3 = (0, 1, 2, 3) -t0_3_bis = tuple(t0_3) -if t0_3 is not t0_3_bis: raise TestFailed, 'tuple((0, 1, 2, 3))' -if tuple([]) != (): raise TestFailed, 'tuple([])' -if tuple([0, 1, 2, 3]) != (0, 1, 2, 3): raise TestFailed, 'tuple([0, 1, 2, 3])' -if tuple('') != (): raise TestFailed, 'tuple('')' -if tuple('spam') != ('s', 'p', 'a', 'm'): raise TestFailed, "tuple('spam')" - -print 'type' -if type('') != type('123') or type('') == type(()): - raise TestFailed, 'type()' - -print 'vars' -a = b = None -a = vars().keys() -b = dir() -a.sort() -b.sort() -if a != b: raise TestFailed, 'vars()' -import sys -a = vars(sys).keys() -b = dir(sys) -a.sort() -b.sort() -if a != b: raise TestFailed, 'vars(sys)' -def f0(): - if vars() != {}: raise TestFailed, 'vars() in f0()' -f0() -def f2(): - f0() - a = 1 - b = 2 - if vars() != {'a': a, 'b': b}: raise TestFailed, 'vars() in f2()' -f2() - -print 'xrange' -import warnings -warnings.filterwarnings('ignore', r".*xrange", DeprecationWarning) -if tuple(xrange(10)) != tuple(range(10)): raise TestFailed, 'xrange(10)' -if tuple(xrange(5,10)) != tuple(range(5,10)): raise TestFailed, 'xrange(5,10)' -if tuple(xrange(0,10,2)) != tuple(range(0,10,2)): - raise TestFailed, 'xrange(0,10,2)' -x = xrange(10); a = iter(x); b = iter(a) # test clearing of SF bug 564601 -if id(x) == id(a): raise TestFailed, "xrange doesn't have a separate iterator" -if id(a) != id(b): raise TestFailed, "xrange iterator not behaving like range" -if type(x) != xrange: raise TestFailed, "xrange type not exposed" # SF 559833 -if list(x) != list(x): raise TestFailed, "xrange should be restartable" - -print 'zip' -a = (1, 2, 3) -b = (4, 5, 6) -t = [(1, 4), (2, 5), (3, 6)] -if zip(a, b) != t: raise TestFailed, 'zip(a, b) - same size, both tuples' -b = [4, 5, 6] -if zip(a, b) != t: raise TestFailed, 'zip(a, b) - same size, tuple/list' -b = (4, 5, 6, 7) -if zip(a, b) != t: raise TestFailed, 'zip(a, b) - b is longer' -class I: - def __getitem__(self, i): - if i < 0 or i > 2: raise IndexError - return i + 4 -if zip(a, I()) != t: raise TestFailed, 'zip(a, b) - b is instance' -exc = 0 -try: - zip() -except TypeError: - exc = 1 -except: - e = sys.exc_info()[0] - raise TestFailed, 'zip() - no args, expected TypeError, got %s' % e -if not exc: - raise TestFailed, 'zip() - no args, missing expected TypeError' - -exc = 0 -try: - zip(None) -except TypeError: - exc = 1 -except: - e = sys.exc_info()[0] - raise TestFailed, 'zip(None) - expected TypeError, got %s' % e -if not exc: - raise TestFailed, 'zip(None) - missing expected TypeError' -class G: - pass -exc = 0 -try: - zip(a, G()) -except TypeError: - exc = 1 -except: - e = sys.exc_info()[0] - raise TestFailed, 'zip(a, b) - b instance w/o __getitem__' -if not exc: - raise TestFailed, 'zip(a, b) - missing expected TypeError' - -# Make sure zip doesn't try to allocate a billion elements for the -# result list when one of its arguments doesn't say how long it is. -# A MemoryError is the most likely failure mode. -class SequenceWithoutALength: - def __getitem__(self, i): - if i == 5: - raise IndexError - else: - return i -vereq(zip(SequenceWithoutALength(), xrange(2**30)), - list(enumerate(range(5)))) - -# Epilogue -- unlink the temp file -unlink(TESTFN) diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index 79a395cc068..60358a45f19 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -1,13 +1,1079 @@ -# Python test set -- part 4, built-in functions +# Python test set -- built-in functions -from test.test_support import unload +import test.test_support, unittest +from test.test_support import fcmp, have_unicode, TESTFN, unlink -print '4. Built-in functions' +import sys, warnings, cStringIO +warnings.filterwarnings("ignore", "hex../oct.. of negative int", + FutureWarning, __name__) -print 'test_b1' -unload('test_b1') -from test import test_b1 +class Squares: -print 'test_b2' -unload('test_b2') -from test import test_b2 + def __init__(self, max): + self.max = max + self.sofar = [] + + def __len__(self): return len(self.sofar) + + def __getitem__(self, i): + if not 0 <= i < self.max: raise IndexError + n = len(self.sofar) + while n <= i: + self.sofar.append(n*n) + n += 1 + return self.sofar[i] + +class StrSquares: + + def __init__(self, max): + self.max = max + self.sofar = [] + + def __len__(self): + return len(self.sofar) + + def __getitem__(self, i): + if not 0 <= i < self.max: + raise IndexError + n = len(self.sofar) + while n <= i: + self.sofar.append(str(n*n)) + n += 1 + return self.sofar[i] + +class BitBucket: + def write(self, line): + pass + +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), + (`sys.maxint`, sys.maxint), + (' 1x', ValueError), + (' 1 ', 1), + (' 1\02 ', ValueError), + ('', ValueError), + (' ', ValueError), + (' \t\t ', ValueError) +] +if have_unicode: + L += [ + (unicode('0'), 0), + (unicode('1'), 1), + (unicode('9'), 9), + (unicode('10'), 10), + (unicode('99'), 99), + (unicode('100'), 100), + (unicode('314'), 314), + (unicode(' 314'), 314), + (unicode('\u0663\u0661\u0664 ','raw-unicode-escape'), 314), + (unicode(' \t\t 314 \t\t '), 314), + (unicode(' 1x'), ValueError), + (unicode(' 1 '), 1), + (unicode(' 1\02 '), ValueError), + (unicode(''), ValueError), + (unicode(' '), ValueError), + (unicode(' \t\t '), ValueError), + (unichr(0x200), ValueError), +] + +class BuiltinTest(unittest.TestCase): + + def test_import(self): + __import__('sys') + __import__('time') + __import__('string') + self.assertRaises(ImportError, __import__, 'spamspam') + self.assertRaises(TypeError, __import__, 1, 2, 3, 4) + + def test_abs(self): + # int + self.assertEqual(abs(0), 0) + self.assertEqual(abs(1234), 1234) + self.assertEqual(abs(-1234), 1234) + # float + self.assertEqual(abs(0.0), 0.0) + self.assertEqual(abs(3.14), 3.14) + self.assertEqual(abs(-3.14), 3.14) + # long + self.assertEqual(abs(0L), 0L) + self.assertEqual(abs(1234L), 1234L) + self.assertEqual(abs(-1234L), 1234L) + # str + self.assertRaises(TypeError, abs, 'a') + + def test_apply(self): + def f0(*args): + self.assertEqual(args, ()) + def f1(a1): + self.assertEqual(a1, 1) + def f2(a1, a2): + self.assertEqual(a1, 1) + self.assertEqual(a2, 2) + def f3(a1, a2, a3): + self.assertEqual(a1, 1) + self.assertEqual(a2, 2) + self.assertEqual(a3, 3) + apply(f0, ()) + apply(f1, (1,)) + apply(f2, (1, 2)) + apply(f3, (1, 2, 3)) + + # A PyCFunction that takes only positional parameters should allow an + # empty keyword dictionary to pass without a complaint, but raise a + # TypeError if the dictionary is non-empty. + apply(id, (1,), {}) + self.assertRaises(TypeError, apply, id, (1,), {"foo": 1}) + self.assertRaises(TypeError, apply) + self.assertRaises(TypeError, apply, id, 42) + self.assertRaises(TypeError, apply, id, (42,), 42) + + def test_callable(self): + self.assert_(callable(len)) + def f(): pass + self.assert_(callable(f)) + class C: + def meth(self): pass + self.assert_(callable(C)) + x = C() + self.assert_(callable(x.meth)) + self.assert_(not callable(x)) + class D(C): + def __call__(self): pass + y = D() + self.assert_(callable(y)) + y() + + def test_chr(self): + self.assertEqual(chr(32), ' ') + self.assertEqual(chr(65), 'A') + self.assertEqual(chr(97), 'a') + self.assertEqual(chr(0xff), '\xff') + self.assertRaises(ValueError, chr, 256) + self.assertRaises(TypeError, chr) + + def test_cmp(self): + self.assertEqual(cmp(-1, 1), -1) + self.assertEqual(cmp(1, -1), 1) + self.assertEqual(cmp(1, 1), 0) + # verify that circular objects are handled + a = []; a.append(a) + b = []; b.append(b) + from UserList import UserList + c = UserList(); c.append(c) + self.assertEqual(cmp(a, b), 0) + self.assertEqual(cmp(b, c), 0) + self.assertEqual(cmp(c, a), 0) + self.assertEqual(cmp(a, c), 0) + # okay, now break the cycles + a.pop(); b.pop(); c.pop() + self.assertRaises(TypeError, cmp) + + def test_coerce(self): + self.assert_(not fcmp(coerce(1, 1.1), (1.0, 1.1))) + self.assertEqual(coerce(1, 1L), (1L, 1L)) + self.assert_(not fcmp(coerce(1L, 1.1), (1.0, 1.1))) + self.assertRaises(TypeError, coerce) + class BadNumber: + def __coerce__(self, other): + raise ValueError + self.assertRaises(ValueError, coerce, 42, BadNumber()) + + def test_compile(self): + compile('print 1\n', '', 'exec') + self.assertRaises(TypeError, compile) + self.assertRaises(ValueError, compile, 'print 42\n', '', 'badmode') + self.assertRaises(ValueError, compile, 'print 42\n', '', 'single', 0xff) + + def test_complex(self): + class OS: + def __complex__(self): return 1+10j + class NS(object): + def __complex__(self): return 1+10j + self.assertEqual(complex(OS()), 1+10j) + self.assertEqual(complex(NS()), 1+10j) + self.assertEqual(complex("1+10j"), 1+10j) + self.assertEqual(complex(10), 10+0j) + self.assertEqual(complex(10.0), 10+0j) + self.assertEqual(complex(10L), 10+0j) + self.assertEqual(complex(10+0j), 10+0j) + self.assertEqual(complex(1,10), 1+10j) + self.assertEqual(complex(1,10L), 1+10j) + self.assertEqual(complex(1,10.0), 1+10j) + self.assertEqual(complex(1L,10), 1+10j) + self.assertEqual(complex(1L,10L), 1+10j) + self.assertEqual(complex(1L,10.0), 1+10j) + self.assertEqual(complex(1.0,10), 1+10j) + self.assertEqual(complex(1.0,10L), 1+10j) + self.assertEqual(complex(1.0,10.0), 1+10j) + self.assertEqual(complex(3.14+0j), 3.14+0j) + self.assertEqual(complex(3.14), 3.14+0j) + self.assertEqual(complex(314), 314.0+0j) + self.assertEqual(complex(314L), 314.0+0j) + self.assertEqual(complex(3.14+0j, 0j), 3.14+0j) + self.assertEqual(complex(3.14, 0.0), 3.14+0j) + self.assertEqual(complex(314, 0), 314.0+0j) + self.assertEqual(complex(314L, 0L), 314.0+0j) + self.assertEqual(complex(0j, 3.14j), -3.14+0j) + self.assertEqual(complex(0.0, 3.14j), -3.14+0j) + self.assertEqual(complex(0j, 3.14), 3.14j) + self.assertEqual(complex(0.0, 3.14), 3.14j) + self.assertEqual(complex("1"), 1+0j) + self.assertEqual(complex("1j"), 1j) + + c = 3.14 + 1j + self.assert_(complex(c) is c) + del c + + self.assertRaises(TypeError, complex, "1", "1") + self.assertRaises(TypeError, complex, 1, "1") + + self.assertEqual(complex(" 3.14+J "), 3.14+1j) + if have_unicode: + self.assertEqual(complex(unicode(" 3.14+J ")), 3.14+1j) + + # SF bug 543840: complex(string) accepts strings with \0 + # Fixed in 2.3. + self.assertRaises(ValueError, complex, '1+1j\0j') + + class Z: + def __complex__(self): return 3.14j + z = Z() + self.assertEqual(complex(z), 3.14j) + + def test_delattr(self): + import sys + sys.spam = 1 + delattr(sys, 'spam') + self.assertRaises(TypeError, delattr) + + def test_dir(self): + x = 1 + self.assert_('x' in dir()) + import sys + self.assert_('modules' in dir(sys)) + self.assertRaises(TypeError, dir, 42, 42) + + def test_divmod(self): + 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(12L, 7L), (1L, 5L)) + self.assertEqual(divmod(-12L, 7L), (-2L, 2L)) + self.assertEqual(divmod(12L, -7L), (-2L, -2L)) + self.assertEqual(divmod(-12L, -7L), (1L, -5L)) + + self.assertEqual(divmod(12, 7L), (1, 5L)) + self.assertEqual(divmod(-12, 7L), (-2, 2L)) + self.assertEqual(divmod(12L, -7), (-2L, -2)) + self.assertEqual(divmod(-12L, -7), (1L, -5)) + + self.assert_(not fcmp(divmod(3.25, 1.0), (3.0, 0.25))) + self.assert_(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75))) + self.assert_(not fcmp(divmod(3.25, -1.0), (-4.0, -0.75))) + self.assert_(not fcmp(divmod(-3.25, -1.0), (3.0, -0.25))) + + self.assertRaises(TypeError, divmod) + + def test_eval(self): + self.assertEqual(eval('1+1'), 2) + self.assertEqual(eval(' 1+1\n'), 2) + globals = {'a': 1, 'b': 2} + locals = {'b': 200, 'c': 300} + self.assertEqual(eval('a', globals) , 1) + self.assertEqual(eval('a', globals, locals), 1) + self.assertEqual(eval('b', globals, locals), 200) + self.assertEqual(eval('c', globals, locals), 300) + if have_unicode: + self.assertEqual(eval(unicode('1+1')), 2) + self.assertEqual(eval(unicode(' 1+1\n')), 2) + globals = {'a': 1, 'b': 2} + locals = {'b': 200, 'c': 300} + if have_unicode: + self.assertEqual(eval(unicode('a'), globals), 1) + self.assertEqual(eval(unicode('a'), globals, locals), 1) + self.assertEqual(eval(unicode('b'), globals, locals), 200) + self.assertEqual(eval(unicode('c'), globals, locals), 300) + self.assertRaises(TypeError, eval) + self.assertRaises(TypeError, eval, ()) + + # Done outside of the method test_z to get the correct scope + z = 0 + f = open(TESTFN, 'w') + f.write('z = z+1\n') + f.write('z = z*2\n') + f.close() + execfile(TESTFN) + + def test_execfile(self): + globals = {'a': 1, 'b': 2} + locals = {'b': 200, 'c': 300} + + self.assertEqual(self.__class__.z, 2) + globals['z'] = 0 + execfile(TESTFN, globals) + self.assertEqual(globals['z'], 2) + locals['z'] = 0 + execfile(TESTFN, globals, locals) + self.assertEqual(locals['z'], 2) + unlink(TESTFN) + self.assertRaises(TypeError, execfile) + import os + self.assertRaises(IOError, execfile, os.curdir) + self.assertRaises(IOError, execfile, "I_dont_exist") + + def test_filter(self): + self.assertEqual(filter(lambda c: 'a' <= c <= 'z', 'Hello World'), 'elloorld') + self.assertEqual(filter(None, [1, 'hello', [], [3], '', None, 9, 0]), [1, 'hello', [3], 9]) + self.assertEqual(filter(lambda x: x > 0, [1, -3, 9, 0, 2]), [1, 9, 2]) + self.assertEqual(filter(None, Squares(10)), [1, 4, 9, 16, 25, 36, 49, 64, 81]) + self.assertEqual(filter(lambda x: x%2, Squares(10)), [1, 9, 25, 49, 81]) + def identity(item): + return 1 + filter(identity, Squares(5)) + self.assertRaises(TypeError, filter) + class BadSeq(object): + def __getitem__(self, index): + if index<4: + return 42 + raise ValueError + self.assertRaises(ValueError, filter, lambda x: x, BadSeq()) + def badfunc(): + pass + self.assertRaises(TypeError, filter, badfunc, range(5)) + + # test biltinmodule.c::filtertuple() + self.assertEqual(filter(None, (1, 2)), (1, 2)) + self.assertEqual(filter(lambda x: x>=3, (1, 2, 3, 4)), (3, 4)) + self.assertRaises(TypeError, filter, 42, (1, 2)) + + # test biltinmodule.c::filterstring() + self.assertEqual(filter(None, "12"), "12") + self.assertEqual(filter(lambda x: x>="3", "1234"), "34") + self.assertRaises(TypeError, filter, 42, "12") + class badstr(str): + def __getitem__(self, index): + raise ValueError + self.assertRaises(ValueError, filter, lambda x: x >="3", badstr("1234")) + + def test_float(self): + self.assertEqual(float(3.14), 3.14) + self.assertEqual(float(314), 314.0) + self.assertEqual(float(314L), 314.0) + self.assertEqual(float(" 3.14 "), 3.14) + if have_unicode: + self.assertEqual(float(unicode(" 3.14 ")), 3.14) + self.assertEqual(float(unicode(" \u0663.\u0661\u0664 ",'raw-unicode-escape')), 3.14) + + def test_getattr(self): + import sys + self.assert_(getattr(sys, 'stdout') is sys.stdout) + self.assertRaises(TypeError, getattr, sys, 1) + self.assertRaises(TypeError, getattr, sys, 1, "foo") + self.assertRaises(TypeError, getattr) + self.assertRaises(UnicodeError, getattr, sys, unichr(sys.maxunicode)) + + def test_hasattr(self): + import sys + self.assert_(hasattr(sys, 'stdout')) + self.assertRaises(TypeError, hasattr, sys, 1) + self.assertRaises(TypeError, hasattr) + self.assertRaises(UnicodeError, hasattr, sys, unichr(sys.maxunicode)) + + def test_hash(self): + hash(None) + self.assertEqual(hash(1), hash(1L)) + self.assertEqual(hash(1), hash(1.0)) + hash('spam') + if have_unicode: + self.assertEqual(hash('spam'), hash(unicode('spam'))) + hash((0,1,2,3)) + def f(): pass + self.assertRaises(TypeError, hash, []) + self.assertRaises(TypeError, hash, {}) + + def test_hex(self): + self.assertEqual(hex(16), '0x10') + self.assertEqual(hex(16L), '0x10L') + self.assertEqual(len(hex(-1)), len(hex(sys.maxint))) + self.assert_(hex(-16) in ('0xfffffff0', '0xfffffffffffffff0')) + self.assertEqual(hex(-16L), '-0x10L') + self.assertRaises(TypeError, hex, {}) + + def test_id(self): + id(None) + id(1) + id(1L) + id(1.0) + id('spam') + id((0,1,2,3)) + id([0,1,2,3]) + id({'spam': 1, 'eggs': 2, 'ham': 3}) + + # Test input() later, together with raw_input + + def test_int(self): + self.assertEqual(int(314), 314) + self.assertEqual(int(3.14), 3) + self.assertEqual(int(314L), 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) + # Different base: + self.assertEqual(int("10",16), 16L) + if have_unicode: + self.assertEqual(int(unicode("10"),16), 16L) + # Test conversion from strings and various anomalies + for s, v in L: + for sign in "", "+", "-": + for prefix in "", " ", "\t", " \t\t ": + ss = prefix + sign + s + vv = v + if sign == "-" and v is not ValueError: + vv = -v + try: + self.assertEqual(int(ss), vv) + except v: + pass + + s = `-1-sys.maxint` + self.assertEqual(int(s)+1, -sys.maxint) + # should return long + int(s[1:]) + + # should return long + x = int(1e100) + self.assert_(isinstance(x, long)) + x = int(-1e100) + self.assert_(isinstance(x, long)) + + + # SF bug 434186: 0x80000000/2 != 0x80000000>>1. + # Worked by accident in Windows release build, but failed in debug build. + # Failed in all Linux builds. + x = -1-sys.maxint + self.assertEqual(x >> 1, x//2) + + self.assertRaises(ValueError, int, '123\0') + self.assertRaises(ValueError, int, '53', 40) + + x = int('1' * 600) + self.assert_(isinstance(x, long)) + + if have_unicode: + x = int(unichr(0x661) * 600) + self.assert_(isinstance(x, long)) + + self.assertRaises(TypeError, int, 1, 12) + + self.assertEqual(int('0123', 0), 83) + + def test_intern(self): + self.assertRaises(TypeError, intern) + s = "never interned before" + self.assert_(intern(s) is s) + s2 = s.swapcase().swapcase() + self.assert_(intern(s2) is s) + + def test_iter(self): + self.assertRaises(TypeError, iter) + self.assertRaises(TypeError, iter, 42, 42) + lists = [("1", "2"), ["1", "2"], "12"] + if have_unicode: + lists.append(unicode("12")) + for l in lists: + i = iter(l) + self.assertEqual(i.next(), '1') + self.assertEqual(i.next(), '2') + self.assertRaises(StopIteration, i.next) + + def test_isinstance(self): + class C: + pass + class D(C): + pass + class E: + pass + c = C() + d = D() + e = E() + self.assert_(isinstance(c, C)) + self.assert_(isinstance(d, C)) + self.assert_(not isinstance(e, C)) + self.assert_(not isinstance(c, D)) + self.assert_(not isinstance('foo', E)) + self.assertRaises(TypeError, isinstance, E, 'foo') + self.assertRaises(TypeError, isinstance) + + def test_issubclass(self): + class C: + pass + class D(C): + pass + class E: + pass + c = C() + d = D() + e = E() + self.assert_(issubclass(D, C)) + self.assert_(issubclass(C, C)) + self.assert_(not issubclass(C, D)) + self.assertRaises(TypeError, issubclass, 'foo', E) + self.assertRaises(TypeError, issubclass, E, 'foo') + self.assertRaises(TypeError, issubclass) + + def test_len(self): + self.assertEqual(len('123'), 3) + self.assertEqual(len(()), 0) + self.assertEqual(len((1, 2, 3, 4)), 4) + self.assertEqual(len([1, 2, 3, 4]), 4) + self.assertEqual(len({}), 0) + self.assertEqual(len({'a':1, 'b': 2}), 2) + class BadSeq: + def __len__(self): + raise ValueError + self.assertRaises(ValueError, len, BadSeq()) + + def test_list(self): + self.assertEqual(list([]), []) + l0_3 = [0, 1, 2, 3] + l0_3_bis = list(l0_3) + self.assertEqual(l0_3, l0_3_bis) + self.assert_(l0_3 is not l0_3_bis) + self.assertEqual(list(()), []) + self.assertEqual(list((0, 1, 2, 3)), [0, 1, 2, 3]) + self.assertEqual(list(''), []) + self.assertEqual(list('spam'), ['s', 'p', 'a', 'm']) + + if sys.maxint == 0x7fffffff: + # This test can currently only work on 32-bit machines. + # XXX If/when PySequence_Length() returns a ssize_t, it should be + # XXX re-enabled. + # Verify clearing of bug #556025. + # This assumes that the max data size (sys.maxint) == max + # address size this also assumes that the address size is at + # least 4 bytes with 8 byte addresses, the bug is not well + # tested + # + # Note: This test is expected to SEGV under Cygwin 1.3.12 or + # earlier due to a newlib bug. See the following mailing list + # thread for the details: + + # http://sources.redhat.com/ml/newlib/2002/msg00369.html + self.assertRaises(MemoryError, list, xrange(sys.maxint // 2)) + + def test_long(self): + self.assertEqual(long(314), 314L) + self.assertEqual(long(3.14), 3L) + self.assertEqual(long(314L), 314L) + # Check that conversion from float truncates towards zero + self.assertEqual(long(-3.14), -3L) + self.assertEqual(long(3.9), 3L) + self.assertEqual(long(-3.9), -3L) + self.assertEqual(long(3.5), 3L) + self.assertEqual(long(-3.5), -3L) + self.assertEqual(long("-3"), -3L) + if have_unicode: + self.assertEqual(long(unicode("-3")), -3L) + # Different base: + self.assertEqual(long("10",16), 16L) + if have_unicode: + self.assertEqual(long(unicode("10"),16), 16L) + # Check conversions from string (same test set as for int(), and then some) + LL = [ + ('1' + '0'*20, 10L**20), + ('1' + '0'*100, 10L**100) + ] + L2 = L + if have_unicode: + L2 += [ + (unicode('1') + unicode('0')*20, 10L**20), + (unicode('1') + unicode('0')*100, 10L**100), + ] + for s, v in L2 + LL: + for sign in "", "+", "-": + for prefix in "", " ", "\t", " \t\t ": + ss = prefix + sign + s + vv = v + if sign == "-" and v is not ValueError: + vv = -v + try: + self.assertEqual(long(ss), long(vv)) + except v: + pass + + self.assertRaises(ValueError, long, '123\0') + self.assertRaises(ValueError, long, '53', 40) + self.assertRaises(TypeError, long, 1, 12) + + def test_map(self): + self.assertEqual( + map(None, 'hello world'), + ['h','e','l','l','o',' ','w','o','r','l','d'] + ) + self.assertEqual( + map(None, 'abcd', 'efg'), + [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', None)] + ) + self.assertEqual( + map(None, range(10)), + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + ) + self.assertEqual( + map(lambda x: x*x, range(1,4)), + [1, 4, 9] + ) + try: + from math import sqrt + except ImportError: + def sqrt(x): + return pow(x, 0.5) + self.assertEqual( + map(lambda x: map(sqrt,x), [[16, 4], [81, 9]]), + [[4.0, 2.0], [9.0, 3.0]] + ) + self.assertEqual( + map(lambda x, y: x+y, [1,3,2], [9,1,4]), + [10, 4, 6] + ) + + def plus(*v): + accu = 0 + for i in v: accu = accu + i + return accu + self.assertEqual( + map(plus, [1, 3, 7]), + [1, 3, 7] + ) + self.assertEqual( + map(plus, [1, 3, 7], [4, 9, 2]), + [1+4, 3+9, 7+2] + ) + self.assertEqual( + map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0]), + [1+4+1, 3+9+1, 7+2+0] + ) + self.assertEqual( + map(None, Squares(10)), + [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] + ) + self.assertEqual( + map(int, Squares(10)), + [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] + ) + self.assertEqual( + map(None, Squares(3), Squares(2)), + [(0,0), (1,1), (4,None)] + ) + self.assertEqual( + map(max, Squares(3), Squares(2)), + [0, 1, 4] + ) + self.assertRaises(TypeError, map) + self.assertRaises(TypeError, map, lambda x: x, 42) + self.assertEqual(map(None, [42]), [42]) + class BadSeq: + def __getitem__(self, index): + raise ValueError + self.assertRaises(ValueError, map, lambda x: x, BadSeq()) + + def test_max(self): + self.assertEqual(max('123123'), '3') + self.assertEqual(max(1, 2, 3), 3) + self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3) + self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3) + + self.assertEqual(max(1, 2L, 3.0), 3.0) + self.assertEqual(max(1L, 2.0, 3), 3) + self.assertEqual(max(1.0, 2, 3L), 3L) + + def test_min(self): + self.assertEqual(min('123123'), '1') + self.assertEqual(min(1, 2, 3), 1) + self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1) + self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1) + + self.assertEqual(min(1, 2L, 3.0), 1) + self.assertEqual(min(1L, 2.0, 3), 1L) + self.assertEqual(min(1.0, 2, 3L), 1.0) + + self.assertRaises(TypeError, min) + self.assertRaises(TypeError, min, 42) + self.assertRaises(ValueError, min, ()) + class BadSeq: + def __getitem__(self, index): + raise ValueError + self.assertRaises(ValueError, min, BadSeq()) + class BadNumber: + def __cmp__(self, other): + raise ValueError + self.assertRaises(ValueError, min, (42, BadNumber())) + + def test_oct(self): + self.assertEqual(oct(100), '0144') + self.assertEqual(oct(100L), '0144L') + self.assert_(oct(-100) in ('037777777634', '01777777777777777777634')) + self.assertEqual(oct(-100L), '-0144L') + self.assertRaises(TypeError, oct, ()) + + def write_testfile(self): + # NB the first 4 lines are also used to test input and raw_input, below + fp = open(TESTFN, 'w') + try: + fp.write('1+1\n') + fp.write('1+1\n') + fp.write('The quick brown fox jumps over the lazy dog') + fp.write('.\n') + fp.write('Dear John\n') + fp.write('XXX'*100) + fp.write('YYY'*100) + finally: + fp.close() + + def test_open(self): + self.write_testfile() + fp = open(TESTFN, 'r') + try: + 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(4), 'Dear') + self.assertEqual(fp.readline(100), ' John\n') + self.assertEqual(fp.read(300), 'XXX'*100) + self.assertEqual(fp.read(1000), 'YYY'*100) + finally: + fp.close() + unlink(TESTFN) + + def test_ord(self): + self.assertEqual(ord(' '), 32) + self.assertEqual(ord('A'), 65) + self.assertEqual(ord('a'), 97) + if have_unicode: + self.assertEqual(ord(unichr(sys.maxunicode)), sys.maxunicode) + self.assertRaises(TypeError, ord, 42) + self.assertRaises(TypeError, ord, unicode("12")) + + def test_pow(self): + 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.assertEqual(pow(0L,0), 1) + self.assertEqual(pow(0L,1), 0) + self.assertEqual(pow(1L,0), 1) + self.assertEqual(pow(1L,1), 1) + + self.assertEqual(pow(2L,0), 1) + self.assertEqual(pow(2L,10), 1024) + self.assertEqual(pow(2L,20), 1024*1024) + self.assertEqual(pow(2L,30), 1024*1024*1024) + + self.assertEqual(pow(-2L,0), 1) + self.assertEqual(pow(-2L,1), -2) + self.assertEqual(pow(-2L,2), 4) + self.assertEqual(pow(-2L,3), -8) + + self.assertAlmostEqual(pow(0.,0), 1.) + self.assertAlmostEqual(pow(0.,1), 0.) + self.assertAlmostEqual(pow(1.,0), 1.) + self.assertAlmostEqual(pow(1.,1), 1.) + + self.assertAlmostEqual(pow(2.,0), 1.) + self.assertAlmostEqual(pow(2.,10), 1024.) + self.assertAlmostEqual(pow(2.,20), 1024.*1024.) + self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.) + + self.assertAlmostEqual(pow(-2.,0), 1.) + self.assertAlmostEqual(pow(-2.,1), -2.) + self.assertAlmostEqual(pow(-2.,2), 4.) + self.assertAlmostEqual(pow(-2.,3), -8.) + + for x in 2, 2L, 2.0: + for y in 10, 10L, 10.0: + for z in 1000, 1000L, 1000.0: + if isinstance(x, float) or \ + isinstance(y, float) or \ + isinstance(z, float): + self.assertRaises(TypeError, pow, x, y, z) + else: + self.assertAlmostEqual(pow(x, y, z), 24.0) + + self.assertRaises(TypeError, pow, -1, -2, 3) + self.assertRaises(ValueError, pow, 1, 2, 0) + self.assertRaises(TypeError, pow, -1L, -2L, 3L) + self.assertRaises(ValueError, pow, 1L, 2L, 0L) + self.assertRaises(ValueError, pow, -342.43, 0.234) + + self.assertRaises(TypeError, pow) + + def test_range(self): + self.assertEqual(range(3), [0, 1, 2]) + self.assertEqual(range(1, 5), [1, 2, 3, 4]) + self.assertEqual(range(0), []) + self.assertEqual(range(-3), []) + self.assertEqual(range(1, 10, 3), [1, 4, 7]) + self.assertEqual(range(5, -5, -3), [5, 2, -1, -4]) + + self.assertRaises(TypeError, range) + self.assertRaises(TypeError, range, 1, 2, 3, 4) + self.assertRaises(ValueError, range, 1, 2, 0) + + def test_input_and_raw_input(self): + self.write_testfile() + fp = open(TESTFN, 'r') + savestdin = sys.stdin + savestdout = sys.stdout # Eats the echo + try: + sys.stdin = fp + sys.stdout = BitBucket() + self.assertEqual(input(), 2) + self.assertEqual(input('testing\n'), 2) + self.assertEqual(raw_input(), 'The quick brown fox jumps over the lazy dog.') + self.assertEqual(raw_input('testing\n'), 'Dear John') + sys.stdin = cStringIO.StringIO("NULL\0") + self.assertRaises(TypeError, input, 42, 42) + sys.stdin = cStringIO.StringIO(" 'whitespace'") + self.assertEqual(input(), 'whitespace') + sys.stdin = cStringIO.StringIO() + self.assertRaises(EOFError, input) + del sys.stdout + self.assertRaises(RuntimeError, input, 'prompt') + del sys.stdin + self.assertRaises(RuntimeError, input, 'prompt') + finally: + sys.stdin = savestdin + sys.stdout = savestdout + fp.close() + unlink(TESTFN) + + def test_reduce(self): + self.assertEqual(reduce(lambda x, y: x+y, ['a', 'b', 'c'], ''), 'abc') + self.assertEqual( + reduce(lambda x, y: x+y, [['a', 'c'], [], ['d', 'w']], []), + ['a','c','d','w'] + ) + self.assertEqual(reduce(lambda x, y: x*y, range(2,8), 1), 5040) + self.assertEqual( + reduce(lambda x, y: x*y, range(2,21), 1L), + 2432902008176640000L + ) + self.assertEqual(reduce(lambda x, y: x+y, Squares(10)), 285) + self.assertEqual(reduce(lambda x, y: x+y, Squares(10), 0), 285) + self.assertEqual(reduce(lambda x, y: x+y, Squares(0), 0), 0) + self.assertRaises(TypeError, reduce) + self.assertRaises(TypeError, reduce, 42, 42) + self.assertRaises(TypeError, reduce, 42, 42, 42) + self.assertEqual(reduce(42, "1"), "1") # func is never called with one item + self.assertEqual(reduce(42, "", "1"), "1") # func is never called with one item + self.assertRaises(TypeError, reduce, 42, (42, 42)) + + class BadSeq: + def __getitem__(self, index): + raise ValueError + self.assertRaises(ValueError, reduce, 42, BadSeq()) + + def test_reload(self): + import marshal + reload(marshal) + import string + reload(string) + ## import sys + ## self.assertRaises(ImportError, reload, sys) + + def test_repr(self): + self.assertEqual(repr(''), '\'\'') + self.assertEqual(repr(0), '0') + self.assertEqual(repr(0L), '0L') + self.assertEqual(repr(()), '()') + self.assertEqual(repr([]), '[]') + self.assertEqual(repr({}), '{}') + a = [] + a.append(a) + self.assertEqual(repr(a), '[[...]]') + a = {} + a[0] = a + self.assertEqual(repr(a), '{0: {...}}') + + def test_round(self): + self.assertEqual(round(0.0), 0.0) + self.assertEqual(round(1.0), 1.0) + self.assertEqual(round(10.0), 10.0) + self.assertEqual(round(1000000000.0), 1000000000.0) + self.assertEqual(round(1e20), 1e20) + + self.assertEqual(round(-1.0), -1.0) + self.assertEqual(round(-10.0), -10.0) + self.assertEqual(round(-1000000000.0), -1000000000.0) + self.assertEqual(round(-1e20), -1e20) + + self.assertEqual(round(0.1), 0.0) + self.assertEqual(round(1.1), 1.0) + self.assertEqual(round(10.1), 10.0) + self.assertEqual(round(1000000000.1), 1000000000.0) + + self.assertEqual(round(-1.1), -1.0) + self.assertEqual(round(-10.1), -10.0) + self.assertEqual(round(-1000000000.1), -1000000000.0) + + self.assertEqual(round(0.9), 1.0) + self.assertEqual(round(9.9), 10.0) + self.assertEqual(round(999999999.9), 1000000000.0) + + self.assertEqual(round(-0.9), -1.0) + self.assertEqual(round(-9.9), -10.0) + self.assertEqual(round(-999999999.9), -1000000000.0) + + self.assertEqual(round(-8.0, -1), -10.0) + + self.assertRaises(TypeError, round) + + def test_setattr(self): + setattr(sys, 'spam', 1) + self.assertEqual(sys.spam, 1) + self.assertRaises(TypeError, setattr, sys, 1, 'spam') + self.assertRaises(TypeError, setattr) + + def test_str(self): + self.assertEqual(str(''), '') + self.assertEqual(str(0), '0') + self.assertEqual(str(0L), '0') + self.assertEqual(str(()), '()') + self.assertEqual(str([]), '[]') + self.assertEqual(str({}), '{}') + a = [] + a.append(a) + self.assertEqual(str(a), '[[...]]') + a = {} + a[0] = a + self.assertEqual(str(a), '{0: {...}}') + + def test_tuple(self): + self.assertEqual(tuple(()), ()) + t0_3 = (0, 1, 2, 3) + t0_3_bis = tuple(t0_3) + self.assert_(t0_3 is t0_3_bis) + self.assertEqual(tuple([]), ()) + self.assertEqual(tuple([0, 1, 2, 3]), (0, 1, 2, 3)) + self.assertEqual(tuple(''), ()) + self.assertEqual(tuple('spam'), ('s', 'p', 'a', 'm')) + + def test_type(self): + self.assertEqual(type(''), type('123')) + self.assertNotEqual(type(''), type(())) + + def test_unichr(self): + if have_unicode: + self.assertEqual(unichr(32), unicode(' ')) + self.assertEqual(unichr(65), unicode('A')) + self.assertEqual(unichr(97), unicode('a')) + self.assertEqual( + unichr(sys.maxunicode), + unicode('\\U%08x' % (sys.maxunicode), 'unicode-escape') + ) + self.assertRaises(ValueError, unichr, sys.maxunicode+1) + self.assertRaises(TypeError, unichr) + + def get_vars_f0(): + return vars() + # we don't want self in vars(), so use staticmethod + get_vars_f0 = staticmethod(get_vars_f0) + + def get_vars_f2(): + BuiltinTest.get_vars_f0() + a = 1 + b = 2 + return vars() + get_vars_f2 = staticmethod(get_vars_f2) + + def test_vars(self): + a = b = None + a = vars().keys() + b = dir() + a.sort() + b.sort() + self.assertEqual(a, b) + import sys + a = vars(sys).keys() + b = dir(sys) + a.sort() + b.sort() + self.assertEqual(a, b) + self.assertEqual(self.get_vars_f0(), {}) + self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2}) + self.assertRaises(TypeError, vars, 42, 42) + self.assertRaises(TypeError, vars, 42) + + def test_zip(self): + a = (1, 2, 3) + b = (4, 5, 6) + t = [(1, 4), (2, 5), (3, 6)] + self.assertEqual(zip(a, b), t) + b = [4, 5, 6] + self.assertEqual(zip(a, b), t) + b = (4, 5, 6, 7) + self.assertEqual(zip(a, b), t) + class I: + def __getitem__(self, i): + if i < 0 or i > 2: raise IndexError + return i + 4 + self.assertEqual(zip(a, I()), t) + self.assertRaises(TypeError, zip) + self.assertRaises(TypeError, zip, None) + class G: + pass + self.assertRaises(TypeError, zip, a, G()) + + # Make sure zip doesn't try to allocate a billion elements for the + # result list when one of its arguments doesn't say how long it is. + # A MemoryError is the most likely failure mode. + class SequenceWithoutALength: + def __getitem__(self, i): + if i == 5: + raise IndexError + else: + return i + self.assertEqual( + zip(SequenceWithoutALength(), xrange(2**30)), + list(enumerate(range(5))) + ) + + class BadSeq: + def __getitem__(self, i): + if i == 5: + raise ValueError + else: + return i + self.assertRaises(ValueError, zip, BadSeq(), BadSeq()) + +def test_main(): + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite(BuiltinTest)) + test.test_support.run_suite(suite) + +if __name__ == "__main__": + test_main()