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