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