symbian-qemu-0.9.1-12/python-2.6.1/Lib/test/test_builtin.py
changeset 1 2fb8b9db1c86
equal deleted inserted replaced
0:ffa851df0825 1:2fb8b9db1c86
       
     1 # Python test set -- built-in functions
       
     2 
       
     3 import test.test_support, unittest
       
     4 from test.test_support import fcmp, have_unicode, TESTFN, unlink, \
       
     5                               run_unittest, run_with_locale
       
     6 from operator import neg
       
     7 
       
     8 import sys, warnings, cStringIO, random, fractions, UserDict
       
     9 warnings.filterwarnings("ignore", "hex../oct.. of negative int",
       
    10                         FutureWarning, __name__)
       
    11 warnings.filterwarnings("ignore", "integer argument expected",
       
    12                         DeprecationWarning, "unittest")
       
    13 
       
    14 # count the number of test runs.
       
    15 # used to skip running test_execfile() multiple times
       
    16 numruns = 0
       
    17 
       
    18 class Squares:
       
    19 
       
    20     def __init__(self, max):
       
    21         self.max = max
       
    22         self.sofar = []
       
    23 
       
    24     def __len__(self): return len(self.sofar)
       
    25 
       
    26     def __getitem__(self, i):
       
    27         if not 0 <= i < self.max: raise IndexError
       
    28         n = len(self.sofar)
       
    29         while n <= i:
       
    30             self.sofar.append(n*n)
       
    31             n += 1
       
    32         return self.sofar[i]
       
    33 
       
    34 class StrSquares:
       
    35 
       
    36     def __init__(self, max):
       
    37         self.max = max
       
    38         self.sofar = []
       
    39 
       
    40     def __len__(self):
       
    41         return len(self.sofar)
       
    42 
       
    43     def __getitem__(self, i):
       
    44         if not 0 <= i < self.max:
       
    45             raise IndexError
       
    46         n = len(self.sofar)
       
    47         while n <= i:
       
    48             self.sofar.append(str(n*n))
       
    49             n += 1
       
    50         return self.sofar[i]
       
    51 
       
    52 class BitBucket:
       
    53     def write(self, line):
       
    54         pass
       
    55 
       
    56 
       
    57 class TestFailingBool:
       
    58     def __nonzero__(self):
       
    59         raise RuntimeError
       
    60 
       
    61 class TestFailingIter:
       
    62     def __iter__(self):
       
    63         raise RuntimeError
       
    64 
       
    65 class BuiltinTest(unittest.TestCase):
       
    66 
       
    67     def test_import(self):
       
    68         __import__('sys')
       
    69         __import__('time')
       
    70         __import__('string')
       
    71         __import__(name='sys')
       
    72         __import__(name='time', level=0)
       
    73         self.assertRaises(ImportError, __import__, 'spamspam')
       
    74         self.assertRaises(TypeError, __import__, 1, 2, 3, 4)
       
    75         self.assertRaises(ValueError, __import__, '')
       
    76         self.assertRaises(TypeError, __import__, 'sys', name='sys')
       
    77 
       
    78     def test_abs(self):
       
    79         # int
       
    80         self.assertEqual(abs(0), 0)
       
    81         self.assertEqual(abs(1234), 1234)
       
    82         self.assertEqual(abs(-1234), 1234)
       
    83         self.assertTrue(abs(-sys.maxint-1) > 0)
       
    84         # float
       
    85         self.assertEqual(abs(0.0), 0.0)
       
    86         self.assertEqual(abs(3.14), 3.14)
       
    87         self.assertEqual(abs(-3.14), 3.14)
       
    88         # long
       
    89         self.assertEqual(abs(0L), 0L)
       
    90         self.assertEqual(abs(1234L), 1234L)
       
    91         self.assertEqual(abs(-1234L), 1234L)
       
    92         # str
       
    93         self.assertRaises(TypeError, abs, 'a')
       
    94 
       
    95     def test_all(self):
       
    96         self.assertEqual(all([2, 4, 6]), True)
       
    97         self.assertEqual(all([2, None, 6]), False)
       
    98         self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6])
       
    99         self.assertRaises(RuntimeError, all, TestFailingIter())
       
   100         self.assertRaises(TypeError, all, 10)               # Non-iterable
       
   101         self.assertRaises(TypeError, all)                   # No args
       
   102         self.assertRaises(TypeError, all, [2, 4, 6], [])    # Too many args
       
   103         self.assertEqual(all([]), True)                     # Empty iterator
       
   104         S = [50, 60]
       
   105         self.assertEqual(all(x > 42 for x in S), True)
       
   106         S = [50, 40, 60]
       
   107         self.assertEqual(all(x > 42 for x in S), False)
       
   108 
       
   109     def test_any(self):
       
   110         self.assertEqual(any([None, None, None]), False)
       
   111         self.assertEqual(any([None, 4, None]), True)
       
   112         self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6])
       
   113         self.assertRaises(RuntimeError, all, TestFailingIter())
       
   114         self.assertRaises(TypeError, any, 10)               # Non-iterable
       
   115         self.assertRaises(TypeError, any)                   # No args
       
   116         self.assertRaises(TypeError, any, [2, 4, 6], [])    # Too many args
       
   117         self.assertEqual(any([]), False)                    # Empty iterator
       
   118         S = [40, 60, 30]
       
   119         self.assertEqual(any(x > 42 for x in S), True)
       
   120         S = [10, 20, 30]
       
   121         self.assertEqual(any(x > 42 for x in S), False)
       
   122 
       
   123     def test_neg(self):
       
   124         x = -sys.maxint-1
       
   125         self.assert_(isinstance(x, int))
       
   126         self.assertEqual(-x, sys.maxint+1)
       
   127 
       
   128     def test_apply(self):
       
   129         def f0(*args):
       
   130             self.assertEqual(args, ())
       
   131         def f1(a1):
       
   132             self.assertEqual(a1, 1)
       
   133         def f2(a1, a2):
       
   134             self.assertEqual(a1, 1)
       
   135             self.assertEqual(a2, 2)
       
   136         def f3(a1, a2, a3):
       
   137             self.assertEqual(a1, 1)
       
   138             self.assertEqual(a2, 2)
       
   139             self.assertEqual(a3, 3)
       
   140         apply(f0, ())
       
   141         apply(f1, (1,))
       
   142         apply(f2, (1, 2))
       
   143         apply(f3, (1, 2, 3))
       
   144 
       
   145         # A PyCFunction that takes only positional parameters should allow an
       
   146         # empty keyword dictionary to pass without a complaint, but raise a
       
   147         # TypeError if the dictionary is non-empty.
       
   148         apply(id, (1,), {})
       
   149         self.assertRaises(TypeError, apply, id, (1,), {"foo": 1})
       
   150         self.assertRaises(TypeError, apply)
       
   151         self.assertRaises(TypeError, apply, id, 42)
       
   152         self.assertRaises(TypeError, apply, id, (42,), 42)
       
   153 
       
   154     def test_callable(self):
       
   155         self.assert_(callable(len))
       
   156         def f(): pass
       
   157         self.assert_(callable(f))
       
   158         class C:
       
   159             def meth(self): pass
       
   160         self.assert_(callable(C))
       
   161         x = C()
       
   162         self.assert_(callable(x.meth))
       
   163         self.assert_(not callable(x))
       
   164         class D(C):
       
   165             def __call__(self): pass
       
   166         y = D()
       
   167         self.assert_(callable(y))
       
   168         y()
       
   169 
       
   170     def test_chr(self):
       
   171         self.assertEqual(chr(32), ' ')
       
   172         self.assertEqual(chr(65), 'A')
       
   173         self.assertEqual(chr(97), 'a')
       
   174         self.assertEqual(chr(0xff), '\xff')
       
   175         self.assertRaises(ValueError, chr, 256)
       
   176         self.assertRaises(TypeError, chr)
       
   177 
       
   178     def test_cmp(self):
       
   179         self.assertEqual(cmp(-1, 1), -1)
       
   180         self.assertEqual(cmp(1, -1), 1)
       
   181         self.assertEqual(cmp(1, 1), 0)
       
   182         # verify that circular objects are not handled
       
   183         a = []; a.append(a)
       
   184         b = []; b.append(b)
       
   185         from UserList import UserList
       
   186         c = UserList(); c.append(c)
       
   187         self.assertRaises(RuntimeError, cmp, a, b)
       
   188         self.assertRaises(RuntimeError, cmp, b, c)
       
   189         self.assertRaises(RuntimeError, cmp, c, a)
       
   190         self.assertRaises(RuntimeError, cmp, a, c)
       
   191        # okay, now break the cycles
       
   192         a.pop(); b.pop(); c.pop()
       
   193         self.assertRaises(TypeError, cmp)
       
   194 
       
   195     def test_coerce(self):
       
   196         self.assert_(not fcmp(coerce(1, 1.1), (1.0, 1.1)))
       
   197         self.assertEqual(coerce(1, 1L), (1L, 1L))
       
   198         self.assert_(not fcmp(coerce(1L, 1.1), (1.0, 1.1)))
       
   199         self.assertRaises(TypeError, coerce)
       
   200         class BadNumber:
       
   201             def __coerce__(self, other):
       
   202                 raise ValueError
       
   203         self.assertRaises(ValueError, coerce, 42, BadNumber())
       
   204         self.assertRaises(OverflowError, coerce, 0.5, int("12345" * 1000))
       
   205 
       
   206     def test_compile(self):
       
   207         compile('print 1\n', '', 'exec')
       
   208         bom = '\xef\xbb\xbf'
       
   209         compile(bom + 'print 1\n', '', 'exec')
       
   210         compile(source='pass', filename='?', mode='exec')
       
   211         compile(dont_inherit=0, filename='tmp', source='0', mode='eval')
       
   212         compile('pass', '?', dont_inherit=1, mode='exec')
       
   213         self.assertRaises(TypeError, compile)
       
   214         self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'badmode')
       
   215         self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'single', 0xff)
       
   216         self.assertRaises(TypeError, compile, chr(0), 'f', 'exec')
       
   217         self.assertRaises(TypeError, compile, 'pass', '?', 'exec',
       
   218                           mode='eval', source='0', filename='tmp')
       
   219         if have_unicode:
       
   220             compile(unicode('print u"\xc3\xa5"\n', 'utf8'), '', 'exec')
       
   221             self.assertRaises(TypeError, compile, unichr(0), 'f', 'exec')
       
   222             self.assertRaises(ValueError, compile, unicode('a = 1'), 'f', 'bad')
       
   223 
       
   224 
       
   225     def test_delattr(self):
       
   226         import sys
       
   227         sys.spam = 1
       
   228         delattr(sys, 'spam')
       
   229         self.assertRaises(TypeError, delattr)
       
   230 
       
   231     def test_dir(self):
       
   232         # dir(wrong number of arguments)
       
   233         self.assertRaises(TypeError, dir, 42, 42)
       
   234 
       
   235         # dir() - local scope
       
   236         local_var = 1
       
   237         self.assert_('local_var' in dir())
       
   238 
       
   239         # dir(module)
       
   240         import sys
       
   241         self.assert_('exit' in dir(sys))
       
   242 
       
   243         # dir(module_with_invalid__dict__)
       
   244         import types
       
   245         class Foo(types.ModuleType):
       
   246             __dict__ = 8
       
   247         f = Foo("foo")
       
   248         self.assertRaises(TypeError, dir, f)
       
   249 
       
   250         # dir(type)
       
   251         self.assert_("strip" in dir(str))
       
   252         self.assert_("__mro__" not in dir(str))
       
   253 
       
   254         # dir(obj)
       
   255         class Foo(object):
       
   256             def __init__(self):
       
   257                 self.x = 7
       
   258                 self.y = 8
       
   259                 self.z = 9
       
   260         f = Foo()
       
   261         self.assert_("y" in dir(f))
       
   262 
       
   263         # dir(obj_no__dict__)
       
   264         class Foo(object):
       
   265             __slots__ = []
       
   266         f = Foo()
       
   267         self.assert_("__repr__" in dir(f))
       
   268 
       
   269         # dir(obj_no__class__with__dict__)
       
   270         # (an ugly trick to cause getattr(f, "__class__") to fail)
       
   271         class Foo(object):
       
   272             __slots__ = ["__class__", "__dict__"]
       
   273             def __init__(self):
       
   274                 self.bar = "wow"
       
   275         f = Foo()
       
   276         self.assert_("__repr__" not in dir(f))
       
   277         self.assert_("bar" in dir(f))
       
   278 
       
   279         # dir(obj_using __dir__)
       
   280         class Foo(object):
       
   281             def __dir__(self):
       
   282                 return ["kan", "ga", "roo"]
       
   283         f = Foo()
       
   284         self.assert_(dir(f) == ["ga", "kan", "roo"])
       
   285 
       
   286         # dir(obj__dir__not_list)
       
   287         class Foo(object):
       
   288             def __dir__(self):
       
   289                 return 7
       
   290         f = Foo()
       
   291         self.assertRaises(TypeError, dir, f)
       
   292 
       
   293     def test_divmod(self):
       
   294         self.assertEqual(divmod(12, 7), (1, 5))
       
   295         self.assertEqual(divmod(-12, 7), (-2, 2))
       
   296         self.assertEqual(divmod(12, -7), (-2, -2))
       
   297         self.assertEqual(divmod(-12, -7), (1, -5))
       
   298 
       
   299         self.assertEqual(divmod(12L, 7L), (1L, 5L))
       
   300         self.assertEqual(divmod(-12L, 7L), (-2L, 2L))
       
   301         self.assertEqual(divmod(12L, -7L), (-2L, -2L))
       
   302         self.assertEqual(divmod(-12L, -7L), (1L, -5L))
       
   303 
       
   304         self.assertEqual(divmod(12, 7L), (1, 5L))
       
   305         self.assertEqual(divmod(-12, 7L), (-2, 2L))
       
   306         self.assertEqual(divmod(12L, -7), (-2L, -2))
       
   307         self.assertEqual(divmod(-12L, -7), (1L, -5))
       
   308 
       
   309         self.assertEqual(divmod(-sys.maxint-1, -1),
       
   310                          (sys.maxint+1, 0))
       
   311 
       
   312         self.assert_(not fcmp(divmod(3.25, 1.0), (3.0, 0.25)))
       
   313         self.assert_(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75)))
       
   314         self.assert_(not fcmp(divmod(3.25, -1.0), (-4.0, -0.75)))
       
   315         self.assert_(not fcmp(divmod(-3.25, -1.0), (3.0, -0.25)))
       
   316 
       
   317         self.assertRaises(TypeError, divmod)
       
   318 
       
   319     def test_eval(self):
       
   320         self.assertEqual(eval('1+1'), 2)
       
   321         self.assertEqual(eval(' 1+1\n'), 2)
       
   322         globals = {'a': 1, 'b': 2}
       
   323         locals = {'b': 200, 'c': 300}
       
   324         self.assertEqual(eval('a', globals) , 1)
       
   325         self.assertEqual(eval('a', globals, locals), 1)
       
   326         self.assertEqual(eval('b', globals, locals), 200)
       
   327         self.assertEqual(eval('c', globals, locals), 300)
       
   328         if have_unicode:
       
   329             self.assertEqual(eval(unicode('1+1')), 2)
       
   330             self.assertEqual(eval(unicode(' 1+1\n')), 2)
       
   331         globals = {'a': 1, 'b': 2}
       
   332         locals = {'b': 200, 'c': 300}
       
   333         if have_unicode:
       
   334             self.assertEqual(eval(unicode('a'), globals), 1)
       
   335             self.assertEqual(eval(unicode('a'), globals, locals), 1)
       
   336             self.assertEqual(eval(unicode('b'), globals, locals), 200)
       
   337             self.assertEqual(eval(unicode('c'), globals, locals), 300)
       
   338             bom = '\xef\xbb\xbf'
       
   339             self.assertEqual(eval(bom + 'a', globals, locals), 1)
       
   340             self.assertEqual(eval(unicode('u"\xc3\xa5"', 'utf8'), globals),
       
   341                              unicode('\xc3\xa5', 'utf8'))
       
   342         self.assertRaises(TypeError, eval)
       
   343         self.assertRaises(TypeError, eval, ())
       
   344 
       
   345     def test_general_eval(self):
       
   346         # Tests that general mappings can be used for the locals argument
       
   347 
       
   348         class M:
       
   349             "Test mapping interface versus possible calls from eval()."
       
   350             def __getitem__(self, key):
       
   351                 if key == 'a':
       
   352                     return 12
       
   353                 raise KeyError
       
   354             def keys(self):
       
   355                 return list('xyz')
       
   356 
       
   357         m = M()
       
   358         g = globals()
       
   359         self.assertEqual(eval('a', g, m), 12)
       
   360         self.assertRaises(NameError, eval, 'b', g, m)
       
   361         self.assertEqual(eval('dir()', g, m), list('xyz'))
       
   362         self.assertEqual(eval('globals()', g, m), g)
       
   363         self.assertEqual(eval('locals()', g, m), m)
       
   364         self.assertRaises(TypeError, eval, 'a', m)
       
   365         class A:
       
   366             "Non-mapping"
       
   367             pass
       
   368         m = A()
       
   369         self.assertRaises(TypeError, eval, 'a', g, m)
       
   370 
       
   371         # Verify that dict subclasses work as well
       
   372         class D(dict):
       
   373             def __getitem__(self, key):
       
   374                 if key == 'a':
       
   375                     return 12
       
   376                 return dict.__getitem__(self, key)
       
   377             def keys(self):
       
   378                 return list('xyz')
       
   379 
       
   380         d = D()
       
   381         self.assertEqual(eval('a', g, d), 12)
       
   382         self.assertRaises(NameError, eval, 'b', g, d)
       
   383         self.assertEqual(eval('dir()', g, d), list('xyz'))
       
   384         self.assertEqual(eval('globals()', g, d), g)
       
   385         self.assertEqual(eval('locals()', g, d), d)
       
   386 
       
   387         # Verify locals stores (used by list comps)
       
   388         eval('[locals() for i in (2,3)]', g, d)
       
   389         eval('[locals() for i in (2,3)]', g, UserDict.UserDict())
       
   390 
       
   391         class SpreadSheet:
       
   392             "Sample application showing nested, calculated lookups."
       
   393             _cells = {}
       
   394             def __setitem__(self, key, formula):
       
   395                 self._cells[key] = formula
       
   396             def __getitem__(self, key):
       
   397                 return eval(self._cells[key], globals(), self)
       
   398 
       
   399         ss = SpreadSheet()
       
   400         ss['a1'] = '5'
       
   401         ss['a2'] = 'a1*6'
       
   402         ss['a3'] = 'a2*7'
       
   403         self.assertEqual(ss['a3'], 210)
       
   404 
       
   405         # Verify that dir() catches a non-list returned by eval
       
   406         # SF bug #1004669
       
   407         class C:
       
   408             def __getitem__(self, item):
       
   409                 raise KeyError(item)
       
   410             def keys(self):
       
   411                 return 'a'
       
   412         self.assertRaises(TypeError, eval, 'dir()', globals(), C())
       
   413 
       
   414     # Done outside of the method test_z to get the correct scope
       
   415     z = 0
       
   416     f = open(TESTFN, 'w')
       
   417     f.write('z = z+1\n')
       
   418     f.write('z = z*2\n')
       
   419     f.close()
       
   420     execfile(TESTFN)
       
   421 
       
   422     def test_execfile(self):
       
   423         global numruns
       
   424         if numruns:
       
   425             return
       
   426         numruns += 1
       
   427 
       
   428         globals = {'a': 1, 'b': 2}
       
   429         locals = {'b': 200, 'c': 300}
       
   430 
       
   431         self.assertEqual(self.__class__.z, 2)
       
   432         globals['z'] = 0
       
   433         execfile(TESTFN, globals)
       
   434         self.assertEqual(globals['z'], 2)
       
   435         locals['z'] = 0
       
   436         execfile(TESTFN, globals, locals)
       
   437         self.assertEqual(locals['z'], 2)
       
   438 
       
   439         class M:
       
   440             "Test mapping interface versus possible calls from execfile()."
       
   441             def __init__(self):
       
   442                 self.z = 10
       
   443             def __getitem__(self, key):
       
   444                 if key == 'z':
       
   445                     return self.z
       
   446                 raise KeyError
       
   447             def __setitem__(self, key, value):
       
   448                 if key == 'z':
       
   449                     self.z = value
       
   450                     return
       
   451                 raise KeyError
       
   452 
       
   453         locals = M()
       
   454         locals['z'] = 0
       
   455         execfile(TESTFN, globals, locals)
       
   456         self.assertEqual(locals['z'], 2)
       
   457 
       
   458         unlink(TESTFN)
       
   459         self.assertRaises(TypeError, execfile)
       
   460         self.assertRaises(TypeError, execfile, TESTFN, {}, ())
       
   461         import os
       
   462         self.assertRaises(IOError, execfile, os.curdir)
       
   463         self.assertRaises(IOError, execfile, "I_dont_exist")
       
   464 
       
   465     def test_filter(self):
       
   466         self.assertEqual(filter(lambda c: 'a' <= c <= 'z', 'Hello World'), 'elloorld')
       
   467         self.assertEqual(filter(None, [1, 'hello', [], [3], '', None, 9, 0]), [1, 'hello', [3], 9])
       
   468         self.assertEqual(filter(lambda x: x > 0, [1, -3, 9, 0, 2]), [1, 9, 2])
       
   469         self.assertEqual(filter(None, Squares(10)), [1, 4, 9, 16, 25, 36, 49, 64, 81])
       
   470         self.assertEqual(filter(lambda x: x%2, Squares(10)), [1, 9, 25, 49, 81])
       
   471         def identity(item):
       
   472             return 1
       
   473         filter(identity, Squares(5))
       
   474         self.assertRaises(TypeError, filter)
       
   475         class BadSeq(object):
       
   476             def __getitem__(self, index):
       
   477                 if index<4:
       
   478                     return 42
       
   479                 raise ValueError
       
   480         self.assertRaises(ValueError, filter, lambda x: x, BadSeq())
       
   481         def badfunc():
       
   482             pass
       
   483         self.assertRaises(TypeError, filter, badfunc, range(5))
       
   484 
       
   485         # test bltinmodule.c::filtertuple()
       
   486         self.assertEqual(filter(None, (1, 2)), (1, 2))
       
   487         self.assertEqual(filter(lambda x: x>=3, (1, 2, 3, 4)), (3, 4))
       
   488         self.assertRaises(TypeError, filter, 42, (1, 2))
       
   489 
       
   490         # test bltinmodule.c::filterstring()
       
   491         self.assertEqual(filter(None, "12"), "12")
       
   492         self.assertEqual(filter(lambda x: x>="3", "1234"), "34")
       
   493         self.assertRaises(TypeError, filter, 42, "12")
       
   494         class badstr(str):
       
   495             def __getitem__(self, index):
       
   496                 raise ValueError
       
   497         self.assertRaises(ValueError, filter, lambda x: x >="3", badstr("1234"))
       
   498 
       
   499         class badstr2(str):
       
   500             def __getitem__(self, index):
       
   501                 return 42
       
   502         self.assertRaises(TypeError, filter, lambda x: x >=42, badstr2("1234"))
       
   503 
       
   504         class weirdstr(str):
       
   505             def __getitem__(self, index):
       
   506                 return weirdstr(2*str.__getitem__(self, index))
       
   507         self.assertEqual(filter(lambda x: x>="33", weirdstr("1234")), "3344")
       
   508 
       
   509         class shiftstr(str):
       
   510             def __getitem__(self, index):
       
   511                 return chr(ord(str.__getitem__(self, index))+1)
       
   512         self.assertEqual(filter(lambda x: x>="3", shiftstr("1234")), "345")
       
   513 
       
   514         if have_unicode:
       
   515             # test bltinmodule.c::filterunicode()
       
   516             self.assertEqual(filter(None, unicode("12")), unicode("12"))
       
   517             self.assertEqual(filter(lambda x: x>="3", unicode("1234")), unicode("34"))
       
   518             self.assertRaises(TypeError, filter, 42, unicode("12"))
       
   519             self.assertRaises(ValueError, filter, lambda x: x >="3", badstr(unicode("1234")))
       
   520 
       
   521             class badunicode(unicode):
       
   522                 def __getitem__(self, index):
       
   523                     return 42
       
   524             self.assertRaises(TypeError, filter, lambda x: x >=42, badunicode("1234"))
       
   525 
       
   526             class weirdunicode(unicode):
       
   527                 def __getitem__(self, index):
       
   528                     return weirdunicode(2*unicode.__getitem__(self, index))
       
   529             self.assertEqual(
       
   530                 filter(lambda x: x>=unicode("33"), weirdunicode("1234")), unicode("3344"))
       
   531 
       
   532             class shiftunicode(unicode):
       
   533                 def __getitem__(self, index):
       
   534                     return unichr(ord(unicode.__getitem__(self, index))+1)
       
   535             self.assertEqual(
       
   536                 filter(lambda x: x>=unicode("3"), shiftunicode("1234")),
       
   537                 unicode("345")
       
   538             )
       
   539 
       
   540     def test_filter_subclasses(self):
       
   541         # test that filter() never returns tuple, str or unicode subclasses
       
   542         # and that the result always goes through __getitem__
       
   543         funcs = (None, bool, lambda x: True)
       
   544         class tuple2(tuple):
       
   545             def __getitem__(self, index):
       
   546                 return 2*tuple.__getitem__(self, index)
       
   547         class str2(str):
       
   548             def __getitem__(self, index):
       
   549                 return 2*str.__getitem__(self, index)
       
   550         inputs = {
       
   551             tuple2: {(): (), (1, 2, 3): (2, 4, 6)},
       
   552             str2:   {"": "", "123": "112233"}
       
   553         }
       
   554         if have_unicode:
       
   555             class unicode2(unicode):
       
   556                 def __getitem__(self, index):
       
   557                     return 2*unicode.__getitem__(self, index)
       
   558             inputs[unicode2] = {
       
   559                 unicode(): unicode(),
       
   560                 unicode("123"): unicode("112233")
       
   561             }
       
   562 
       
   563         for (cls, inps) in inputs.iteritems():
       
   564             for (inp, exp) in inps.iteritems():
       
   565                 # make sure the output goes through __getitem__
       
   566                 # even if func is None
       
   567                 self.assertEqual(
       
   568                     filter(funcs[0], cls(inp)),
       
   569                     filter(funcs[1], cls(inp))
       
   570                 )
       
   571                 for func in funcs:
       
   572                     outp = filter(func, cls(inp))
       
   573                     self.assertEqual(outp, exp)
       
   574                     self.assert_(not isinstance(outp, cls))
       
   575 
       
   576     def test_getattr(self):
       
   577         import sys
       
   578         self.assert_(getattr(sys, 'stdout') is sys.stdout)
       
   579         self.assertRaises(TypeError, getattr, sys, 1)
       
   580         self.assertRaises(TypeError, getattr, sys, 1, "foo")
       
   581         self.assertRaises(TypeError, getattr)
       
   582         if have_unicode:
       
   583             self.assertRaises(UnicodeError, getattr, sys, unichr(sys.maxunicode))
       
   584 
       
   585     def test_hasattr(self):
       
   586         import sys
       
   587         self.assert_(hasattr(sys, 'stdout'))
       
   588         self.assertRaises(TypeError, hasattr, sys, 1)
       
   589         self.assertRaises(TypeError, hasattr)
       
   590         if have_unicode:
       
   591             self.assertRaises(UnicodeError, hasattr, sys, unichr(sys.maxunicode))
       
   592 
       
   593         # Check that hasattr allows SystemExit and KeyboardInterrupts by
       
   594         class A:
       
   595             def __getattr__(self, what):
       
   596                 raise KeyboardInterrupt
       
   597         self.assertRaises(KeyboardInterrupt, hasattr, A(), "b")
       
   598         class B:
       
   599             def __getattr__(self, what):
       
   600                 raise SystemExit
       
   601         self.assertRaises(SystemExit, hasattr, B(), "b")
       
   602 
       
   603     def test_hash(self):
       
   604         hash(None)
       
   605         self.assertEqual(hash(1), hash(1L))
       
   606         self.assertEqual(hash(1), hash(1.0))
       
   607         hash('spam')
       
   608         if have_unicode:
       
   609             self.assertEqual(hash('spam'), hash(unicode('spam')))
       
   610         hash((0,1,2,3))
       
   611         def f(): pass
       
   612         self.assertRaises(TypeError, hash, [])
       
   613         self.assertRaises(TypeError, hash, {})
       
   614         # Bug 1536021: Allow hash to return long objects
       
   615         class X:
       
   616             def __hash__(self):
       
   617                 return 2**100
       
   618         self.assertEquals(type(hash(X())), int)
       
   619         class Y(object):
       
   620             def __hash__(self):
       
   621                 return 2**100
       
   622         self.assertEquals(type(hash(Y())), int)
       
   623         class Z(long):
       
   624             def __hash__(self):
       
   625                 return self
       
   626         self.assertEquals(hash(Z(42)), hash(42L))
       
   627 
       
   628     def test_hex(self):
       
   629         self.assertEqual(hex(16), '0x10')
       
   630         self.assertEqual(hex(16L), '0x10L')
       
   631         self.assertEqual(hex(-16), '-0x10')
       
   632         self.assertEqual(hex(-16L), '-0x10L')
       
   633         self.assertRaises(TypeError, hex, {})
       
   634 
       
   635     def test_id(self):
       
   636         id(None)
       
   637         id(1)
       
   638         id(1L)
       
   639         id(1.0)
       
   640         id('spam')
       
   641         id((0,1,2,3))
       
   642         id([0,1,2,3])
       
   643         id({'spam': 1, 'eggs': 2, 'ham': 3})
       
   644 
       
   645     # Test input() later, together with raw_input
       
   646 
       
   647     def test_intern(self):
       
   648         self.assertRaises(TypeError, intern)
       
   649         s = "never interned before"
       
   650         self.assert_(intern(s) is s)
       
   651         s2 = s.swapcase().swapcase()
       
   652         self.assert_(intern(s2) is s)
       
   653 
       
   654         # Subclasses of string can't be interned, because they
       
   655         # provide too much opportunity for insane things to happen.
       
   656         # We don't want them in the interned dict and if they aren't
       
   657         # actually interned, we don't want to create the appearance
       
   658         # that they are by allowing intern() to succeeed.
       
   659         class S(str):
       
   660             def __hash__(self):
       
   661                 return 123
       
   662 
       
   663         self.assertRaises(TypeError, intern, S("abc"))
       
   664 
       
   665         # It's still safe to pass these strings to routines that
       
   666         # call intern internally, e.g. PyObject_SetAttr().
       
   667         s = S("abc")
       
   668         setattr(s, s, s)
       
   669         self.assertEqual(getattr(s, s), s)
       
   670 
       
   671     def test_iter(self):
       
   672         self.assertRaises(TypeError, iter)
       
   673         self.assertRaises(TypeError, iter, 42, 42)
       
   674         lists = [("1", "2"), ["1", "2"], "12"]
       
   675         if have_unicode:
       
   676             lists.append(unicode("12"))
       
   677         for l in lists:
       
   678             i = iter(l)
       
   679             self.assertEqual(i.next(), '1')
       
   680             self.assertEqual(i.next(), '2')
       
   681             self.assertRaises(StopIteration, i.next)
       
   682 
       
   683     def test_isinstance(self):
       
   684         class C:
       
   685             pass
       
   686         class D(C):
       
   687             pass
       
   688         class E:
       
   689             pass
       
   690         c = C()
       
   691         d = D()
       
   692         e = E()
       
   693         self.assert_(isinstance(c, C))
       
   694         self.assert_(isinstance(d, C))
       
   695         self.assert_(not isinstance(e, C))
       
   696         self.assert_(not isinstance(c, D))
       
   697         self.assert_(not isinstance('foo', E))
       
   698         self.assertRaises(TypeError, isinstance, E, 'foo')
       
   699         self.assertRaises(TypeError, isinstance)
       
   700 
       
   701     def test_issubclass(self):
       
   702         class C:
       
   703             pass
       
   704         class D(C):
       
   705             pass
       
   706         class E:
       
   707             pass
       
   708         c = C()
       
   709         d = D()
       
   710         e = E()
       
   711         self.assert_(issubclass(D, C))
       
   712         self.assert_(issubclass(C, C))
       
   713         self.assert_(not issubclass(C, D))
       
   714         self.assertRaises(TypeError, issubclass, 'foo', E)
       
   715         self.assertRaises(TypeError, issubclass, E, 'foo')
       
   716         self.assertRaises(TypeError, issubclass)
       
   717 
       
   718     def test_len(self):
       
   719         self.assertEqual(len('123'), 3)
       
   720         self.assertEqual(len(()), 0)
       
   721         self.assertEqual(len((1, 2, 3, 4)), 4)
       
   722         self.assertEqual(len([1, 2, 3, 4]), 4)
       
   723         self.assertEqual(len({}), 0)
       
   724         self.assertEqual(len({'a':1, 'b': 2}), 2)
       
   725         class BadSeq:
       
   726             def __len__(self):
       
   727                 raise ValueError
       
   728         self.assertRaises(ValueError, len, BadSeq())
       
   729 
       
   730     def test_map(self):
       
   731         self.assertEqual(
       
   732             map(None, 'hello world'),
       
   733             ['h','e','l','l','o',' ','w','o','r','l','d']
       
   734         )
       
   735         self.assertEqual(
       
   736             map(None, 'abcd', 'efg'),
       
   737             [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', None)]
       
   738         )
       
   739         self.assertEqual(
       
   740             map(None, range(10)),
       
   741             [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
       
   742         )
       
   743         self.assertEqual(
       
   744             map(lambda x: x*x, range(1,4)),
       
   745             [1, 4, 9]
       
   746         )
       
   747         try:
       
   748             from math import sqrt
       
   749         except ImportError:
       
   750             def sqrt(x):
       
   751                 return pow(x, 0.5)
       
   752         self.assertEqual(
       
   753             map(lambda x: map(sqrt,x), [[16, 4], [81, 9]]),
       
   754             [[4.0, 2.0], [9.0, 3.0]]
       
   755         )
       
   756         self.assertEqual(
       
   757             map(lambda x, y: x+y, [1,3,2], [9,1,4]),
       
   758             [10, 4, 6]
       
   759         )
       
   760 
       
   761         def plus(*v):
       
   762             accu = 0
       
   763             for i in v: accu = accu + i
       
   764             return accu
       
   765         self.assertEqual(
       
   766             map(plus, [1, 3, 7]),
       
   767             [1, 3, 7]
       
   768         )
       
   769         self.assertEqual(
       
   770             map(plus, [1, 3, 7], [4, 9, 2]),
       
   771             [1+4, 3+9, 7+2]
       
   772         )
       
   773         self.assertEqual(
       
   774             map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0]),
       
   775             [1+4+1, 3+9+1, 7+2+0]
       
   776         )
       
   777         self.assertEqual(
       
   778             map(None, Squares(10)),
       
   779             [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
       
   780         )
       
   781         self.assertEqual(
       
   782             map(int, Squares(10)),
       
   783             [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
       
   784         )
       
   785         self.assertEqual(
       
   786             map(None, Squares(3), Squares(2)),
       
   787             [(0,0), (1,1), (4,None)]
       
   788         )
       
   789         self.assertEqual(
       
   790             map(max, Squares(3), Squares(2)),
       
   791             [0, 1, 4]
       
   792         )
       
   793         self.assertRaises(TypeError, map)
       
   794         self.assertRaises(TypeError, map, lambda x: x, 42)
       
   795         self.assertEqual(map(None, [42]), [42])
       
   796         class BadSeq:
       
   797             def __getitem__(self, index):
       
   798                 raise ValueError
       
   799         self.assertRaises(ValueError, map, lambda x: x, BadSeq())
       
   800         def badfunc(x):
       
   801             raise RuntimeError
       
   802         self.assertRaises(RuntimeError, map, badfunc, range(5))
       
   803 
       
   804     def test_max(self):
       
   805         self.assertEqual(max('123123'), '3')
       
   806         self.assertEqual(max(1, 2, 3), 3)
       
   807         self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)
       
   808         self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)
       
   809 
       
   810         self.assertEqual(max(1, 2L, 3.0), 3.0)
       
   811         self.assertEqual(max(1L, 2.0, 3), 3)
       
   812         self.assertEqual(max(1.0, 2, 3L), 3L)
       
   813 
       
   814         for stmt in (
       
   815             "max(key=int)",                 # no args
       
   816             "max(1, key=int)",              # single arg not iterable
       
   817             "max(1, 2, keystone=int)",      # wrong keyword
       
   818             "max(1, 2, key=int, abc=int)",  # two many keywords
       
   819             "max(1, 2, key=1)",             # keyfunc is not callable
       
   820             ):
       
   821             try:
       
   822                 exec(stmt) in globals()
       
   823             except TypeError:
       
   824                 pass
       
   825             else:
       
   826                 self.fail(stmt)
       
   827 
       
   828         self.assertEqual(max((1,), key=neg), 1)     # one elem iterable
       
   829         self.assertEqual(max((1,2), key=neg), 1)    # two elem iterable
       
   830         self.assertEqual(max(1, 2, key=neg), 1)     # two elems
       
   831 
       
   832         data = [random.randrange(200) for i in range(100)]
       
   833         keys = dict((elem, random.randrange(50)) for elem in data)
       
   834         f = keys.__getitem__
       
   835         self.assertEqual(max(data, key=f),
       
   836                          sorted(reversed(data), key=f)[-1])
       
   837 
       
   838     def test_min(self):
       
   839         self.assertEqual(min('123123'), '1')
       
   840         self.assertEqual(min(1, 2, 3), 1)
       
   841         self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1)
       
   842         self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1)
       
   843 
       
   844         self.assertEqual(min(1, 2L, 3.0), 1)
       
   845         self.assertEqual(min(1L, 2.0, 3), 1L)
       
   846         self.assertEqual(min(1.0, 2, 3L), 1.0)
       
   847 
       
   848         self.assertRaises(TypeError, min)
       
   849         self.assertRaises(TypeError, min, 42)
       
   850         self.assertRaises(ValueError, min, ())
       
   851         class BadSeq:
       
   852             def __getitem__(self, index):
       
   853                 raise ValueError
       
   854         self.assertRaises(ValueError, min, BadSeq())
       
   855         class BadNumber:
       
   856             def __cmp__(self, other):
       
   857                 raise ValueError
       
   858         self.assertRaises(ValueError, min, (42, BadNumber()))
       
   859 
       
   860         for stmt in (
       
   861             "min(key=int)",                 # no args
       
   862             "min(1, key=int)",              # single arg not iterable
       
   863             "min(1, 2, keystone=int)",      # wrong keyword
       
   864             "min(1, 2, key=int, abc=int)",  # two many keywords
       
   865             "min(1, 2, key=1)",             # keyfunc is not callable
       
   866             ):
       
   867             try:
       
   868                 exec(stmt) in globals()
       
   869             except TypeError:
       
   870                 pass
       
   871             else:
       
   872                 self.fail(stmt)
       
   873 
       
   874         self.assertEqual(min((1,), key=neg), 1)     # one elem iterable
       
   875         self.assertEqual(min((1,2), key=neg), 2)    # two elem iterable
       
   876         self.assertEqual(min(1, 2, key=neg), 2)     # two elems
       
   877 
       
   878         data = [random.randrange(200) for i in range(100)]
       
   879         keys = dict((elem, random.randrange(50)) for elem in data)
       
   880         f = keys.__getitem__
       
   881         self.assertEqual(min(data, key=f),
       
   882                          sorted(data, key=f)[0])
       
   883 
       
   884     def test_next(self):
       
   885         it = iter(range(2))
       
   886         self.assertEqual(next(it), 0)
       
   887         self.assertEqual(next(it), 1)
       
   888         self.assertRaises(StopIteration, next, it)
       
   889         self.assertRaises(StopIteration, next, it)
       
   890         self.assertEquals(next(it, 42), 42)
       
   891 
       
   892         class Iter(object):
       
   893             def __iter__(self):
       
   894                 return self
       
   895             def next(self):
       
   896                 raise StopIteration
       
   897 
       
   898         it = iter(Iter())
       
   899         self.assertEquals(next(it, 42), 42)
       
   900         self.assertRaises(StopIteration, next, it)
       
   901 
       
   902         def gen():
       
   903             yield 1
       
   904             return
       
   905 
       
   906         it = gen()
       
   907         self.assertEquals(next(it), 1)
       
   908         self.assertRaises(StopIteration, next, it)
       
   909         self.assertEquals(next(it, 42), 42)
       
   910 
       
   911     def test_oct(self):
       
   912         self.assertEqual(oct(100), '0144')
       
   913         self.assertEqual(oct(100L), '0144L')
       
   914         self.assertEqual(oct(-100), '-0144')
       
   915         self.assertEqual(oct(-100L), '-0144L')
       
   916         self.assertRaises(TypeError, oct, ())
       
   917 
       
   918     def write_testfile(self):
       
   919         # NB the first 4 lines are also used to test input and raw_input, below
       
   920         fp = open(TESTFN, 'w')
       
   921         try:
       
   922             fp.write('1+1\n')
       
   923             fp.write('1+1\n')
       
   924             fp.write('The quick brown fox jumps over the lazy dog')
       
   925             fp.write('.\n')
       
   926             fp.write('Dear John\n')
       
   927             fp.write('XXX'*100)
       
   928             fp.write('YYY'*100)
       
   929         finally:
       
   930             fp.close()
       
   931 
       
   932     def test_open(self):
       
   933         self.write_testfile()
       
   934         fp = open(TESTFN, 'r')
       
   935         try:
       
   936             self.assertEqual(fp.readline(4), '1+1\n')
       
   937             self.assertEqual(fp.readline(4), '1+1\n')
       
   938             self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n')
       
   939             self.assertEqual(fp.readline(4), 'Dear')
       
   940             self.assertEqual(fp.readline(100), ' John\n')
       
   941             self.assertEqual(fp.read(300), 'XXX'*100)
       
   942             self.assertEqual(fp.read(1000), 'YYY'*100)
       
   943         finally:
       
   944             fp.close()
       
   945         unlink(TESTFN)
       
   946 
       
   947     def test_ord(self):
       
   948         self.assertEqual(ord(' '), 32)
       
   949         self.assertEqual(ord('A'), 65)
       
   950         self.assertEqual(ord('a'), 97)
       
   951         if have_unicode:
       
   952             self.assertEqual(ord(unichr(sys.maxunicode)), sys.maxunicode)
       
   953         self.assertRaises(TypeError, ord, 42)
       
   954         if have_unicode:
       
   955             self.assertRaises(TypeError, ord, unicode("12"))
       
   956 
       
   957     def test_pow(self):
       
   958         self.assertEqual(pow(0,0), 1)
       
   959         self.assertEqual(pow(0,1), 0)
       
   960         self.assertEqual(pow(1,0), 1)
       
   961         self.assertEqual(pow(1,1), 1)
       
   962 
       
   963         self.assertEqual(pow(2,0), 1)
       
   964         self.assertEqual(pow(2,10), 1024)
       
   965         self.assertEqual(pow(2,20), 1024*1024)
       
   966         self.assertEqual(pow(2,30), 1024*1024*1024)
       
   967 
       
   968         self.assertEqual(pow(-2,0), 1)
       
   969         self.assertEqual(pow(-2,1), -2)
       
   970         self.assertEqual(pow(-2,2), 4)
       
   971         self.assertEqual(pow(-2,3), -8)
       
   972 
       
   973         self.assertEqual(pow(0L,0), 1)
       
   974         self.assertEqual(pow(0L,1), 0)
       
   975         self.assertEqual(pow(1L,0), 1)
       
   976         self.assertEqual(pow(1L,1), 1)
       
   977 
       
   978         self.assertEqual(pow(2L,0), 1)
       
   979         self.assertEqual(pow(2L,10), 1024)
       
   980         self.assertEqual(pow(2L,20), 1024*1024)
       
   981         self.assertEqual(pow(2L,30), 1024*1024*1024)
       
   982 
       
   983         self.assertEqual(pow(-2L,0), 1)
       
   984         self.assertEqual(pow(-2L,1), -2)
       
   985         self.assertEqual(pow(-2L,2), 4)
       
   986         self.assertEqual(pow(-2L,3), -8)
       
   987 
       
   988         self.assertAlmostEqual(pow(0.,0), 1.)
       
   989         self.assertAlmostEqual(pow(0.,1), 0.)
       
   990         self.assertAlmostEqual(pow(1.,0), 1.)
       
   991         self.assertAlmostEqual(pow(1.,1), 1.)
       
   992 
       
   993         self.assertAlmostEqual(pow(2.,0), 1.)
       
   994         self.assertAlmostEqual(pow(2.,10), 1024.)
       
   995         self.assertAlmostEqual(pow(2.,20), 1024.*1024.)
       
   996         self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.)
       
   997 
       
   998         self.assertAlmostEqual(pow(-2.,0), 1.)
       
   999         self.assertAlmostEqual(pow(-2.,1), -2.)
       
  1000         self.assertAlmostEqual(pow(-2.,2), 4.)
       
  1001         self.assertAlmostEqual(pow(-2.,3), -8.)
       
  1002 
       
  1003         for x in 2, 2L, 2.0:
       
  1004             for y in 10, 10L, 10.0:
       
  1005                 for z in 1000, 1000L, 1000.0:
       
  1006                     if isinstance(x, float) or \
       
  1007                        isinstance(y, float) or \
       
  1008                        isinstance(z, float):
       
  1009                         self.assertRaises(TypeError, pow, x, y, z)
       
  1010                     else:
       
  1011                         self.assertAlmostEqual(pow(x, y, z), 24.0)
       
  1012 
       
  1013         self.assertRaises(TypeError, pow, -1, -2, 3)
       
  1014         self.assertRaises(ValueError, pow, 1, 2, 0)
       
  1015         self.assertRaises(TypeError, pow, -1L, -2L, 3L)
       
  1016         self.assertRaises(ValueError, pow, 1L, 2L, 0L)
       
  1017         # Will return complex in 3.0:
       
  1018         self.assertRaises(ValueError, pow, -342.43, 0.234)
       
  1019 
       
  1020         self.assertRaises(TypeError, pow)
       
  1021 
       
  1022     def test_range(self):
       
  1023         self.assertEqual(range(3), [0, 1, 2])
       
  1024         self.assertEqual(range(1, 5), [1, 2, 3, 4])
       
  1025         self.assertEqual(range(0), [])
       
  1026         self.assertEqual(range(-3), [])
       
  1027         self.assertEqual(range(1, 10, 3), [1, 4, 7])
       
  1028         self.assertEqual(range(5, -5, -3), [5, 2, -1, -4])
       
  1029 
       
  1030         # Now test range() with longs
       
  1031         self.assertEqual(range(-2**100), [])
       
  1032         self.assertEqual(range(0, -2**100), [])
       
  1033         self.assertEqual(range(0, 2**100, -1), [])
       
  1034         self.assertEqual(range(0, 2**100, -1), [])
       
  1035 
       
  1036         a = long(10 * sys.maxint)
       
  1037         b = long(100 * sys.maxint)
       
  1038         c = long(50 * sys.maxint)
       
  1039 
       
  1040         self.assertEqual(range(a, a+2), [a, a+1])
       
  1041         self.assertEqual(range(a+2, a, -1L), [a+2, a+1])
       
  1042         self.assertEqual(range(a+4, a, -2), [a+4, a+2])
       
  1043 
       
  1044         seq = range(a, b, c)
       
  1045         self.assert_(a in seq)
       
  1046         self.assert_(b not in seq)
       
  1047         self.assertEqual(len(seq), 2)
       
  1048 
       
  1049         seq = range(b, a, -c)
       
  1050         self.assert_(b in seq)
       
  1051         self.assert_(a not in seq)
       
  1052         self.assertEqual(len(seq), 2)
       
  1053 
       
  1054         seq = range(-a, -b, -c)
       
  1055         self.assert_(-a in seq)
       
  1056         self.assert_(-b not in seq)
       
  1057         self.assertEqual(len(seq), 2)
       
  1058 
       
  1059         self.assertRaises(TypeError, range)
       
  1060         self.assertRaises(TypeError, range, 1, 2, 3, 4)
       
  1061         self.assertRaises(ValueError, range, 1, 2, 0)
       
  1062         self.assertRaises(ValueError, range, a, a + 1, long(0))
       
  1063 
       
  1064         class badzero(int):
       
  1065             def __cmp__(self, other):
       
  1066                 raise RuntimeError
       
  1067             __hash__ = None # Invalid cmp makes this unhashable
       
  1068         self.assertRaises(RuntimeError, range, a, a + 1, badzero(1))
       
  1069 
       
  1070         # Reject floats when it would require PyLongs to represent.
       
  1071         # (smaller floats still accepted, but deprecated)
       
  1072         self.assertRaises(TypeError, range, 1e100, 1e101, 1e101)
       
  1073 
       
  1074         self.assertRaises(TypeError, range, 0, "spam")
       
  1075         self.assertRaises(TypeError, range, 0, 42, "spam")
       
  1076 
       
  1077         self.assertRaises(OverflowError, range, -sys.maxint, sys.maxint)
       
  1078         self.assertRaises(OverflowError, range, 0, 2*sys.maxint)
       
  1079 
       
  1080     def test_input_and_raw_input(self):
       
  1081         self.write_testfile()
       
  1082         fp = open(TESTFN, 'r')
       
  1083         savestdin = sys.stdin
       
  1084         savestdout = sys.stdout # Eats the echo
       
  1085         try:
       
  1086             sys.stdin = fp
       
  1087             sys.stdout = BitBucket()
       
  1088             self.assertEqual(input(), 2)
       
  1089             self.assertEqual(input('testing\n'), 2)
       
  1090             self.assertEqual(raw_input(), 'The quick brown fox jumps over the lazy dog.')
       
  1091             self.assertEqual(raw_input('testing\n'), 'Dear John')
       
  1092 
       
  1093             # SF 1535165: don't segfault on closed stdin
       
  1094             # sys.stdout must be a regular file for triggering
       
  1095             sys.stdout = savestdout
       
  1096             sys.stdin.close()
       
  1097             self.assertRaises(ValueError, input)
       
  1098 
       
  1099             sys.stdout = BitBucket()
       
  1100             sys.stdin = cStringIO.StringIO("NULL\0")
       
  1101             self.assertRaises(TypeError, input, 42, 42)
       
  1102             sys.stdin = cStringIO.StringIO("    'whitespace'")
       
  1103             self.assertEqual(input(), 'whitespace')
       
  1104             sys.stdin = cStringIO.StringIO()
       
  1105             self.assertRaises(EOFError, input)
       
  1106 
       
  1107             # SF 876178: make sure input() respect future options.
       
  1108             sys.stdin = cStringIO.StringIO('1/2')
       
  1109             sys.stdout = cStringIO.StringIO()
       
  1110             exec compile('print input()', 'test_builtin_tmp', 'exec')
       
  1111             sys.stdin.seek(0, 0)
       
  1112             exec compile('from __future__ import division;print input()',
       
  1113                          'test_builtin_tmp', 'exec')
       
  1114             sys.stdin.seek(0, 0)
       
  1115             exec compile('print input()', 'test_builtin_tmp', 'exec')
       
  1116             # The result we expect depends on whether new division semantics
       
  1117             # are already in effect.
       
  1118             if 1/2 == 0:
       
  1119                 # This test was compiled with old semantics.
       
  1120                 expected = ['0', '0.5', '0']
       
  1121             else:
       
  1122                 # This test was compiled with new semantics (e.g., -Qnew
       
  1123                 # was given on the command line.
       
  1124                 expected = ['0.5', '0.5', '0.5']
       
  1125             self.assertEqual(sys.stdout.getvalue().splitlines(), expected)
       
  1126 
       
  1127             del sys.stdout
       
  1128             self.assertRaises(RuntimeError, input, 'prompt')
       
  1129             del sys.stdin
       
  1130             self.assertRaises(RuntimeError, input, 'prompt')
       
  1131         finally:
       
  1132             sys.stdin = savestdin
       
  1133             sys.stdout = savestdout
       
  1134             fp.close()
       
  1135             unlink(TESTFN)
       
  1136 
       
  1137     def test_reduce(self):
       
  1138         self.assertEqual(reduce(lambda x, y: x+y, ['a', 'b', 'c'], ''), 'abc')
       
  1139         self.assertEqual(
       
  1140             reduce(lambda x, y: x+y, [['a', 'c'], [], ['d', 'w']], []),
       
  1141             ['a','c','d','w']
       
  1142         )
       
  1143         self.assertEqual(reduce(lambda x, y: x*y, range(2,8), 1), 5040)
       
  1144         self.assertEqual(
       
  1145             reduce(lambda x, y: x*y, range(2,21), 1L),
       
  1146             2432902008176640000L
       
  1147         )
       
  1148         self.assertEqual(reduce(lambda x, y: x+y, Squares(10)), 285)
       
  1149         self.assertEqual(reduce(lambda x, y: x+y, Squares(10), 0), 285)
       
  1150         self.assertEqual(reduce(lambda x, y: x+y, Squares(0), 0), 0)
       
  1151         self.assertRaises(TypeError, reduce)
       
  1152         self.assertRaises(TypeError, reduce, 42, 42)
       
  1153         self.assertRaises(TypeError, reduce, 42, 42, 42)
       
  1154         self.assertEqual(reduce(42, "1"), "1") # func is never called with one item
       
  1155         self.assertEqual(reduce(42, "", "1"), "1") # func is never called with one item
       
  1156         self.assertRaises(TypeError, reduce, 42, (42, 42))
       
  1157 
       
  1158         class BadSeq:
       
  1159             def __getitem__(self, index):
       
  1160                 raise ValueError
       
  1161         self.assertRaises(ValueError, reduce, 42, BadSeq())
       
  1162 
       
  1163     def test_reload(self):
       
  1164         import marshal
       
  1165         reload(marshal)
       
  1166         import string
       
  1167         reload(string)
       
  1168         ## import sys
       
  1169         ## self.assertRaises(ImportError, reload, sys)
       
  1170 
       
  1171     def test_repr(self):
       
  1172         self.assertEqual(repr(''), '\'\'')
       
  1173         self.assertEqual(repr(0), '0')
       
  1174         self.assertEqual(repr(0L), '0L')
       
  1175         self.assertEqual(repr(()), '()')
       
  1176         self.assertEqual(repr([]), '[]')
       
  1177         self.assertEqual(repr({}), '{}')
       
  1178         a = []
       
  1179         a.append(a)
       
  1180         self.assertEqual(repr(a), '[[...]]')
       
  1181         a = {}
       
  1182         a[0] = a
       
  1183         self.assertEqual(repr(a), '{0: {...}}')
       
  1184 
       
  1185     def test_round(self):
       
  1186         self.assertEqual(round(0.0), 0.0)
       
  1187         self.assertEqual(type(round(0.0)), float)  # Will be int in 3.0.
       
  1188         self.assertEqual(round(1.0), 1.0)
       
  1189         self.assertEqual(round(10.0), 10.0)
       
  1190         self.assertEqual(round(1000000000.0), 1000000000.0)
       
  1191         self.assertEqual(round(1e20), 1e20)
       
  1192 
       
  1193         self.assertEqual(round(-1.0), -1.0)
       
  1194         self.assertEqual(round(-10.0), -10.0)
       
  1195         self.assertEqual(round(-1000000000.0), -1000000000.0)
       
  1196         self.assertEqual(round(-1e20), -1e20)
       
  1197 
       
  1198         self.assertEqual(round(0.1), 0.0)
       
  1199         self.assertEqual(round(1.1), 1.0)
       
  1200         self.assertEqual(round(10.1), 10.0)
       
  1201         self.assertEqual(round(1000000000.1), 1000000000.0)
       
  1202 
       
  1203         self.assertEqual(round(-1.1), -1.0)
       
  1204         self.assertEqual(round(-10.1), -10.0)
       
  1205         self.assertEqual(round(-1000000000.1), -1000000000.0)
       
  1206 
       
  1207         self.assertEqual(round(0.9), 1.0)
       
  1208         self.assertEqual(round(9.9), 10.0)
       
  1209         self.assertEqual(round(999999999.9), 1000000000.0)
       
  1210 
       
  1211         self.assertEqual(round(-0.9), -1.0)
       
  1212         self.assertEqual(round(-9.9), -10.0)
       
  1213         self.assertEqual(round(-999999999.9), -1000000000.0)
       
  1214 
       
  1215         self.assertEqual(round(-8.0, -1), -10.0)
       
  1216         self.assertEqual(type(round(-8.0, -1)), float)
       
  1217 
       
  1218         self.assertEqual(type(round(-8.0, 0)), float)
       
  1219         self.assertEqual(type(round(-8.0, 1)), float)
       
  1220 
       
  1221         # Check half rounding behaviour.
       
  1222         self.assertEqual(round(5.5), 6)
       
  1223         self.assertEqual(round(6.5), 7)
       
  1224         self.assertEqual(round(-5.5), -6)
       
  1225         self.assertEqual(round(-6.5), -7)
       
  1226 
       
  1227         # Check behavior on ints
       
  1228         self.assertEqual(round(0), 0)
       
  1229         self.assertEqual(round(8), 8)
       
  1230         self.assertEqual(round(-8), -8)
       
  1231         self.assertEqual(type(round(0)), float)  # Will be int in 3.0.
       
  1232         self.assertEqual(type(round(-8, -1)), float)
       
  1233         self.assertEqual(type(round(-8, 0)), float)
       
  1234         self.assertEqual(type(round(-8, 1)), float)
       
  1235 
       
  1236         # test new kwargs
       
  1237         self.assertEqual(round(number=-8.0, ndigits=-1), -10.0)
       
  1238 
       
  1239         self.assertRaises(TypeError, round)
       
  1240 
       
  1241         # test generic rounding delegation for reals
       
  1242         class TestRound(object):
       
  1243             def __float__(self):
       
  1244                 return 23.0
       
  1245 
       
  1246         class TestNoRound(object):
       
  1247             pass
       
  1248 
       
  1249         self.assertEqual(round(TestRound()), 23)
       
  1250 
       
  1251         self.assertRaises(TypeError, round, 1, 2, 3)
       
  1252         self.assertRaises(TypeError, round, TestNoRound())
       
  1253 
       
  1254         t = TestNoRound()
       
  1255         t.__float__ = lambda *args: args
       
  1256         self.assertRaises(TypeError, round, t)
       
  1257         self.assertRaises(TypeError, round, t, 0)
       
  1258 
       
  1259     def test_setattr(self):
       
  1260         setattr(sys, 'spam', 1)
       
  1261         self.assertEqual(sys.spam, 1)
       
  1262         self.assertRaises(TypeError, setattr, sys, 1, 'spam')
       
  1263         self.assertRaises(TypeError, setattr)
       
  1264 
       
  1265     def test_sum(self):
       
  1266         self.assertEqual(sum([]), 0)
       
  1267         self.assertEqual(sum(range(2,8)), 27)
       
  1268         self.assertEqual(sum(iter(range(2,8))), 27)
       
  1269         self.assertEqual(sum(Squares(10)), 285)
       
  1270         self.assertEqual(sum(iter(Squares(10))), 285)
       
  1271         self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])
       
  1272 
       
  1273         self.assertRaises(TypeError, sum)
       
  1274         self.assertRaises(TypeError, sum, 42)
       
  1275         self.assertRaises(TypeError, sum, ['a', 'b', 'c'])
       
  1276         self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '')
       
  1277         self.assertRaises(TypeError, sum, [[1], [2], [3]])
       
  1278         self.assertRaises(TypeError, sum, [{2:3}])
       
  1279         self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3})
       
  1280 
       
  1281         class BadSeq:
       
  1282             def __getitem__(self, index):
       
  1283                 raise ValueError
       
  1284         self.assertRaises(ValueError, sum, BadSeq())
       
  1285 
       
  1286     def test_type(self):
       
  1287         self.assertEqual(type(''),  type('123'))
       
  1288         self.assertNotEqual(type(''), type(()))
       
  1289 
       
  1290     def test_unichr(self):
       
  1291         if have_unicode:
       
  1292             self.assertEqual(unichr(32), unicode(' '))
       
  1293             self.assertEqual(unichr(65), unicode('A'))
       
  1294             self.assertEqual(unichr(97), unicode('a'))
       
  1295             self.assertEqual(
       
  1296                 unichr(sys.maxunicode),
       
  1297                 unicode('\\U%08x' % (sys.maxunicode), 'unicode-escape')
       
  1298             )
       
  1299             self.assertRaises(ValueError, unichr, sys.maxunicode+1)
       
  1300             self.assertRaises(TypeError, unichr)
       
  1301             self.assertRaises((OverflowError, ValueError), unichr, 2**32)
       
  1302 
       
  1303     # We don't want self in vars(), so these are static methods
       
  1304 
       
  1305     @staticmethod
       
  1306     def get_vars_f0():
       
  1307         return vars()
       
  1308 
       
  1309     @staticmethod
       
  1310     def get_vars_f2():
       
  1311         BuiltinTest.get_vars_f0()
       
  1312         a = 1
       
  1313         b = 2
       
  1314         return vars()
       
  1315 
       
  1316     def test_vars(self):
       
  1317         self.assertEqual(set(vars()), set(dir()))
       
  1318         import sys
       
  1319         self.assertEqual(set(vars(sys)), set(dir(sys)))
       
  1320         self.assertEqual(self.get_vars_f0(), {})
       
  1321         self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2})
       
  1322         self.assertRaises(TypeError, vars, 42, 42)
       
  1323         self.assertRaises(TypeError, vars, 42)
       
  1324 
       
  1325     def test_zip(self):
       
  1326         a = (1, 2, 3)
       
  1327         b = (4, 5, 6)
       
  1328         t = [(1, 4), (2, 5), (3, 6)]
       
  1329         self.assertEqual(zip(a, b), t)
       
  1330         b = [4, 5, 6]
       
  1331         self.assertEqual(zip(a, b), t)
       
  1332         b = (4, 5, 6, 7)
       
  1333         self.assertEqual(zip(a, b), t)
       
  1334         class I:
       
  1335             def __getitem__(self, i):
       
  1336                 if i < 0 or i > 2: raise IndexError
       
  1337                 return i + 4
       
  1338         self.assertEqual(zip(a, I()), t)
       
  1339         self.assertEqual(zip(), [])
       
  1340         self.assertEqual(zip(*[]), [])
       
  1341         self.assertRaises(TypeError, zip, None)
       
  1342         class G:
       
  1343             pass
       
  1344         self.assertRaises(TypeError, zip, a, G())
       
  1345 
       
  1346         # Make sure zip doesn't try to allocate a billion elements for the
       
  1347         # result list when one of its arguments doesn't say how long it is.
       
  1348         # A MemoryError is the most likely failure mode.
       
  1349         class SequenceWithoutALength:
       
  1350             def __getitem__(self, i):
       
  1351                 if i == 5:
       
  1352                     raise IndexError
       
  1353                 else:
       
  1354                     return i
       
  1355         self.assertEqual(
       
  1356             zip(SequenceWithoutALength(), xrange(2**30)),
       
  1357             list(enumerate(range(5)))
       
  1358         )
       
  1359 
       
  1360         class BadSeq:
       
  1361             def __getitem__(self, i):
       
  1362                 if i == 5:
       
  1363                     raise ValueError
       
  1364                 else:
       
  1365                     return i
       
  1366         self.assertRaises(ValueError, zip, BadSeq(), BadSeq())
       
  1367 
       
  1368     def test_format(self):
       
  1369         # Test the basic machinery of the format() builtin.  Don't test
       
  1370         #  the specifics of the various formatters
       
  1371         self.assertEqual(format(3, ''), '3')
       
  1372 
       
  1373         # Returns some classes to use for various tests.  There's
       
  1374         #  an old-style version, and a new-style version
       
  1375         def classes_new():
       
  1376             class A(object):
       
  1377                 def __init__(self, x):
       
  1378                     self.x = x
       
  1379                 def __format__(self, format_spec):
       
  1380                     return str(self.x) + format_spec
       
  1381             class DerivedFromA(A):
       
  1382                 pass
       
  1383 
       
  1384             class Simple(object): pass
       
  1385             class DerivedFromSimple(Simple):
       
  1386                 def __init__(self, x):
       
  1387                     self.x = x
       
  1388                 def __format__(self, format_spec):
       
  1389                     return str(self.x) + format_spec
       
  1390             class DerivedFromSimple2(DerivedFromSimple): pass
       
  1391             return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2
       
  1392 
       
  1393         # In 3.0, classes_classic has the same meaning as classes_new
       
  1394         def classes_classic():
       
  1395             class A:
       
  1396                 def __init__(self, x):
       
  1397                     self.x = x
       
  1398                 def __format__(self, format_spec):
       
  1399                     return str(self.x) + format_spec
       
  1400             class DerivedFromA(A):
       
  1401                 pass
       
  1402 
       
  1403             class Simple: pass
       
  1404             class DerivedFromSimple(Simple):
       
  1405                 def __init__(self, x):
       
  1406                     self.x = x
       
  1407                 def __format__(self, format_spec):
       
  1408                     return str(self.x) + format_spec
       
  1409             class DerivedFromSimple2(DerivedFromSimple): pass
       
  1410             return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2
       
  1411 
       
  1412         def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2):
       
  1413             self.assertEqual(format(A(3), 'spec'), '3spec')
       
  1414             self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec')
       
  1415             self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc')
       
  1416             self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'),
       
  1417                              '10abcdef')
       
  1418 
       
  1419         class_test(*classes_new())
       
  1420         class_test(*classes_classic())
       
  1421 
       
  1422         def empty_format_spec(value):
       
  1423             # test that:
       
  1424             #  format(x, '') == str(x)
       
  1425             #  format(x) == str(x)
       
  1426             self.assertEqual(format(value, ""), str(value))
       
  1427             self.assertEqual(format(value), str(value))
       
  1428 
       
  1429         # for builtin types, format(x, "") == str(x)
       
  1430         empty_format_spec(17**13)
       
  1431         empty_format_spec(1.0)
       
  1432         empty_format_spec(3.1415e104)
       
  1433         empty_format_spec(-3.1415e104)
       
  1434         empty_format_spec(3.1415e-104)
       
  1435         empty_format_spec(-3.1415e-104)
       
  1436         empty_format_spec(object)
       
  1437         empty_format_spec(None)
       
  1438 
       
  1439         # TypeError because self.__format__ returns the wrong type
       
  1440         class BadFormatResult:
       
  1441             def __format__(self, format_spec):
       
  1442                 return 1.0
       
  1443         self.assertRaises(TypeError, format, BadFormatResult(), "")
       
  1444 
       
  1445         # TypeError because format_spec is not unicode or str
       
  1446         self.assertRaises(TypeError, format, object(), 4)
       
  1447         self.assertRaises(TypeError, format, object(), object())
       
  1448 
       
  1449         # tests for object.__format__ really belong elsewhere, but
       
  1450         #  there's no good place to put them
       
  1451         x = object().__format__('')
       
  1452         self.assert_(x.startswith('<object object at'))
       
  1453 
       
  1454         # first argument to object.__format__ must be string
       
  1455         self.assertRaises(TypeError, object().__format__, 3)
       
  1456         self.assertRaises(TypeError, object().__format__, object())
       
  1457         self.assertRaises(TypeError, object().__format__, None)
       
  1458 
       
  1459         # make sure we can take a subclass of str as a format spec
       
  1460         class DerivedFromStr(str): pass
       
  1461         self.assertEqual(format(0, DerivedFromStr('10')), '         0')
       
  1462 
       
  1463     def test_bin(self):
       
  1464         self.assertEqual(bin(0), '0b0')
       
  1465         self.assertEqual(bin(1), '0b1')
       
  1466         self.assertEqual(bin(-1), '-0b1')
       
  1467         self.assertEqual(bin(2**65), '0b1' + '0' * 65)
       
  1468         self.assertEqual(bin(2**65-1), '0b' + '1' * 65)
       
  1469         self.assertEqual(bin(-(2**65)), '-0b1' + '0' * 65)
       
  1470         self.assertEqual(bin(-(2**65-1)), '-0b' + '1' * 65)
       
  1471 
       
  1472 class TestSorted(unittest.TestCase):
       
  1473 
       
  1474     def test_basic(self):
       
  1475         data = range(100)
       
  1476         copy = data[:]
       
  1477         random.shuffle(copy)
       
  1478         self.assertEqual(data, sorted(copy))
       
  1479         self.assertNotEqual(data, copy)
       
  1480 
       
  1481         data.reverse()
       
  1482         random.shuffle(copy)
       
  1483         self.assertEqual(data, sorted(copy, cmp=lambda x, y: cmp(y,x)))
       
  1484         self.assertNotEqual(data, copy)
       
  1485         random.shuffle(copy)
       
  1486         self.assertEqual(data, sorted(copy, key=lambda x: -x))
       
  1487         self.assertNotEqual(data, copy)
       
  1488         random.shuffle(copy)
       
  1489         self.assertEqual(data, sorted(copy, reverse=1))
       
  1490         self.assertNotEqual(data, copy)
       
  1491 
       
  1492     def test_inputtypes(self):
       
  1493         s = 'abracadabra'
       
  1494         types = [list, tuple]
       
  1495         if have_unicode:
       
  1496             types.insert(0, unicode)
       
  1497         for T in types:
       
  1498             self.assertEqual(sorted(s), sorted(T(s)))
       
  1499 
       
  1500         s = ''.join(dict.fromkeys(s).keys())  # unique letters only
       
  1501         types = [set, frozenset, list, tuple, dict.fromkeys]
       
  1502         if have_unicode:
       
  1503             types.insert(0, unicode)
       
  1504         for T in types:
       
  1505             self.assertEqual(sorted(s), sorted(T(s)))
       
  1506 
       
  1507     def test_baddecorator(self):
       
  1508         data = 'The quick Brown fox Jumped over The lazy Dog'.split()
       
  1509         self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0)
       
  1510 
       
  1511 def test_main(verbose=None):
       
  1512     test_classes = (BuiltinTest, TestSorted)
       
  1513 
       
  1514     run_unittest(*test_classes)
       
  1515 
       
  1516     # verify reference counting
       
  1517     if verbose and hasattr(sys, "gettotalrefcount"):
       
  1518         import gc
       
  1519         counts = [None] * 5
       
  1520         for i in xrange(len(counts)):
       
  1521             run_unittest(*test_classes)
       
  1522             gc.collect()
       
  1523             counts[i] = sys.gettotalrefcount()
       
  1524         print counts
       
  1525 
       
  1526 
       
  1527 if __name__ == "__main__":
       
  1528     test_main(verbose=True)