• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Python test set -- built-in functions
2
3import ast
4import asyncio
5import builtins
6import collections
7import decimal
8import fractions
9import io
10import locale
11import os
12import pickle
13import platform
14import random
15import re
16import sys
17import traceback
18import types
19import unittest
20import warnings
21from contextlib import ExitStack
22from functools import partial
23from inspect import CO_COROUTINE
24from itertools import product
25from textwrap import dedent
26from types import AsyncGeneratorType, FunctionType
27from operator import neg
28from test.support import (
29    EnvironmentVarGuard, TESTFN, check_warnings, swap_attr, unlink,
30    maybe_get_event_loop_policy)
31from test.support.script_helper import assert_python_ok
32from unittest.mock import MagicMock, patch
33try:
34    import pty, signal
35except ImportError:
36    pty = signal = None
37
38
39class Squares:
40
41    def __init__(self, max):
42        self.max = max
43        self.sofar = []
44
45    def __len__(self): return len(self.sofar)
46
47    def __getitem__(self, i):
48        if not 0 <= i < self.max: raise IndexError
49        n = len(self.sofar)
50        while n <= i:
51            self.sofar.append(n*n)
52            n += 1
53        return self.sofar[i]
54
55class StrSquares:
56
57    def __init__(self, max):
58        self.max = max
59        self.sofar = []
60
61    def __len__(self):
62        return len(self.sofar)
63
64    def __getitem__(self, i):
65        if not 0 <= i < self.max:
66            raise IndexError
67        n = len(self.sofar)
68        while n <= i:
69            self.sofar.append(str(n*n))
70            n += 1
71        return self.sofar[i]
72
73class BitBucket:
74    def write(self, line):
75        pass
76
77test_conv_no_sign = [
78        ('0', 0),
79        ('1', 1),
80        ('9', 9),
81        ('10', 10),
82        ('99', 99),
83        ('100', 100),
84        ('314', 314),
85        (' 314', 314),
86        ('314 ', 314),
87        ('  \t\t  314  \t\t  ', 314),
88        (repr(sys.maxsize), sys.maxsize),
89        ('  1x', ValueError),
90        ('  1  ', 1),
91        ('  1\02  ', ValueError),
92        ('', ValueError),
93        (' ', ValueError),
94        ('  \t\t  ', ValueError),
95        (str(br'\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
96        (chr(0x200), ValueError),
97]
98
99test_conv_sign = [
100        ('0', 0),
101        ('1', 1),
102        ('9', 9),
103        ('10', 10),
104        ('99', 99),
105        ('100', 100),
106        ('314', 314),
107        (' 314', ValueError),
108        ('314 ', 314),
109        ('  \t\t  314  \t\t  ', ValueError),
110        (repr(sys.maxsize), sys.maxsize),
111        ('  1x', ValueError),
112        ('  1  ', ValueError),
113        ('  1\02  ', ValueError),
114        ('', ValueError),
115        (' ', ValueError),
116        ('  \t\t  ', ValueError),
117        (str(br'\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
118        (chr(0x200), ValueError),
119]
120
121class TestFailingBool:
122    def __bool__(self):
123        raise RuntimeError
124
125class TestFailingIter:
126    def __iter__(self):
127        raise RuntimeError
128
129def filter_char(arg):
130    return ord(arg) > ord("d")
131
132def map_char(arg):
133    return chr(ord(arg)+1)
134
135class BuiltinTest(unittest.TestCase):
136    # Helper to check picklability
137    def check_iter_pickle(self, it, seq, proto):
138        itorg = it
139        d = pickle.dumps(it, proto)
140        it = pickle.loads(d)
141        self.assertEqual(type(itorg), type(it))
142        self.assertEqual(list(it), seq)
143
144        #test the iterator after dropping one from it
145        it = pickle.loads(d)
146        try:
147            next(it)
148        except StopIteration:
149            return
150        d = pickle.dumps(it, proto)
151        it = pickle.loads(d)
152        self.assertEqual(list(it), seq[1:])
153
154    def test_import(self):
155        __import__('sys')
156        __import__('time')
157        __import__('string')
158        __import__(name='sys')
159        __import__(name='time', level=0)
160        self.assertRaises(ImportError, __import__, 'spamspam')
161        self.assertRaises(TypeError, __import__, 1, 2, 3, 4)
162        self.assertRaises(ValueError, __import__, '')
163        self.assertRaises(TypeError, __import__, 'sys', name='sys')
164        # Relative import outside of a package with no __package__ or __spec__ (bpo-37409).
165        with self.assertWarns(ImportWarning):
166            self.assertRaises(ImportError, __import__, '',
167                              {'__package__': None, '__spec__': None, '__name__': '__main__'},
168                              locals={}, fromlist=('foo',), level=1)
169        # embedded null character
170        self.assertRaises(ModuleNotFoundError, __import__, 'string\x00')
171
172    def test_abs(self):
173        # int
174        self.assertEqual(abs(0), 0)
175        self.assertEqual(abs(1234), 1234)
176        self.assertEqual(abs(-1234), 1234)
177        self.assertTrue(abs(-sys.maxsize-1) > 0)
178        # float
179        self.assertEqual(abs(0.0), 0.0)
180        self.assertEqual(abs(3.14), 3.14)
181        self.assertEqual(abs(-3.14), 3.14)
182        # str
183        self.assertRaises(TypeError, abs, 'a')
184        # bool
185        self.assertEqual(abs(True), 1)
186        self.assertEqual(abs(False), 0)
187        # other
188        self.assertRaises(TypeError, abs)
189        self.assertRaises(TypeError, abs, None)
190        class AbsClass(object):
191            def __abs__(self):
192                return -5
193        self.assertEqual(abs(AbsClass()), -5)
194
195    def test_all(self):
196        self.assertEqual(all([2, 4, 6]), True)
197        self.assertEqual(all([2, None, 6]), False)
198        self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6])
199        self.assertRaises(RuntimeError, all, TestFailingIter())
200        self.assertRaises(TypeError, all, 10)               # Non-iterable
201        self.assertRaises(TypeError, all)                   # No args
202        self.assertRaises(TypeError, all, [2, 4, 6], [])    # Too many args
203        self.assertEqual(all([]), True)                     # Empty iterator
204        self.assertEqual(all([0, TestFailingBool()]), False)# Short-circuit
205        S = [50, 60]
206        self.assertEqual(all(x > 42 for x in S), True)
207        S = [50, 40, 60]
208        self.assertEqual(all(x > 42 for x in S), False)
209
210    def test_any(self):
211        self.assertEqual(any([None, None, None]), False)
212        self.assertEqual(any([None, 4, None]), True)
213        self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6])
214        self.assertRaises(RuntimeError, any, TestFailingIter())
215        self.assertRaises(TypeError, any, 10)               # Non-iterable
216        self.assertRaises(TypeError, any)                   # No args
217        self.assertRaises(TypeError, any, [2, 4, 6], [])    # Too many args
218        self.assertEqual(any([]), False)                    # Empty iterator
219        self.assertEqual(any([1, TestFailingBool()]), True) # Short-circuit
220        S = [40, 60, 30]
221        self.assertEqual(any(x > 42 for x in S), True)
222        S = [10, 20, 30]
223        self.assertEqual(any(x > 42 for x in S), False)
224
225    def test_ascii(self):
226        self.assertEqual(ascii(''), '\'\'')
227        self.assertEqual(ascii(0), '0')
228        self.assertEqual(ascii(()), '()')
229        self.assertEqual(ascii([]), '[]')
230        self.assertEqual(ascii({}), '{}')
231        a = []
232        a.append(a)
233        self.assertEqual(ascii(a), '[[...]]')
234        a = {}
235        a[0] = a
236        self.assertEqual(ascii(a), '{0: {...}}')
237        # Advanced checks for unicode strings
238        def _check_uni(s):
239            self.assertEqual(ascii(s), repr(s))
240        _check_uni("'")
241        _check_uni('"')
242        _check_uni('"\'')
243        _check_uni('\0')
244        _check_uni('\r\n\t .')
245        # Unprintable non-ASCII characters
246        _check_uni('\x85')
247        _check_uni('\u1fff')
248        _check_uni('\U00012fff')
249        # Lone surrogates
250        _check_uni('\ud800')
251        _check_uni('\udfff')
252        # Issue #9804: surrogates should be joined even for printable
253        # wide characters (UCS-2 builds).
254        self.assertEqual(ascii('\U0001d121'), "'\\U0001d121'")
255        # All together
256        s = "'\0\"\n\r\t abcd\x85é\U00012fff\uD800\U0001D121xxx."
257        self.assertEqual(ascii(s),
258            r"""'\'\x00"\n\r\t abcd\x85\xe9\U00012fff\ud800\U0001d121xxx.'""")
259
260    def test_neg(self):
261        x = -sys.maxsize-1
262        self.assertTrue(isinstance(x, int))
263        self.assertEqual(-x, sys.maxsize+1)
264
265    def test_callable(self):
266        self.assertTrue(callable(len))
267        self.assertFalse(callable("a"))
268        self.assertTrue(callable(callable))
269        self.assertTrue(callable(lambda x, y: x + y))
270        self.assertFalse(callable(__builtins__))
271        def f(): pass
272        self.assertTrue(callable(f))
273
274        class C1:
275            def meth(self): pass
276        self.assertTrue(callable(C1))
277        c = C1()
278        self.assertTrue(callable(c.meth))
279        self.assertFalse(callable(c))
280
281        # __call__ is looked up on the class, not the instance
282        c.__call__ = None
283        self.assertFalse(callable(c))
284        c.__call__ = lambda self: 0
285        self.assertFalse(callable(c))
286        del c.__call__
287        self.assertFalse(callable(c))
288
289        class C2(object):
290            def __call__(self): pass
291        c2 = C2()
292        self.assertTrue(callable(c2))
293        c2.__call__ = None
294        self.assertTrue(callable(c2))
295        class C3(C2): pass
296        c3 = C3()
297        self.assertTrue(callable(c3))
298
299    def test_chr(self):
300        self.assertEqual(chr(32), ' ')
301        self.assertEqual(chr(65), 'A')
302        self.assertEqual(chr(97), 'a')
303        self.assertEqual(chr(0xff), '\xff')
304        self.assertRaises(ValueError, chr, 1<<24)
305        self.assertEqual(chr(sys.maxunicode),
306                         str('\\U0010ffff'.encode("ascii"), 'unicode-escape'))
307        self.assertRaises(TypeError, chr)
308        self.assertEqual(chr(0x0000FFFF), "\U0000FFFF")
309        self.assertEqual(chr(0x00010000), "\U00010000")
310        self.assertEqual(chr(0x00010001), "\U00010001")
311        self.assertEqual(chr(0x000FFFFE), "\U000FFFFE")
312        self.assertEqual(chr(0x000FFFFF), "\U000FFFFF")
313        self.assertEqual(chr(0x00100000), "\U00100000")
314        self.assertEqual(chr(0x00100001), "\U00100001")
315        self.assertEqual(chr(0x0010FFFE), "\U0010FFFE")
316        self.assertEqual(chr(0x0010FFFF), "\U0010FFFF")
317        self.assertRaises(ValueError, chr, -1)
318        self.assertRaises(ValueError, chr, 0x00110000)
319        self.assertRaises((OverflowError, ValueError), chr, 2**32)
320
321    def test_cmp(self):
322        self.assertTrue(not hasattr(builtins, "cmp"))
323
324    def test_compile(self):
325        compile('print(1)\n', '', 'exec')
326        bom = b'\xef\xbb\xbf'
327        compile(bom + b'print(1)\n', '', 'exec')
328        compile(source='pass', filename='?', mode='exec')
329        compile(dont_inherit=0, filename='tmp', source='0', mode='eval')
330        compile('pass', '?', dont_inherit=1, mode='exec')
331        compile(memoryview(b"text"), "name", "exec")
332        self.assertRaises(TypeError, compile)
333        self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'badmode')
334        self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'single', 0xff)
335        self.assertRaises(ValueError, compile, chr(0), 'f', 'exec')
336        self.assertRaises(TypeError, compile, 'pass', '?', 'exec',
337                          mode='eval', source='0', filename='tmp')
338        compile('print("\xe5")\n', '', 'exec')
339        self.assertRaises(ValueError, compile, chr(0), 'f', 'exec')
340        self.assertRaises(ValueError, compile, str('a = 1'), 'f', 'bad')
341
342        # test the optimize argument
343
344        codestr = '''def f():
345        """doc"""
346        debug_enabled = False
347        if __debug__:
348            debug_enabled = True
349        try:
350            assert False
351        except AssertionError:
352            return (True, f.__doc__, debug_enabled, __debug__)
353        else:
354            return (False, f.__doc__, debug_enabled, __debug__)
355        '''
356        def f(): """doc"""
357        values = [(-1, __debug__, f.__doc__, __debug__, __debug__),
358                  (0, True, 'doc', True, True),
359                  (1, False, 'doc', False, False),
360                  (2, False, None, False, False)]
361        for optval, *expected in values:
362            # test both direct compilation and compilation via AST
363            codeobjs = []
364            codeobjs.append(compile(codestr, "<test>", "exec", optimize=optval))
365            tree = ast.parse(codestr)
366            codeobjs.append(compile(tree, "<test>", "exec", optimize=optval))
367            for code in codeobjs:
368                ns = {}
369                exec(code, ns)
370                rv = ns['f']()
371                self.assertEqual(rv, tuple(expected))
372
373    def test_compile_top_level_await(self):
374        """Test whether code some top level await can be compiled.
375
376        Make sure it compiles only with the PyCF_ALLOW_TOP_LEVEL_AWAIT flag
377        set, and make sure the generated code object has the CO_COROUTINE flag
378        set in order to execute it with  `await eval(.....)` instead of exec,
379        or via a FunctionType.
380        """
381
382        # helper function just to check we can run top=level async-for
383        async def arange(n):
384            for i in range(n):
385                yield i
386
387        modes = ('single', 'exec')
388        code_samples = [
389            '''a = await asyncio.sleep(0, result=1)''',
390            '''async for i in arange(1):
391                   a = 1''',
392            '''async with asyncio.Lock() as l:
393                   a = 1'''
394        ]
395        policy = maybe_get_event_loop_policy()
396        try:
397            for mode, code_sample in product(modes, code_samples):
398                source = dedent(code_sample)
399                with self.assertRaises(
400                        SyntaxError, msg=f"source={source} mode={mode}"):
401                    compile(source, '?', mode)
402
403                co = compile(source,
404                             '?',
405                             mode,
406                             flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)
407
408                self.assertEqual(co.co_flags & CO_COROUTINE, CO_COROUTINE,
409                                 msg=f"source={source} mode={mode}")
410
411                # test we can create and  advance a function type
412                globals_ = {'asyncio': asyncio, 'a': 0, 'arange': arange}
413                async_f = FunctionType(co, globals_)
414                asyncio.run(async_f())
415                self.assertEqual(globals_['a'], 1)
416
417                # test we can await-eval,
418                globals_ = {'asyncio': asyncio, 'a': 0, 'arange': arange}
419                asyncio.run(eval(co, globals_))
420                self.assertEqual(globals_['a'], 1)
421        finally:
422            asyncio.set_event_loop_policy(policy)
423
424    def test_compile_async_generator(self):
425        """
426        With the PyCF_ALLOW_TOP_LEVEL_AWAIT flag added in 3.8, we want to
427        make sure AsyncGenerators are still properly not marked with the
428        CO_COROUTINE flag.
429        """
430        code = dedent("""async def ticker():
431                for i in range(10):
432                    yield i
433                    await asyncio.sleep(0)""")
434
435        co = compile(code, '?', 'exec', flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)
436        glob = {}
437        exec(co, glob)
438        self.assertEqual(type(glob['ticker']()), AsyncGeneratorType)
439
440    def test_delattr(self):
441        sys.spam = 1
442        delattr(sys, 'spam')
443        self.assertRaises(TypeError, delattr)
444
445    def test_dir(self):
446        # dir(wrong number of arguments)
447        self.assertRaises(TypeError, dir, 42, 42)
448
449        # dir() - local scope
450        local_var = 1
451        self.assertIn('local_var', dir())
452
453        # dir(module)
454        self.assertIn('exit', dir(sys))
455
456        # dir(module_with_invalid__dict__)
457        class Foo(types.ModuleType):
458            __dict__ = 8
459        f = Foo("foo")
460        self.assertRaises(TypeError, dir, f)
461
462        # dir(type)
463        self.assertIn("strip", dir(str))
464        self.assertNotIn("__mro__", dir(str))
465
466        # dir(obj)
467        class Foo(object):
468            def __init__(self):
469                self.x = 7
470                self.y = 8
471                self.z = 9
472        f = Foo()
473        self.assertIn("y", dir(f))
474
475        # dir(obj_no__dict__)
476        class Foo(object):
477            __slots__ = []
478        f = Foo()
479        self.assertIn("__repr__", dir(f))
480
481        # dir(obj_no__class__with__dict__)
482        # (an ugly trick to cause getattr(f, "__class__") to fail)
483        class Foo(object):
484            __slots__ = ["__class__", "__dict__"]
485            def __init__(self):
486                self.bar = "wow"
487        f = Foo()
488        self.assertNotIn("__repr__", dir(f))
489        self.assertIn("bar", dir(f))
490
491        # dir(obj_using __dir__)
492        class Foo(object):
493            def __dir__(self):
494                return ["kan", "ga", "roo"]
495        f = Foo()
496        self.assertTrue(dir(f) == ["ga", "kan", "roo"])
497
498        # dir(obj__dir__tuple)
499        class Foo(object):
500            def __dir__(self):
501                return ("b", "c", "a")
502        res = dir(Foo())
503        self.assertIsInstance(res, list)
504        self.assertTrue(res == ["a", "b", "c"])
505
506        # dir(obj__dir__not_sequence)
507        class Foo(object):
508            def __dir__(self):
509                return 7
510        f = Foo()
511        self.assertRaises(TypeError, dir, f)
512
513        # dir(traceback)
514        try:
515            raise IndexError
516        except:
517            self.assertEqual(len(dir(sys.exc_info()[2])), 4)
518
519        # test that object has a __dir__()
520        self.assertEqual(sorted([].__dir__()), dir([]))
521
522    def test_divmod(self):
523        self.assertEqual(divmod(12, 7), (1, 5))
524        self.assertEqual(divmod(-12, 7), (-2, 2))
525        self.assertEqual(divmod(12, -7), (-2, -2))
526        self.assertEqual(divmod(-12, -7), (1, -5))
527
528        self.assertEqual(divmod(-sys.maxsize-1, -1), (sys.maxsize+1, 0))
529
530        for num, denom, exp_result in [ (3.25, 1.0, (3.0, 0.25)),
531                                        (-3.25, 1.0, (-4.0, 0.75)),
532                                        (3.25, -1.0, (-4.0, -0.75)),
533                                        (-3.25, -1.0, (3.0, -0.25))]:
534            result = divmod(num, denom)
535            self.assertAlmostEqual(result[0], exp_result[0])
536            self.assertAlmostEqual(result[1], exp_result[1])
537
538        self.assertRaises(TypeError, divmod)
539
540    def test_eval(self):
541        self.assertEqual(eval('1+1'), 2)
542        self.assertEqual(eval(' 1+1\n'), 2)
543        globals = {'a': 1, 'b': 2}
544        locals = {'b': 200, 'c': 300}
545        self.assertEqual(eval('a', globals) , 1)
546        self.assertEqual(eval('a', globals, locals), 1)
547        self.assertEqual(eval('b', globals, locals), 200)
548        self.assertEqual(eval('c', globals, locals), 300)
549        globals = {'a': 1, 'b': 2}
550        locals = {'b': 200, 'c': 300}
551        bom = b'\xef\xbb\xbf'
552        self.assertEqual(eval(bom + b'a', globals, locals), 1)
553        self.assertEqual(eval('"\xe5"', globals), "\xe5")
554        self.assertRaises(TypeError, eval)
555        self.assertRaises(TypeError, eval, ())
556        self.assertRaises(SyntaxError, eval, bom[:2] + b'a')
557
558        class X:
559            def __getitem__(self, key):
560                raise ValueError
561        self.assertRaises(ValueError, eval, "foo", {}, X())
562
563    def test_general_eval(self):
564        # Tests that general mappings can be used for the locals argument
565
566        class M:
567            "Test mapping interface versus possible calls from eval()."
568            def __getitem__(self, key):
569                if key == 'a':
570                    return 12
571                raise KeyError
572            def keys(self):
573                return list('xyz')
574
575        m = M()
576        g = globals()
577        self.assertEqual(eval('a', g, m), 12)
578        self.assertRaises(NameError, eval, 'b', g, m)
579        self.assertEqual(eval('dir()', g, m), list('xyz'))
580        self.assertEqual(eval('globals()', g, m), g)
581        self.assertEqual(eval('locals()', g, m), m)
582        self.assertRaises(TypeError, eval, 'a', m)
583        class A:
584            "Non-mapping"
585            pass
586        m = A()
587        self.assertRaises(TypeError, eval, 'a', g, m)
588
589        # Verify that dict subclasses work as well
590        class D(dict):
591            def __getitem__(self, key):
592                if key == 'a':
593                    return 12
594                return dict.__getitem__(self, key)
595            def keys(self):
596                return list('xyz')
597
598        d = D()
599        self.assertEqual(eval('a', g, d), 12)
600        self.assertRaises(NameError, eval, 'b', g, d)
601        self.assertEqual(eval('dir()', g, d), list('xyz'))
602        self.assertEqual(eval('globals()', g, d), g)
603        self.assertEqual(eval('locals()', g, d), d)
604
605        # Verify locals stores (used by list comps)
606        eval('[locals() for i in (2,3)]', g, d)
607        eval('[locals() for i in (2,3)]', g, collections.UserDict())
608
609        class SpreadSheet:
610            "Sample application showing nested, calculated lookups."
611            _cells = {}
612            def __setitem__(self, key, formula):
613                self._cells[key] = formula
614            def __getitem__(self, key):
615                return eval(self._cells[key], globals(), self)
616
617        ss = SpreadSheet()
618        ss['a1'] = '5'
619        ss['a2'] = 'a1*6'
620        ss['a3'] = 'a2*7'
621        self.assertEqual(ss['a3'], 210)
622
623        # Verify that dir() catches a non-list returned by eval
624        # SF bug #1004669
625        class C:
626            def __getitem__(self, item):
627                raise KeyError(item)
628            def keys(self):
629                return 1 # used to be 'a' but that's no longer an error
630        self.assertRaises(TypeError, eval, 'dir()', globals(), C())
631
632    def test_exec(self):
633        g = {}
634        exec('z = 1', g)
635        if '__builtins__' in g:
636            del g['__builtins__']
637        self.assertEqual(g, {'z': 1})
638
639        exec('z = 1+1', g)
640        if '__builtins__' in g:
641            del g['__builtins__']
642        self.assertEqual(g, {'z': 2})
643        g = {}
644        l = {}
645
646        with check_warnings():
647            warnings.filterwarnings("ignore", "global statement",
648                    module="<string>")
649            exec('global a; a = 1; b = 2', g, l)
650        if '__builtins__' in g:
651            del g['__builtins__']
652        if '__builtins__' in l:
653            del l['__builtins__']
654        self.assertEqual((g, l), ({'a': 1}, {'b': 2}))
655
656    def test_exec_globals(self):
657        code = compile("print('Hello World!')", "", "exec")
658        # no builtin function
659        self.assertRaisesRegex(NameError, "name 'print' is not defined",
660                               exec, code, {'__builtins__': {}})
661        # __builtins__ must be a mapping type
662        self.assertRaises(TypeError,
663                          exec, code, {'__builtins__': 123})
664
665        # no __build_class__ function
666        code = compile("class A: pass", "", "exec")
667        self.assertRaisesRegex(NameError, "__build_class__ not found",
668                               exec, code, {'__builtins__': {}})
669
670        class frozendict_error(Exception):
671            pass
672
673        class frozendict(dict):
674            def __setitem__(self, key, value):
675                raise frozendict_error("frozendict is readonly")
676
677        # read-only builtins
678        if isinstance(__builtins__, types.ModuleType):
679            frozen_builtins = frozendict(__builtins__.__dict__)
680        else:
681            frozen_builtins = frozendict(__builtins__)
682        code = compile("__builtins__['superglobal']=2; print(superglobal)", "test", "exec")
683        self.assertRaises(frozendict_error,
684                          exec, code, {'__builtins__': frozen_builtins})
685
686        # read-only globals
687        namespace = frozendict({})
688        code = compile("x=1", "test", "exec")
689        self.assertRaises(frozendict_error,
690                          exec, code, namespace)
691
692    def test_exec_redirected(self):
693        savestdout = sys.stdout
694        sys.stdout = None # Whatever that cannot flush()
695        try:
696            # Used to raise SystemError('error return without exception set')
697            exec('a')
698        except NameError:
699            pass
700        finally:
701            sys.stdout = savestdout
702
703    def test_filter(self):
704        self.assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld'))
705        self.assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9])
706        self.assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2])
707        self.assertEqual(list(filter(None, Squares(10))), [1, 4, 9, 16, 25, 36, 49, 64, 81])
708        self.assertEqual(list(filter(lambda x: x%2, Squares(10))), [1, 9, 25, 49, 81])
709        def identity(item):
710            return 1
711        filter(identity, Squares(5))
712        self.assertRaises(TypeError, filter)
713        class BadSeq(object):
714            def __getitem__(self, index):
715                if index<4:
716                    return 42
717                raise ValueError
718        self.assertRaises(ValueError, list, filter(lambda x: x, BadSeq()))
719        def badfunc():
720            pass
721        self.assertRaises(TypeError, list, filter(badfunc, range(5)))
722
723        # test bltinmodule.c::filtertuple()
724        self.assertEqual(list(filter(None, (1, 2))), [1, 2])
725        self.assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4])
726        self.assertRaises(TypeError, list, filter(42, (1, 2)))
727
728    def test_filter_pickle(self):
729        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
730            f1 = filter(filter_char, "abcdeabcde")
731            f2 = filter(filter_char, "abcdeabcde")
732            self.check_iter_pickle(f1, list(f2), proto)
733
734    def test_getattr(self):
735        self.assertTrue(getattr(sys, 'stdout') is sys.stdout)
736        self.assertRaises(TypeError, getattr, sys, 1)
737        self.assertRaises(TypeError, getattr, sys, 1, "foo")
738        self.assertRaises(TypeError, getattr)
739        self.assertRaises(AttributeError, getattr, sys, chr(sys.maxunicode))
740        # unicode surrogates are not encodable to the default encoding (utf8)
741        self.assertRaises(AttributeError, getattr, 1, "\uDAD1\uD51E")
742
743    def test_hasattr(self):
744        self.assertTrue(hasattr(sys, 'stdout'))
745        self.assertRaises(TypeError, hasattr, sys, 1)
746        self.assertRaises(TypeError, hasattr)
747        self.assertEqual(False, hasattr(sys, chr(sys.maxunicode)))
748
749        # Check that hasattr propagates all exceptions outside of
750        # AttributeError.
751        class A:
752            def __getattr__(self, what):
753                raise SystemExit
754        self.assertRaises(SystemExit, hasattr, A(), "b")
755        class B:
756            def __getattr__(self, what):
757                raise ValueError
758        self.assertRaises(ValueError, hasattr, B(), "b")
759
760    def test_hash(self):
761        hash(None)
762        self.assertEqual(hash(1), hash(1))
763        self.assertEqual(hash(1), hash(1.0))
764        hash('spam')
765        self.assertEqual(hash('spam'), hash(b'spam'))
766        hash((0,1,2,3))
767        def f(): pass
768        self.assertRaises(TypeError, hash, [])
769        self.assertRaises(TypeError, hash, {})
770        # Bug 1536021: Allow hash to return long objects
771        class X:
772            def __hash__(self):
773                return 2**100
774        self.assertEqual(type(hash(X())), int)
775        class Z(int):
776            def __hash__(self):
777                return self
778        self.assertEqual(hash(Z(42)), hash(42))
779
780    def test_hex(self):
781        self.assertEqual(hex(16), '0x10')
782        self.assertEqual(hex(-16), '-0x10')
783        self.assertRaises(TypeError, hex, {})
784
785    def test_id(self):
786        id(None)
787        id(1)
788        id(1.0)
789        id('spam')
790        id((0,1,2,3))
791        id([0,1,2,3])
792        id({'spam': 1, 'eggs': 2, 'ham': 3})
793
794    # Test input() later, alphabetized as if it were raw_input
795
796    def test_iter(self):
797        self.assertRaises(TypeError, iter)
798        self.assertRaises(TypeError, iter, 42, 42)
799        lists = [("1", "2"), ["1", "2"], "12"]
800        for l in lists:
801            i = iter(l)
802            self.assertEqual(next(i), '1')
803            self.assertEqual(next(i), '2')
804            self.assertRaises(StopIteration, next, i)
805
806    def test_isinstance(self):
807        class C:
808            pass
809        class D(C):
810            pass
811        class E:
812            pass
813        c = C()
814        d = D()
815        e = E()
816        self.assertTrue(isinstance(c, C))
817        self.assertTrue(isinstance(d, C))
818        self.assertTrue(not isinstance(e, C))
819        self.assertTrue(not isinstance(c, D))
820        self.assertTrue(not isinstance('foo', E))
821        self.assertRaises(TypeError, isinstance, E, 'foo')
822        self.assertRaises(TypeError, isinstance)
823
824    def test_issubclass(self):
825        class C:
826            pass
827        class D(C):
828            pass
829        class E:
830            pass
831        c = C()
832        d = D()
833        e = E()
834        self.assertTrue(issubclass(D, C))
835        self.assertTrue(issubclass(C, C))
836        self.assertTrue(not issubclass(C, D))
837        self.assertRaises(TypeError, issubclass, 'foo', E)
838        self.assertRaises(TypeError, issubclass, E, 'foo')
839        self.assertRaises(TypeError, issubclass)
840
841    def test_len(self):
842        self.assertEqual(len('123'), 3)
843        self.assertEqual(len(()), 0)
844        self.assertEqual(len((1, 2, 3, 4)), 4)
845        self.assertEqual(len([1, 2, 3, 4]), 4)
846        self.assertEqual(len({}), 0)
847        self.assertEqual(len({'a':1, 'b': 2}), 2)
848        class BadSeq:
849            def __len__(self):
850                raise ValueError
851        self.assertRaises(ValueError, len, BadSeq())
852        class InvalidLen:
853            def __len__(self):
854                return None
855        self.assertRaises(TypeError, len, InvalidLen())
856        class FloatLen:
857            def __len__(self):
858                return 4.5
859        self.assertRaises(TypeError, len, FloatLen())
860        class NegativeLen:
861            def __len__(self):
862                return -10
863        self.assertRaises(ValueError, len, NegativeLen())
864        class HugeLen:
865            def __len__(self):
866                return sys.maxsize + 1
867        self.assertRaises(OverflowError, len, HugeLen())
868        class HugeNegativeLen:
869            def __len__(self):
870                return -sys.maxsize-10
871        self.assertRaises(ValueError, len, HugeNegativeLen())
872        class NoLenMethod(object): pass
873        self.assertRaises(TypeError, len, NoLenMethod())
874
875    def test_map(self):
876        self.assertEqual(
877            list(map(lambda x: x*x, range(1,4))),
878            [1, 4, 9]
879        )
880        try:
881            from math import sqrt
882        except ImportError:
883            def sqrt(x):
884                return pow(x, 0.5)
885        self.assertEqual(
886            list(map(lambda x: list(map(sqrt, x)), [[16, 4], [81, 9]])),
887            [[4.0, 2.0], [9.0, 3.0]]
888        )
889        self.assertEqual(
890            list(map(lambda x, y: x+y, [1,3,2], [9,1,4])),
891            [10, 4, 6]
892        )
893
894        def plus(*v):
895            accu = 0
896            for i in v: accu = accu + i
897            return accu
898        self.assertEqual(
899            list(map(plus, [1, 3, 7])),
900            [1, 3, 7]
901        )
902        self.assertEqual(
903            list(map(plus, [1, 3, 7], [4, 9, 2])),
904            [1+4, 3+9, 7+2]
905        )
906        self.assertEqual(
907            list(map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])),
908            [1+4+1, 3+9+1, 7+2+0]
909        )
910        self.assertEqual(
911            list(map(int, Squares(10))),
912            [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
913        )
914        def Max(a, b):
915            if a is None:
916                return b
917            if b is None:
918                return a
919            return max(a, b)
920        self.assertEqual(
921            list(map(Max, Squares(3), Squares(2))),
922            [0, 1]
923        )
924        self.assertRaises(TypeError, map)
925        self.assertRaises(TypeError, map, lambda x: x, 42)
926        class BadSeq:
927            def __iter__(self):
928                raise ValueError
929                yield None
930        self.assertRaises(ValueError, list, map(lambda x: x, BadSeq()))
931        def badfunc(x):
932            raise RuntimeError
933        self.assertRaises(RuntimeError, list, map(badfunc, range(5)))
934
935    def test_map_pickle(self):
936        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
937            m1 = map(map_char, "Is this the real life?")
938            m2 = map(map_char, "Is this the real life?")
939            self.check_iter_pickle(m1, list(m2), proto)
940
941    def test_max(self):
942        self.assertEqual(max('123123'), '3')
943        self.assertEqual(max(1, 2, 3), 3)
944        self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)
945        self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)
946
947        self.assertEqual(max(1, 2, 3.0), 3.0)
948        self.assertEqual(max(1, 2.0, 3), 3)
949        self.assertEqual(max(1.0, 2, 3), 3)
950
951        self.assertRaises(TypeError, max)
952        self.assertRaises(TypeError, max, 42)
953        self.assertRaises(ValueError, max, ())
954        class BadSeq:
955            def __getitem__(self, index):
956                raise ValueError
957        self.assertRaises(ValueError, max, BadSeq())
958
959        for stmt in (
960            "max(key=int)",                 # no args
961            "max(default=None)",
962            "max(1, 2, default=None)",      # require container for default
963            "max(default=None, key=int)",
964            "max(1, key=int)",              # single arg not iterable
965            "max(1, 2, keystone=int)",      # wrong keyword
966            "max(1, 2, key=int, abc=int)",  # two many keywords
967            "max(1, 2, key=1)",             # keyfunc is not callable
968            ):
969            try:
970                exec(stmt, globals())
971            except TypeError:
972                pass
973            else:
974                self.fail(stmt)
975
976        self.assertEqual(max((1,), key=neg), 1)     # one elem iterable
977        self.assertEqual(max((1,2), key=neg), 1)    # two elem iterable
978        self.assertEqual(max(1, 2, key=neg), 1)     # two elems
979
980        self.assertEqual(max((), default=None), None)    # zero elem iterable
981        self.assertEqual(max((1,), default=None), 1)     # one elem iterable
982        self.assertEqual(max((1,2), default=None), 2)    # two elem iterable
983
984        self.assertEqual(max((), default=1, key=neg), 1)
985        self.assertEqual(max((1, 2), default=3, key=neg), 1)
986
987        self.assertEqual(max((1, 2), key=None), 2)
988
989        data = [random.randrange(200) for i in range(100)]
990        keys = dict((elem, random.randrange(50)) for elem in data)
991        f = keys.__getitem__
992        self.assertEqual(max(data, key=f),
993                         sorted(reversed(data), key=f)[-1])
994
995    def test_min(self):
996        self.assertEqual(min('123123'), '1')
997        self.assertEqual(min(1, 2, 3), 1)
998        self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1)
999        self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1)
1000
1001        self.assertEqual(min(1, 2, 3.0), 1)
1002        self.assertEqual(min(1, 2.0, 3), 1)
1003        self.assertEqual(min(1.0, 2, 3), 1.0)
1004
1005        self.assertRaises(TypeError, min)
1006        self.assertRaises(TypeError, min, 42)
1007        self.assertRaises(ValueError, min, ())
1008        class BadSeq:
1009            def __getitem__(self, index):
1010                raise ValueError
1011        self.assertRaises(ValueError, min, BadSeq())
1012
1013        for stmt in (
1014            "min(key=int)",                 # no args
1015            "min(default=None)",
1016            "min(1, 2, default=None)",      # require container for default
1017            "min(default=None, key=int)",
1018            "min(1, key=int)",              # single arg not iterable
1019            "min(1, 2, keystone=int)",      # wrong keyword
1020            "min(1, 2, key=int, abc=int)",  # two many keywords
1021            "min(1, 2, key=1)",             # keyfunc is not callable
1022            ):
1023            try:
1024                exec(stmt, globals())
1025            except TypeError:
1026                pass
1027            else:
1028                self.fail(stmt)
1029
1030        self.assertEqual(min((1,), key=neg), 1)     # one elem iterable
1031        self.assertEqual(min((1,2), key=neg), 2)    # two elem iterable
1032        self.assertEqual(min(1, 2, key=neg), 2)     # two elems
1033
1034        self.assertEqual(min((), default=None), None)    # zero elem iterable
1035        self.assertEqual(min((1,), default=None), 1)     # one elem iterable
1036        self.assertEqual(min((1,2), default=None), 1)    # two elem iterable
1037
1038        self.assertEqual(min((), default=1, key=neg), 1)
1039        self.assertEqual(min((1, 2), default=1, key=neg), 2)
1040
1041        self.assertEqual(min((1, 2), key=None), 1)
1042
1043        data = [random.randrange(200) for i in range(100)]
1044        keys = dict((elem, random.randrange(50)) for elem in data)
1045        f = keys.__getitem__
1046        self.assertEqual(min(data, key=f),
1047                         sorted(data, key=f)[0])
1048
1049    def test_next(self):
1050        it = iter(range(2))
1051        self.assertEqual(next(it), 0)
1052        self.assertEqual(next(it), 1)
1053        self.assertRaises(StopIteration, next, it)
1054        self.assertRaises(StopIteration, next, it)
1055        self.assertEqual(next(it, 42), 42)
1056
1057        class Iter(object):
1058            def __iter__(self):
1059                return self
1060            def __next__(self):
1061                raise StopIteration
1062
1063        it = iter(Iter())
1064        self.assertEqual(next(it, 42), 42)
1065        self.assertRaises(StopIteration, next, it)
1066
1067        def gen():
1068            yield 1
1069            return
1070
1071        it = gen()
1072        self.assertEqual(next(it), 1)
1073        self.assertRaises(StopIteration, next, it)
1074        self.assertEqual(next(it, 42), 42)
1075
1076    def test_oct(self):
1077        self.assertEqual(oct(100), '0o144')
1078        self.assertEqual(oct(-100), '-0o144')
1079        self.assertRaises(TypeError, oct, ())
1080
1081    def write_testfile(self):
1082        # NB the first 4 lines are also used to test input, below
1083        fp = open(TESTFN, 'w')
1084        self.addCleanup(unlink, TESTFN)
1085        with fp:
1086            fp.write('1+1\n')
1087            fp.write('The quick brown fox jumps over the lazy dog')
1088            fp.write('.\n')
1089            fp.write('Dear John\n')
1090            fp.write('XXX'*100)
1091            fp.write('YYY'*100)
1092
1093    def test_open(self):
1094        self.write_testfile()
1095        fp = open(TESTFN, 'r')
1096        with fp:
1097            self.assertEqual(fp.readline(4), '1+1\n')
1098            self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n')
1099            self.assertEqual(fp.readline(4), 'Dear')
1100            self.assertEqual(fp.readline(100), ' John\n')
1101            self.assertEqual(fp.read(300), 'XXX'*100)
1102            self.assertEqual(fp.read(1000), 'YYY'*100)
1103
1104        # embedded null bytes and characters
1105        self.assertRaises(ValueError, open, 'a\x00b')
1106        self.assertRaises(ValueError, open, b'a\x00b')
1107
1108    @unittest.skipIf(sys.flags.utf8_mode, "utf-8 mode is enabled")
1109    def test_open_default_encoding(self):
1110        old_environ = dict(os.environ)
1111        try:
1112            # try to get a user preferred encoding different than the current
1113            # locale encoding to check that open() uses the current locale
1114            # encoding and not the user preferred encoding
1115            for key in ('LC_ALL', 'LANG', 'LC_CTYPE'):
1116                if key in os.environ:
1117                    del os.environ[key]
1118
1119            self.write_testfile()
1120            current_locale_encoding = locale.getpreferredencoding(False)
1121            fp = open(TESTFN, 'w')
1122            with fp:
1123                self.assertEqual(fp.encoding, current_locale_encoding)
1124        finally:
1125            os.environ.clear()
1126            os.environ.update(old_environ)
1127
1128    def test_open_non_inheritable(self):
1129        fileobj = open(__file__)
1130        with fileobj:
1131            self.assertFalse(os.get_inheritable(fileobj.fileno()))
1132
1133    def test_ord(self):
1134        self.assertEqual(ord(' '), 32)
1135        self.assertEqual(ord('A'), 65)
1136        self.assertEqual(ord('a'), 97)
1137        self.assertEqual(ord('\x80'), 128)
1138        self.assertEqual(ord('\xff'), 255)
1139
1140        self.assertEqual(ord(b' '), 32)
1141        self.assertEqual(ord(b'A'), 65)
1142        self.assertEqual(ord(b'a'), 97)
1143        self.assertEqual(ord(b'\x80'), 128)
1144        self.assertEqual(ord(b'\xff'), 255)
1145
1146        self.assertEqual(ord(chr(sys.maxunicode)), sys.maxunicode)
1147        self.assertRaises(TypeError, ord, 42)
1148
1149        self.assertEqual(ord(chr(0x10FFFF)), 0x10FFFF)
1150        self.assertEqual(ord("\U0000FFFF"), 0x0000FFFF)
1151        self.assertEqual(ord("\U00010000"), 0x00010000)
1152        self.assertEqual(ord("\U00010001"), 0x00010001)
1153        self.assertEqual(ord("\U000FFFFE"), 0x000FFFFE)
1154        self.assertEqual(ord("\U000FFFFF"), 0x000FFFFF)
1155        self.assertEqual(ord("\U00100000"), 0x00100000)
1156        self.assertEqual(ord("\U00100001"), 0x00100001)
1157        self.assertEqual(ord("\U0010FFFE"), 0x0010FFFE)
1158        self.assertEqual(ord("\U0010FFFF"), 0x0010FFFF)
1159
1160    def test_pow(self):
1161        self.assertEqual(pow(0,0), 1)
1162        self.assertEqual(pow(0,1), 0)
1163        self.assertEqual(pow(1,0), 1)
1164        self.assertEqual(pow(1,1), 1)
1165
1166        self.assertEqual(pow(2,0), 1)
1167        self.assertEqual(pow(2,10), 1024)
1168        self.assertEqual(pow(2,20), 1024*1024)
1169        self.assertEqual(pow(2,30), 1024*1024*1024)
1170
1171        self.assertEqual(pow(-2,0), 1)
1172        self.assertEqual(pow(-2,1), -2)
1173        self.assertEqual(pow(-2,2), 4)
1174        self.assertEqual(pow(-2,3), -8)
1175
1176        self.assertAlmostEqual(pow(0.,0), 1.)
1177        self.assertAlmostEqual(pow(0.,1), 0.)
1178        self.assertAlmostEqual(pow(1.,0), 1.)
1179        self.assertAlmostEqual(pow(1.,1), 1.)
1180
1181        self.assertAlmostEqual(pow(2.,0), 1.)
1182        self.assertAlmostEqual(pow(2.,10), 1024.)
1183        self.assertAlmostEqual(pow(2.,20), 1024.*1024.)
1184        self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.)
1185
1186        self.assertAlmostEqual(pow(-2.,0), 1.)
1187        self.assertAlmostEqual(pow(-2.,1), -2.)
1188        self.assertAlmostEqual(pow(-2.,2), 4.)
1189        self.assertAlmostEqual(pow(-2.,3), -8.)
1190
1191        for x in 2, 2.0:
1192            for y in 10, 10.0:
1193                for z in 1000, 1000.0:
1194                    if isinstance(x, float) or \
1195                       isinstance(y, float) or \
1196                       isinstance(z, float):
1197                        self.assertRaises(TypeError, pow, x, y, z)
1198                    else:
1199                        self.assertAlmostEqual(pow(x, y, z), 24.0)
1200
1201        self.assertAlmostEqual(pow(-1, 0.5), 1j)
1202        self.assertAlmostEqual(pow(-1, 1/3), 0.5 + 0.8660254037844386j)
1203
1204        # See test_pow for additional tests for three-argument pow.
1205        self.assertEqual(pow(-1, -2, 3), 1)
1206        self.assertRaises(ValueError, pow, 1, 2, 0)
1207
1208        self.assertRaises(TypeError, pow)
1209
1210        # Test passing in arguments as keywords.
1211        self.assertEqual(pow(0, exp=0), 1)
1212        self.assertEqual(pow(base=2, exp=4), 16)
1213        self.assertEqual(pow(base=5, exp=2, mod=14), 11)
1214        twopow = partial(pow, base=2)
1215        self.assertEqual(twopow(exp=5), 32)
1216        fifth_power = partial(pow, exp=5)
1217        self.assertEqual(fifth_power(2), 32)
1218        mod10 = partial(pow, mod=10)
1219        self.assertEqual(mod10(2, 6), 4)
1220        self.assertEqual(mod10(exp=6, base=2), 4)
1221
1222    def test_input(self):
1223        self.write_testfile()
1224        fp = open(TESTFN, 'r')
1225        savestdin = sys.stdin
1226        savestdout = sys.stdout # Eats the echo
1227        try:
1228            sys.stdin = fp
1229            sys.stdout = BitBucket()
1230            self.assertEqual(input(), "1+1")
1231            self.assertEqual(input(), 'The quick brown fox jumps over the lazy dog.')
1232            self.assertEqual(input('testing\n'), 'Dear John')
1233
1234            # SF 1535165: don't segfault on closed stdin
1235            # sys.stdout must be a regular file for triggering
1236            sys.stdout = savestdout
1237            sys.stdin.close()
1238            self.assertRaises(ValueError, input)
1239
1240            sys.stdout = BitBucket()
1241            sys.stdin = io.StringIO("NULL\0")
1242            self.assertRaises(TypeError, input, 42, 42)
1243            sys.stdin = io.StringIO("    'whitespace'")
1244            self.assertEqual(input(), "    'whitespace'")
1245            sys.stdin = io.StringIO()
1246            self.assertRaises(EOFError, input)
1247
1248            del sys.stdout
1249            self.assertRaises(RuntimeError, input, 'prompt')
1250            del sys.stdin
1251            self.assertRaises(RuntimeError, input, 'prompt')
1252        finally:
1253            sys.stdin = savestdin
1254            sys.stdout = savestdout
1255            fp.close()
1256
1257    # test_int(): see test_int.py for tests of built-in function int().
1258
1259    def test_repr(self):
1260        self.assertEqual(repr(''), '\'\'')
1261        self.assertEqual(repr(0), '0')
1262        self.assertEqual(repr(()), '()')
1263        self.assertEqual(repr([]), '[]')
1264        self.assertEqual(repr({}), '{}')
1265        a = []
1266        a.append(a)
1267        self.assertEqual(repr(a), '[[...]]')
1268        a = {}
1269        a[0] = a
1270        self.assertEqual(repr(a), '{0: {...}}')
1271
1272    def test_round(self):
1273        self.assertEqual(round(0.0), 0.0)
1274        self.assertEqual(type(round(0.0)), int)
1275        self.assertEqual(round(1.0), 1.0)
1276        self.assertEqual(round(10.0), 10.0)
1277        self.assertEqual(round(1000000000.0), 1000000000.0)
1278        self.assertEqual(round(1e20), 1e20)
1279
1280        self.assertEqual(round(-1.0), -1.0)
1281        self.assertEqual(round(-10.0), -10.0)
1282        self.assertEqual(round(-1000000000.0), -1000000000.0)
1283        self.assertEqual(round(-1e20), -1e20)
1284
1285        self.assertEqual(round(0.1), 0.0)
1286        self.assertEqual(round(1.1), 1.0)
1287        self.assertEqual(round(10.1), 10.0)
1288        self.assertEqual(round(1000000000.1), 1000000000.0)
1289
1290        self.assertEqual(round(-1.1), -1.0)
1291        self.assertEqual(round(-10.1), -10.0)
1292        self.assertEqual(round(-1000000000.1), -1000000000.0)
1293
1294        self.assertEqual(round(0.9), 1.0)
1295        self.assertEqual(round(9.9), 10.0)
1296        self.assertEqual(round(999999999.9), 1000000000.0)
1297
1298        self.assertEqual(round(-0.9), -1.0)
1299        self.assertEqual(round(-9.9), -10.0)
1300        self.assertEqual(round(-999999999.9), -1000000000.0)
1301
1302        self.assertEqual(round(-8.0, -1), -10.0)
1303        self.assertEqual(type(round(-8.0, -1)), float)
1304
1305        self.assertEqual(type(round(-8.0, 0)), float)
1306        self.assertEqual(type(round(-8.0, 1)), float)
1307
1308        # Check even / odd rounding behaviour
1309        self.assertEqual(round(5.5), 6)
1310        self.assertEqual(round(6.5), 6)
1311        self.assertEqual(round(-5.5), -6)
1312        self.assertEqual(round(-6.5), -6)
1313
1314        # Check behavior on ints
1315        self.assertEqual(round(0), 0)
1316        self.assertEqual(round(8), 8)
1317        self.assertEqual(round(-8), -8)
1318        self.assertEqual(type(round(0)), int)
1319        self.assertEqual(type(round(-8, -1)), int)
1320        self.assertEqual(type(round(-8, 0)), int)
1321        self.assertEqual(type(round(-8, 1)), int)
1322
1323        # test new kwargs
1324        self.assertEqual(round(number=-8.0, ndigits=-1), -10.0)
1325
1326        self.assertRaises(TypeError, round)
1327
1328        # test generic rounding delegation for reals
1329        class TestRound:
1330            def __round__(self):
1331                return 23
1332
1333        class TestNoRound:
1334            pass
1335
1336        self.assertEqual(round(TestRound()), 23)
1337
1338        self.assertRaises(TypeError, round, 1, 2, 3)
1339        self.assertRaises(TypeError, round, TestNoRound())
1340
1341        t = TestNoRound()
1342        t.__round__ = lambda *args: args
1343        self.assertRaises(TypeError, round, t)
1344        self.assertRaises(TypeError, round, t, 0)
1345
1346    # Some versions of glibc for alpha have a bug that affects
1347    # float -> integer rounding (floor, ceil, rint, round) for
1348    # values in the range [2**52, 2**53).  See:
1349    #
1350    #   http://sources.redhat.com/bugzilla/show_bug.cgi?id=5350
1351    #
1352    # We skip this test on Linux/alpha if it would fail.
1353    linux_alpha = (platform.system().startswith('Linux') and
1354                   platform.machine().startswith('alpha'))
1355    system_round_bug = round(5e15+1) != 5e15+1
1356    @unittest.skipIf(linux_alpha and system_round_bug,
1357                     "test will fail;  failure is probably due to a "
1358                     "buggy system round function")
1359    def test_round_large(self):
1360        # Issue #1869: integral floats should remain unchanged
1361        self.assertEqual(round(5e15-1), 5e15-1)
1362        self.assertEqual(round(5e15), 5e15)
1363        self.assertEqual(round(5e15+1), 5e15+1)
1364        self.assertEqual(round(5e15+2), 5e15+2)
1365        self.assertEqual(round(5e15+3), 5e15+3)
1366
1367    def test_bug_27936(self):
1368        # Verify that ndigits=None means the same as passing in no argument
1369        for x in [1234,
1370                  1234.56,
1371                  decimal.Decimal('1234.56'),
1372                  fractions.Fraction(123456, 100)]:
1373            self.assertEqual(round(x, None), round(x))
1374            self.assertEqual(type(round(x, None)), type(round(x)))
1375
1376    def test_setattr(self):
1377        setattr(sys, 'spam', 1)
1378        self.assertEqual(sys.spam, 1)
1379        self.assertRaises(TypeError, setattr, sys, 1, 'spam')
1380        self.assertRaises(TypeError, setattr)
1381
1382    # test_str(): see test_unicode.py and test_bytes.py for str() tests.
1383
1384    def test_sum(self):
1385        self.assertEqual(sum([]), 0)
1386        self.assertEqual(sum(list(range(2,8))), 27)
1387        self.assertEqual(sum(iter(list(range(2,8)))), 27)
1388        self.assertEqual(sum(Squares(10)), 285)
1389        self.assertEqual(sum(iter(Squares(10))), 285)
1390        self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])
1391
1392        self.assertEqual(sum(range(10), 1000), 1045)
1393        self.assertEqual(sum(range(10), start=1000), 1045)
1394
1395        self.assertRaises(TypeError, sum)
1396        self.assertRaises(TypeError, sum, 42)
1397        self.assertRaises(TypeError, sum, ['a', 'b', 'c'])
1398        self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '')
1399        self.assertRaises(TypeError, sum, [b'a', b'c'], b'')
1400        values = [bytearray(b'a'), bytearray(b'b')]
1401        self.assertRaises(TypeError, sum, values, bytearray(b''))
1402        self.assertRaises(TypeError, sum, [[1], [2], [3]])
1403        self.assertRaises(TypeError, sum, [{2:3}])
1404        self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3})
1405
1406        class BadSeq:
1407            def __getitem__(self, index):
1408                raise ValueError
1409        self.assertRaises(ValueError, sum, BadSeq())
1410
1411        empty = []
1412        sum(([x] for x in range(10)), empty)
1413        self.assertEqual(empty, [])
1414
1415    def test_type(self):
1416        self.assertEqual(type(''),  type('123'))
1417        self.assertNotEqual(type(''), type(()))
1418
1419    # We don't want self in vars(), so these are static methods
1420
1421    @staticmethod
1422    def get_vars_f0():
1423        return vars()
1424
1425    @staticmethod
1426    def get_vars_f2():
1427        BuiltinTest.get_vars_f0()
1428        a = 1
1429        b = 2
1430        return vars()
1431
1432    class C_get_vars(object):
1433        def getDict(self):
1434            return {'a':2}
1435        __dict__ = property(fget=getDict)
1436
1437    def test_vars(self):
1438        self.assertEqual(set(vars()), set(dir()))
1439        self.assertEqual(set(vars(sys)), set(dir(sys)))
1440        self.assertEqual(self.get_vars_f0(), {})
1441        self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2})
1442        self.assertRaises(TypeError, vars, 42, 42)
1443        self.assertRaises(TypeError, vars, 42)
1444        self.assertEqual(vars(self.C_get_vars()), {'a':2})
1445
1446    def test_zip(self):
1447        a = (1, 2, 3)
1448        b = (4, 5, 6)
1449        t = [(1, 4), (2, 5), (3, 6)]
1450        self.assertEqual(list(zip(a, b)), t)
1451        b = [4, 5, 6]
1452        self.assertEqual(list(zip(a, b)), t)
1453        b = (4, 5, 6, 7)
1454        self.assertEqual(list(zip(a, b)), t)
1455        class I:
1456            def __getitem__(self, i):
1457                if i < 0 or i > 2: raise IndexError
1458                return i + 4
1459        self.assertEqual(list(zip(a, I())), t)
1460        self.assertEqual(list(zip()), [])
1461        self.assertEqual(list(zip(*[])), [])
1462        self.assertRaises(TypeError, zip, None)
1463        class G:
1464            pass
1465        self.assertRaises(TypeError, zip, a, G())
1466        self.assertRaises(RuntimeError, zip, a, TestFailingIter())
1467
1468        # Make sure zip doesn't try to allocate a billion elements for the
1469        # result list when one of its arguments doesn't say how long it is.
1470        # A MemoryError is the most likely failure mode.
1471        class SequenceWithoutALength:
1472            def __getitem__(self, i):
1473                if i == 5:
1474                    raise IndexError
1475                else:
1476                    return i
1477        self.assertEqual(
1478            list(zip(SequenceWithoutALength(), range(2**30))),
1479            list(enumerate(range(5)))
1480        )
1481
1482        class BadSeq:
1483            def __getitem__(self, i):
1484                if i == 5:
1485                    raise ValueError
1486                else:
1487                    return i
1488        self.assertRaises(ValueError, list, zip(BadSeq(), BadSeq()))
1489
1490    def test_zip_pickle(self):
1491        a = (1, 2, 3)
1492        b = (4, 5, 6)
1493        t = [(1, 4), (2, 5), (3, 6)]
1494        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1495            z1 = zip(a, b)
1496            self.check_iter_pickle(z1, t, proto)
1497
1498    def test_zip_bad_iterable(self):
1499        exception = TypeError()
1500
1501        class BadIterable:
1502            def __iter__(self):
1503                raise exception
1504
1505        with self.assertRaises(TypeError) as cm:
1506            zip(BadIterable())
1507
1508        self.assertIs(cm.exception, exception)
1509
1510    def test_format(self):
1511        # Test the basic machinery of the format() builtin.  Don't test
1512        #  the specifics of the various formatters
1513        self.assertEqual(format(3, ''), '3')
1514
1515        # Returns some classes to use for various tests.  There's
1516        #  an old-style version, and a new-style version
1517        def classes_new():
1518            class A(object):
1519                def __init__(self, x):
1520                    self.x = x
1521                def __format__(self, format_spec):
1522                    return str(self.x) + format_spec
1523            class DerivedFromA(A):
1524                pass
1525
1526            class Simple(object): pass
1527            class DerivedFromSimple(Simple):
1528                def __init__(self, x):
1529                    self.x = x
1530                def __format__(self, format_spec):
1531                    return str(self.x) + format_spec
1532            class DerivedFromSimple2(DerivedFromSimple): pass
1533            return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2
1534
1535        def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2):
1536            self.assertEqual(format(A(3), 'spec'), '3spec')
1537            self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec')
1538            self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc')
1539            self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'),
1540                             '10abcdef')
1541
1542        class_test(*classes_new())
1543
1544        def empty_format_spec(value):
1545            # test that:
1546            #  format(x, '') == str(x)
1547            #  format(x) == str(x)
1548            self.assertEqual(format(value, ""), str(value))
1549            self.assertEqual(format(value), str(value))
1550
1551        # for builtin types, format(x, "") == str(x)
1552        empty_format_spec(17**13)
1553        empty_format_spec(1.0)
1554        empty_format_spec(3.1415e104)
1555        empty_format_spec(-3.1415e104)
1556        empty_format_spec(3.1415e-104)
1557        empty_format_spec(-3.1415e-104)
1558        empty_format_spec(object)
1559        empty_format_spec(None)
1560
1561        # TypeError because self.__format__ returns the wrong type
1562        class BadFormatResult:
1563            def __format__(self, format_spec):
1564                return 1.0
1565        self.assertRaises(TypeError, format, BadFormatResult(), "")
1566
1567        # TypeError because format_spec is not unicode or str
1568        self.assertRaises(TypeError, format, object(), 4)
1569        self.assertRaises(TypeError, format, object(), object())
1570
1571        # tests for object.__format__ really belong elsewhere, but
1572        #  there's no good place to put them
1573        x = object().__format__('')
1574        self.assertTrue(x.startswith('<object object at'))
1575
1576        # first argument to object.__format__ must be string
1577        self.assertRaises(TypeError, object().__format__, 3)
1578        self.assertRaises(TypeError, object().__format__, object())
1579        self.assertRaises(TypeError, object().__format__, None)
1580
1581        # --------------------------------------------------------------------
1582        # Issue #7994: object.__format__ with a non-empty format string is
1583        # disallowed
1584        class A:
1585            def __format__(self, fmt_str):
1586                return format('', fmt_str)
1587
1588        self.assertEqual(format(A()), '')
1589        self.assertEqual(format(A(), ''), '')
1590        self.assertEqual(format(A(), 's'), '')
1591
1592        class B:
1593            pass
1594
1595        class C(object):
1596            pass
1597
1598        for cls in [object, B, C]:
1599            obj = cls()
1600            self.assertEqual(format(obj), str(obj))
1601            self.assertEqual(format(obj, ''), str(obj))
1602            with self.assertRaisesRegex(TypeError,
1603                                        r'\b%s\b' % re.escape(cls.__name__)):
1604                format(obj, 's')
1605        # --------------------------------------------------------------------
1606
1607        # make sure we can take a subclass of str as a format spec
1608        class DerivedFromStr(str): pass
1609        self.assertEqual(format(0, DerivedFromStr('10')), '         0')
1610
1611    def test_bin(self):
1612        self.assertEqual(bin(0), '0b0')
1613        self.assertEqual(bin(1), '0b1')
1614        self.assertEqual(bin(-1), '-0b1')
1615        self.assertEqual(bin(2**65), '0b1' + '0' * 65)
1616        self.assertEqual(bin(2**65-1), '0b' + '1' * 65)
1617        self.assertEqual(bin(-(2**65)), '-0b1' + '0' * 65)
1618        self.assertEqual(bin(-(2**65-1)), '-0b' + '1' * 65)
1619
1620    def test_bytearray_translate(self):
1621        x = bytearray(b"abc")
1622        self.assertRaises(ValueError, x.translate, b"1", 1)
1623        self.assertRaises(TypeError, x.translate, b"1"*256, 1)
1624
1625    def test_bytearray_extend_error(self):
1626        array = bytearray()
1627        bad_iter = map(int, "X")
1628        self.assertRaises(ValueError, array.extend, bad_iter)
1629
1630    def test_construct_singletons(self):
1631        for const in None, Ellipsis, NotImplemented:
1632            tp = type(const)
1633            self.assertIs(tp(), const)
1634            self.assertRaises(TypeError, tp, 1, 2)
1635            self.assertRaises(TypeError, tp, a=1, b=2)
1636
1637
1638class TestBreakpoint(unittest.TestCase):
1639    def setUp(self):
1640        # These tests require a clean slate environment.  For example, if the
1641        # test suite is run with $PYTHONBREAKPOINT set to something else, it
1642        # will mess up these tests.  Similarly for sys.breakpointhook.
1643        # Cleaning the slate here means you can't use breakpoint() to debug
1644        # these tests, but I think that's okay.  Just use pdb.set_trace() if
1645        # you must.
1646        self.resources = ExitStack()
1647        self.addCleanup(self.resources.close)
1648        self.env = self.resources.enter_context(EnvironmentVarGuard())
1649        del self.env['PYTHONBREAKPOINT']
1650        self.resources.enter_context(
1651            swap_attr(sys, 'breakpointhook', sys.__breakpointhook__))
1652
1653    def test_breakpoint(self):
1654        with patch('pdb.set_trace') as mock:
1655            breakpoint()
1656        mock.assert_called_once()
1657
1658    def test_breakpoint_with_breakpointhook_set(self):
1659        my_breakpointhook = MagicMock()
1660        sys.breakpointhook = my_breakpointhook
1661        breakpoint()
1662        my_breakpointhook.assert_called_once_with()
1663
1664    def test_breakpoint_with_breakpointhook_reset(self):
1665        my_breakpointhook = MagicMock()
1666        sys.breakpointhook = my_breakpointhook
1667        breakpoint()
1668        my_breakpointhook.assert_called_once_with()
1669        # Reset the hook and it will not be called again.
1670        sys.breakpointhook = sys.__breakpointhook__
1671        with patch('pdb.set_trace') as mock:
1672            breakpoint()
1673            mock.assert_called_once_with()
1674        my_breakpointhook.assert_called_once_with()
1675
1676    def test_breakpoint_with_args_and_keywords(self):
1677        my_breakpointhook = MagicMock()
1678        sys.breakpointhook = my_breakpointhook
1679        breakpoint(1, 2, 3, four=4, five=5)
1680        my_breakpointhook.assert_called_once_with(1, 2, 3, four=4, five=5)
1681
1682    def test_breakpoint_with_passthru_error(self):
1683        def my_breakpointhook():
1684            pass
1685        sys.breakpointhook = my_breakpointhook
1686        self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5)
1687
1688    @unittest.skipIf(sys.flags.ignore_environment, '-E was given')
1689    def test_envar_good_path_builtin(self):
1690        self.env['PYTHONBREAKPOINT'] = 'int'
1691        with patch('builtins.int') as mock:
1692            breakpoint('7')
1693            mock.assert_called_once_with('7')
1694
1695    @unittest.skipIf(sys.flags.ignore_environment, '-E was given')
1696    def test_envar_good_path_other(self):
1697        self.env['PYTHONBREAKPOINT'] = 'sys.exit'
1698        with patch('sys.exit') as mock:
1699            breakpoint()
1700            mock.assert_called_once_with()
1701
1702    @unittest.skipIf(sys.flags.ignore_environment, '-E was given')
1703    def test_envar_good_path_noop_0(self):
1704        self.env['PYTHONBREAKPOINT'] = '0'
1705        with patch('pdb.set_trace') as mock:
1706            breakpoint()
1707            mock.assert_not_called()
1708
1709    def test_envar_good_path_empty_string(self):
1710        # PYTHONBREAKPOINT='' is the same as it not being set.
1711        self.env['PYTHONBREAKPOINT'] = ''
1712        with patch('pdb.set_trace') as mock:
1713            breakpoint()
1714            mock.assert_called_once_with()
1715
1716    @unittest.skipIf(sys.flags.ignore_environment, '-E was given')
1717    def test_envar_unimportable(self):
1718        for envar in (
1719                '.', '..', '.foo', 'foo.', '.int', 'int.',
1720                '.foo.bar', '..foo.bar', '/./',
1721                'nosuchbuiltin',
1722                'nosuchmodule.nosuchcallable',
1723                ):
1724            with self.subTest(envar=envar):
1725                self.env['PYTHONBREAKPOINT'] = envar
1726                mock = self.resources.enter_context(patch('pdb.set_trace'))
1727                w = self.resources.enter_context(check_warnings(quiet=True))
1728                breakpoint()
1729                self.assertEqual(
1730                    str(w.message),
1731                    f'Ignoring unimportable $PYTHONBREAKPOINT: "{envar}"')
1732                self.assertEqual(w.category, RuntimeWarning)
1733                mock.assert_not_called()
1734
1735    def test_envar_ignored_when_hook_is_set(self):
1736        self.env['PYTHONBREAKPOINT'] = 'sys.exit'
1737        with patch('sys.exit') as mock:
1738            sys.breakpointhook = int
1739            breakpoint()
1740            mock.assert_not_called()
1741
1742
1743@unittest.skipUnless(pty, "the pty and signal modules must be available")
1744class PtyTests(unittest.TestCase):
1745    """Tests that use a pseudo terminal to guarantee stdin and stdout are
1746    terminals in the test environment"""
1747
1748    def run_child(self, child, terminal_input):
1749        r, w = os.pipe()  # Pipe test results from child back to parent
1750        try:
1751            pid, fd = pty.fork()
1752        except (OSError, AttributeError) as e:
1753            os.close(r)
1754            os.close(w)
1755            self.skipTest("pty.fork() raised {}".format(e))
1756            raise
1757        if pid == 0:
1758            # Child
1759            try:
1760                # Make sure we don't get stuck if there's a problem
1761                signal.alarm(2)
1762                os.close(r)
1763                with open(w, "w") as wpipe:
1764                    child(wpipe)
1765            except:
1766                traceback.print_exc()
1767            finally:
1768                # We don't want to return to unittest...
1769                os._exit(0)
1770        # Parent
1771        os.close(w)
1772        os.write(fd, terminal_input)
1773        # Get results from the pipe
1774        with open(r, "r") as rpipe:
1775            lines = []
1776            while True:
1777                line = rpipe.readline().strip()
1778                if line == "":
1779                    # The other end was closed => the child exited
1780                    break
1781                lines.append(line)
1782        # Check the result was got and corresponds to the user's terminal input
1783        if len(lines) != 2:
1784            # Something went wrong, try to get at stderr
1785            # Beware of Linux raising EIO when the slave is closed
1786            child_output = bytearray()
1787            while True:
1788                try:
1789                    chunk = os.read(fd, 3000)
1790                except OSError:  # Assume EIO
1791                    break
1792                if not chunk:
1793                    break
1794                child_output.extend(chunk)
1795            os.close(fd)
1796            child_output = child_output.decode("ascii", "ignore")
1797            self.fail("got %d lines in pipe but expected 2, child output was:\n%s"
1798                      % (len(lines), child_output))
1799        os.close(fd)
1800
1801        # Wait until the child process completes
1802        os.waitpid(pid, 0)
1803
1804        return lines
1805
1806    def check_input_tty(self, prompt, terminal_input, stdio_encoding=None):
1807        if not sys.stdin.isatty() or not sys.stdout.isatty():
1808            self.skipTest("stdin and stdout must be ttys")
1809        def child(wpipe):
1810            # Check the error handlers are accounted for
1811            if stdio_encoding:
1812                sys.stdin = io.TextIOWrapper(sys.stdin.detach(),
1813                                             encoding=stdio_encoding,
1814                                             errors='surrogateescape')
1815                sys.stdout = io.TextIOWrapper(sys.stdout.detach(),
1816                                              encoding=stdio_encoding,
1817                                              errors='replace')
1818            print("tty =", sys.stdin.isatty() and sys.stdout.isatty(), file=wpipe)
1819            print(ascii(input(prompt)), file=wpipe)
1820        lines = self.run_child(child, terminal_input + b"\r\n")
1821        # Check we did exercise the GNU readline path
1822        self.assertIn(lines[0], {'tty = True', 'tty = False'})
1823        if lines[0] != 'tty = True':
1824            self.skipTest("standard IO in should have been a tty")
1825        input_result = eval(lines[1])   # ascii() -> eval() roundtrip
1826        if stdio_encoding:
1827            expected = terminal_input.decode(stdio_encoding, 'surrogateescape')
1828        else:
1829            expected = terminal_input.decode(sys.stdin.encoding)  # what else?
1830        self.assertEqual(input_result, expected)
1831
1832    def test_input_tty(self):
1833        # Test input() functionality when wired to a tty (the code path
1834        # is different and invokes GNU readline if available).
1835        self.check_input_tty("prompt", b"quux")
1836
1837    def test_input_tty_non_ascii(self):
1838        # Check stdin/stdout encoding is used when invoking GNU readline
1839        self.check_input_tty("prompté", b"quux\xe9", "utf-8")
1840
1841    def test_input_tty_non_ascii_unicode_errors(self):
1842        # Check stdin/stdout error handler is used when invoking GNU readline
1843        self.check_input_tty("prompté", b"quux\xe9", "ascii")
1844
1845    def test_input_no_stdout_fileno(self):
1846        # Issue #24402: If stdin is the original terminal but stdout.fileno()
1847        # fails, do not use the original stdout file descriptor
1848        def child(wpipe):
1849            print("stdin.isatty():", sys.stdin.isatty(), file=wpipe)
1850            sys.stdout = io.StringIO()  # Does not support fileno()
1851            input("prompt")
1852            print("captured:", ascii(sys.stdout.getvalue()), file=wpipe)
1853        lines = self.run_child(child, b"quux\r")
1854        expected = (
1855            "stdin.isatty(): True",
1856            "captured: 'prompt'",
1857        )
1858        self.assertSequenceEqual(lines, expected)
1859
1860class TestSorted(unittest.TestCase):
1861
1862    def test_basic(self):
1863        data = list(range(100))
1864        copy = data[:]
1865        random.shuffle(copy)
1866        self.assertEqual(data, sorted(copy))
1867        self.assertNotEqual(data, copy)
1868
1869        data.reverse()
1870        random.shuffle(copy)
1871        self.assertEqual(data, sorted(copy, key=lambda x: -x))
1872        self.assertNotEqual(data, copy)
1873        random.shuffle(copy)
1874        self.assertEqual(data, sorted(copy, reverse=1))
1875        self.assertNotEqual(data, copy)
1876
1877    def test_bad_arguments(self):
1878        # Issue #29327: The first argument is positional-only.
1879        sorted([])
1880        with self.assertRaises(TypeError):
1881            sorted(iterable=[])
1882        # Other arguments are keyword-only
1883        sorted([], key=None)
1884        with self.assertRaises(TypeError):
1885            sorted([], None)
1886
1887    def test_inputtypes(self):
1888        s = 'abracadabra'
1889        types = [list, tuple, str]
1890        for T in types:
1891            self.assertEqual(sorted(s), sorted(T(s)))
1892
1893        s = ''.join(set(s))  # unique letters only
1894        types = [str, set, frozenset, list, tuple, dict.fromkeys]
1895        for T in types:
1896            self.assertEqual(sorted(s), sorted(T(s)))
1897
1898    def test_baddecorator(self):
1899        data = 'The quick Brown fox Jumped over The lazy Dog'.split()
1900        self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0)
1901
1902
1903class ShutdownTest(unittest.TestCase):
1904
1905    def test_cleanup(self):
1906        # Issue #19255: builtins are still available at shutdown
1907        code = """if 1:
1908            import builtins
1909            import sys
1910
1911            class C:
1912                def __del__(self):
1913                    print("before")
1914                    # Check that builtins still exist
1915                    len(())
1916                    print("after")
1917
1918            c = C()
1919            # Make this module survive until builtins and sys are cleaned
1920            builtins.here = sys.modules[__name__]
1921            sys.here = sys.modules[__name__]
1922            # Create a reference loop so that this module needs to go
1923            # through a GC phase.
1924            here = sys.modules[__name__]
1925            """
1926        # Issue #20599: Force ASCII encoding to get a codec implemented in C,
1927        # otherwise the codec may be unloaded before C.__del__() is called, and
1928        # so print("before") fails because the codec cannot be used to encode
1929        # "before" to sys.stdout.encoding. For example, on Windows,
1930        # sys.stdout.encoding is the OEM code page and these code pages are
1931        # implemented in Python
1932        rc, out, err = assert_python_ok("-c", code,
1933                                        PYTHONIOENCODING="ascii")
1934        self.assertEqual(["before", "after"], out.decode().splitlines())
1935
1936
1937class TestType(unittest.TestCase):
1938    def test_new_type(self):
1939        A = type('A', (), {})
1940        self.assertEqual(A.__name__, 'A')
1941        self.assertEqual(A.__qualname__, 'A')
1942        self.assertEqual(A.__module__, __name__)
1943        self.assertEqual(A.__bases__, (object,))
1944        self.assertIs(A.__base__, object)
1945        x = A()
1946        self.assertIs(type(x), A)
1947        self.assertIs(x.__class__, A)
1948
1949        class B:
1950            def ham(self):
1951                return 'ham%d' % self
1952        C = type('C', (B, int), {'spam': lambda self: 'spam%s' % self})
1953        self.assertEqual(C.__name__, 'C')
1954        self.assertEqual(C.__qualname__, 'C')
1955        self.assertEqual(C.__module__, __name__)
1956        self.assertEqual(C.__bases__, (B, int))
1957        self.assertIs(C.__base__, int)
1958        self.assertIn('spam', C.__dict__)
1959        self.assertNotIn('ham', C.__dict__)
1960        x = C(42)
1961        self.assertEqual(x, 42)
1962        self.assertIs(type(x), C)
1963        self.assertIs(x.__class__, C)
1964        self.assertEqual(x.ham(), 'ham42')
1965        self.assertEqual(x.spam(), 'spam42')
1966        self.assertEqual(x.to_bytes(2, 'little'), b'\x2a\x00')
1967
1968    def test_type_nokwargs(self):
1969        with self.assertRaises(TypeError):
1970            type('a', (), {}, x=5)
1971        with self.assertRaises(TypeError):
1972            type('a', (), dict={})
1973
1974    def test_type_name(self):
1975        for name in 'A', '\xc4', '\U0001f40d', 'B.A', '42', '':
1976            with self.subTest(name=name):
1977                A = type(name, (), {})
1978                self.assertEqual(A.__name__, name)
1979                self.assertEqual(A.__qualname__, name)
1980                self.assertEqual(A.__module__, __name__)
1981        with self.assertRaises(ValueError):
1982            type('A\x00B', (), {})
1983        with self.assertRaises(ValueError):
1984            type('A\udcdcB', (), {})
1985        with self.assertRaises(TypeError):
1986            type(b'A', (), {})
1987
1988        C = type('C', (), {})
1989        for name in 'A', '\xc4', '\U0001f40d', 'B.A', '42', '':
1990            with self.subTest(name=name):
1991                C.__name__ = name
1992                self.assertEqual(C.__name__, name)
1993                self.assertEqual(C.__qualname__, 'C')
1994                self.assertEqual(C.__module__, __name__)
1995
1996        A = type('C', (), {})
1997        with self.assertRaises(ValueError):
1998            A.__name__ = 'A\x00B'
1999        self.assertEqual(A.__name__, 'C')
2000        with self.assertRaises(ValueError):
2001            A.__name__ = 'A\udcdcB'
2002        self.assertEqual(A.__name__, 'C')
2003        with self.assertRaises(TypeError):
2004            A.__name__ = b'A'
2005        self.assertEqual(A.__name__, 'C')
2006
2007    def test_type_qualname(self):
2008        A = type('A', (), {'__qualname__': 'B.C'})
2009        self.assertEqual(A.__name__, 'A')
2010        self.assertEqual(A.__qualname__, 'B.C')
2011        self.assertEqual(A.__module__, __name__)
2012        with self.assertRaises(TypeError):
2013            type('A', (), {'__qualname__': b'B'})
2014        self.assertEqual(A.__qualname__, 'B.C')
2015
2016        A.__qualname__ = 'D.E'
2017        self.assertEqual(A.__name__, 'A')
2018        self.assertEqual(A.__qualname__, 'D.E')
2019        with self.assertRaises(TypeError):
2020            A.__qualname__ = b'B'
2021        self.assertEqual(A.__qualname__, 'D.E')
2022
2023    def test_type_doc(self):
2024        for doc in 'x', '\xc4', '\U0001f40d', 'x\x00y', b'x', 42, None:
2025            A = type('A', (), {'__doc__': doc})
2026            self.assertEqual(A.__doc__, doc)
2027        with self.assertRaises(UnicodeEncodeError):
2028            type('A', (), {'__doc__': 'x\udcdcy'})
2029
2030        A = type('A', (), {})
2031        self.assertEqual(A.__doc__, None)
2032        for doc in 'x', '\xc4', '\U0001f40d', 'x\x00y', 'x\udcdcy', b'x', 42, None:
2033            A.__doc__ = doc
2034            self.assertEqual(A.__doc__, doc)
2035
2036    def test_bad_args(self):
2037        with self.assertRaises(TypeError):
2038            type()
2039        with self.assertRaises(TypeError):
2040            type('A', ())
2041        with self.assertRaises(TypeError):
2042            type('A', (), {}, ())
2043        with self.assertRaises(TypeError):
2044            type('A', (), dict={})
2045        with self.assertRaises(TypeError):
2046            type('A', [], {})
2047        with self.assertRaises(TypeError):
2048            type('A', (), types.MappingProxyType({}))
2049        with self.assertRaises(TypeError):
2050            type('A', (None,), {})
2051        with self.assertRaises(TypeError):
2052            type('A', (bool,), {})
2053        with self.assertRaises(TypeError):
2054            type('A', (int, str), {})
2055
2056    def test_bad_slots(self):
2057        with self.assertRaises(TypeError):
2058            type('A', (), {'__slots__': b'x'})
2059        with self.assertRaises(TypeError):
2060            type('A', (int,), {'__slots__': 'x'})
2061        with self.assertRaises(TypeError):
2062            type('A', (), {'__slots__': ''})
2063        with self.assertRaises(TypeError):
2064            type('A', (), {'__slots__': '42'})
2065        with self.assertRaises(TypeError):
2066            type('A', (), {'__slots__': 'x\x00y'})
2067        with self.assertRaises(ValueError):
2068            type('A', (), {'__slots__': 'x', 'x': 0})
2069        with self.assertRaises(TypeError):
2070            type('A', (), {'__slots__': ('__dict__', '__dict__')})
2071        with self.assertRaises(TypeError):
2072            type('A', (), {'__slots__': ('__weakref__', '__weakref__')})
2073
2074        class B:
2075            pass
2076        with self.assertRaises(TypeError):
2077            type('A', (B,), {'__slots__': '__dict__'})
2078        with self.assertRaises(TypeError):
2079            type('A', (B,), {'__slots__': '__weakref__'})
2080
2081    def test_namespace_order(self):
2082        # bpo-34320: namespace should preserve order
2083        od = collections.OrderedDict([('a', 1), ('b', 2)])
2084        od.move_to_end('a')
2085        expected = list(od.items())
2086
2087        C = type('C', (), od)
2088        self.assertEqual(list(C.__dict__.items())[:2], [('b', 2), ('a', 1)])
2089
2090
2091def load_tests(loader, tests, pattern):
2092    from doctest import DocTestSuite
2093    tests.addTest(DocTestSuite(builtins))
2094    return tests
2095
2096if __name__ == "__main__":
2097    unittest.main()
2098