• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Python test set -- built-in functions
2
3import ast
4import asyncio
5import builtins
6import collections
7import contextlib
8import decimal
9import fractions
10import gc
11import io
12import locale
13import math
14import os
15import pickle
16import platform
17import random
18import re
19import sys
20import traceback
21import types
22import typing
23import unittest
24import warnings
25from contextlib import ExitStack
26from functools import partial
27from inspect import CO_COROUTINE
28from itertools import product
29from textwrap import dedent
30from types import AsyncGeneratorType, FunctionType, CellType
31from operator import neg
32from test import support
33from test.support import (cpython_only, swap_attr, maybe_get_event_loop_policy)
34from test.support.import_helper import import_module
35from test.support.os_helper import (EnvironmentVarGuard, TESTFN, unlink)
36from test.support.script_helper import assert_python_ok
37from test.support.warnings_helper import check_warnings
38from test.support import requires_IEEE_754
39from unittest.mock import MagicMock, patch
40try:
41    import pty, signal
42except ImportError:
43    pty = signal = None
44
45
46# Detect evidence of double-rounding: sum() does not always
47# get improved accuracy on machines that suffer from double rounding.
48x, y = 1e16, 2.9999 # use temporary values to defeat peephole optimizer
49HAVE_DOUBLE_ROUNDING = (x + y == 1e16 + 4)
50
51# used as proof of globals being used
52A_GLOBAL_VALUE = 123
53
54class Squares:
55
56    def __init__(self, max):
57        self.max = max
58        self.sofar = []
59
60    def __len__(self): return len(self.sofar)
61
62    def __getitem__(self, i):
63        if not 0 <= i < self.max: raise IndexError
64        n = len(self.sofar)
65        while n <= i:
66            self.sofar.append(n*n)
67            n += 1
68        return self.sofar[i]
69
70class StrSquares:
71
72    def __init__(self, max):
73        self.max = max
74        self.sofar = []
75
76    def __len__(self):
77        return len(self.sofar)
78
79    def __getitem__(self, i):
80        if not 0 <= i < self.max:
81            raise IndexError
82        n = len(self.sofar)
83        while n <= i:
84            self.sofar.append(str(n*n))
85            n += 1
86        return self.sofar[i]
87
88class BitBucket:
89    def write(self, line):
90        pass
91
92test_conv_no_sign = [
93        ('0', 0),
94        ('1', 1),
95        ('9', 9),
96        ('10', 10),
97        ('99', 99),
98        ('100', 100),
99        ('314', 314),
100        (' 314', 314),
101        ('314 ', 314),
102        ('  \t\t  314  \t\t  ', 314),
103        (repr(sys.maxsize), sys.maxsize),
104        ('  1x', ValueError),
105        ('  1  ', 1),
106        ('  1\02  ', ValueError),
107        ('', ValueError),
108        (' ', ValueError),
109        ('  \t\t  ', ValueError),
110        (str(br'\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
111        (chr(0x200), ValueError),
112]
113
114test_conv_sign = [
115        ('0', 0),
116        ('1', 1),
117        ('9', 9),
118        ('10', 10),
119        ('99', 99),
120        ('100', 100),
121        ('314', 314),
122        (' 314', ValueError),
123        ('314 ', 314),
124        ('  \t\t  314  \t\t  ', ValueError),
125        (repr(sys.maxsize), sys.maxsize),
126        ('  1x', ValueError),
127        ('  1  ', ValueError),
128        ('  1\02  ', ValueError),
129        ('', ValueError),
130        (' ', ValueError),
131        ('  \t\t  ', ValueError),
132        (str(br'\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
133        (chr(0x200), ValueError),
134]
135
136class TestFailingBool:
137    def __bool__(self):
138        raise RuntimeError
139
140class TestFailingIter:
141    def __iter__(self):
142        raise RuntimeError
143
144def filter_char(arg):
145    return ord(arg) > ord("d")
146
147def map_char(arg):
148    return chr(ord(arg)+1)
149
150class BuiltinTest(unittest.TestCase):
151    # Helper to check picklability
152    def check_iter_pickle(self, it, seq, proto):
153        itorg = it
154        d = pickle.dumps(it, proto)
155        it = pickle.loads(d)
156        self.assertEqual(type(itorg), type(it))
157        self.assertEqual(list(it), seq)
158
159        #test the iterator after dropping one from it
160        it = pickle.loads(d)
161        try:
162            next(it)
163        except StopIteration:
164            return
165        d = pickle.dumps(it, proto)
166        it = pickle.loads(d)
167        self.assertEqual(list(it), seq[1:])
168
169    def test_import(self):
170        __import__('sys')
171        __import__('time')
172        __import__('string')
173        __import__(name='sys')
174        __import__(name='time', level=0)
175        self.assertRaises(ModuleNotFoundError, __import__, 'spamspam')
176        self.assertRaises(TypeError, __import__, 1, 2, 3, 4)
177        self.assertRaises(ValueError, __import__, '')
178        self.assertRaises(TypeError, __import__, 'sys', name='sys')
179        # Relative import outside of a package with no __package__ or __spec__ (bpo-37409).
180        with self.assertWarns(ImportWarning):
181            self.assertRaises(ImportError, __import__, '',
182                              {'__package__': None, '__spec__': None, '__name__': '__main__'},
183                              locals={}, fromlist=('foo',), level=1)
184        # embedded null character
185        self.assertRaises(ModuleNotFoundError, __import__, 'string\x00')
186
187    def test_abs(self):
188        # int
189        self.assertEqual(abs(0), 0)
190        self.assertEqual(abs(1234), 1234)
191        self.assertEqual(abs(-1234), 1234)
192        self.assertTrue(abs(-sys.maxsize-1) > 0)
193        # float
194        self.assertEqual(abs(0.0), 0.0)
195        self.assertEqual(abs(3.14), 3.14)
196        self.assertEqual(abs(-3.14), 3.14)
197        # str
198        self.assertRaises(TypeError, abs, 'a')
199        # bool
200        self.assertEqual(abs(True), 1)
201        self.assertEqual(abs(False), 0)
202        # other
203        self.assertRaises(TypeError, abs)
204        self.assertRaises(TypeError, abs, None)
205        class AbsClass(object):
206            def __abs__(self):
207                return -5
208        self.assertEqual(abs(AbsClass()), -5)
209
210    def test_all(self):
211        self.assertEqual(all([2, 4, 6]), True)
212        self.assertEqual(all([2, None, 6]), False)
213        self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6])
214        self.assertRaises(RuntimeError, all, TestFailingIter())
215        self.assertRaises(TypeError, all, 10)               # Non-iterable
216        self.assertRaises(TypeError, all)                   # No args
217        self.assertRaises(TypeError, all, [2, 4, 6], [])    # Too many args
218        self.assertEqual(all([]), True)                     # Empty iterator
219        self.assertEqual(all([0, TestFailingBool()]), False)# Short-circuit
220        S = [50, 60]
221        self.assertEqual(all(x > 42 for x in S), True)
222        S = [50, 40, 60]
223        self.assertEqual(all(x > 42 for x in S), False)
224
225    def test_any(self):
226        self.assertEqual(any([None, None, None]), False)
227        self.assertEqual(any([None, 4, None]), True)
228        self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6])
229        self.assertRaises(RuntimeError, any, TestFailingIter())
230        self.assertRaises(TypeError, any, 10)               # Non-iterable
231        self.assertRaises(TypeError, any)                   # No args
232        self.assertRaises(TypeError, any, [2, 4, 6], [])    # Too many args
233        self.assertEqual(any([]), False)                    # Empty iterator
234        self.assertEqual(any([1, TestFailingBool()]), True) # Short-circuit
235        S = [40, 60, 30]
236        self.assertEqual(any(x > 42 for x in S), True)
237        S = [10, 20, 30]
238        self.assertEqual(any(x > 42 for x in S), False)
239
240    def test_ascii(self):
241        self.assertEqual(ascii(''), '\'\'')
242        self.assertEqual(ascii(0), '0')
243        self.assertEqual(ascii(()), '()')
244        self.assertEqual(ascii([]), '[]')
245        self.assertEqual(ascii({}), '{}')
246        a = []
247        a.append(a)
248        self.assertEqual(ascii(a), '[[...]]')
249        a = {}
250        a[0] = a
251        self.assertEqual(ascii(a), '{0: {...}}')
252        # Advanced checks for unicode strings
253        def _check_uni(s):
254            self.assertEqual(ascii(s), repr(s))
255        _check_uni("'")
256        _check_uni('"')
257        _check_uni('"\'')
258        _check_uni('\0')
259        _check_uni('\r\n\t .')
260        # Unprintable non-ASCII characters
261        _check_uni('\x85')
262        _check_uni('\u1fff')
263        _check_uni('\U00012fff')
264        # Lone surrogates
265        _check_uni('\ud800')
266        _check_uni('\udfff')
267        # Issue #9804: surrogates should be joined even for printable
268        # wide characters (UCS-2 builds).
269        self.assertEqual(ascii('\U0001d121'), "'\\U0001d121'")
270        # All together
271        s = "'\0\"\n\r\t abcd\x85é\U00012fff\uD800\U0001D121xxx."
272        self.assertEqual(ascii(s),
273            r"""'\'\x00"\n\r\t abcd\x85\xe9\U00012fff\ud800\U0001d121xxx.'""")
274
275    def test_neg(self):
276        x = -sys.maxsize-1
277        self.assertTrue(isinstance(x, int))
278        self.assertEqual(-x, sys.maxsize+1)
279
280    def test_callable(self):
281        self.assertTrue(callable(len))
282        self.assertFalse(callable("a"))
283        self.assertTrue(callable(callable))
284        self.assertTrue(callable(lambda x, y: x + y))
285        self.assertFalse(callable(__builtins__))
286        def f(): pass
287        self.assertTrue(callable(f))
288
289        class C1:
290            def meth(self): pass
291        self.assertTrue(callable(C1))
292        c = C1()
293        self.assertTrue(callable(c.meth))
294        self.assertFalse(callable(c))
295
296        # __call__ is looked up on the class, not the instance
297        c.__call__ = None
298        self.assertFalse(callable(c))
299        c.__call__ = lambda self: 0
300        self.assertFalse(callable(c))
301        del c.__call__
302        self.assertFalse(callable(c))
303
304        class C2(object):
305            def __call__(self): pass
306        c2 = C2()
307        self.assertTrue(callable(c2))
308        c2.__call__ = None
309        self.assertTrue(callable(c2))
310        class C3(C2): pass
311        c3 = C3()
312        self.assertTrue(callable(c3))
313
314    def test_chr(self):
315        self.assertEqual(chr(0), '\0')
316        self.assertEqual(chr(32), ' ')
317        self.assertEqual(chr(65), 'A')
318        self.assertEqual(chr(97), 'a')
319        self.assertEqual(chr(0xff), '\xff')
320        self.assertRaises(TypeError, chr)
321        self.assertRaises(TypeError, chr, 65.0)
322        self.assertEqual(chr(0x0000FFFF), "\U0000FFFF")
323        self.assertEqual(chr(0x00010000), "\U00010000")
324        self.assertEqual(chr(0x00010001), "\U00010001")
325        self.assertEqual(chr(0x000FFFFE), "\U000FFFFE")
326        self.assertEqual(chr(0x000FFFFF), "\U000FFFFF")
327        self.assertEqual(chr(0x00100000), "\U00100000")
328        self.assertEqual(chr(0x00100001), "\U00100001")
329        self.assertEqual(chr(0x0010FFFE), "\U0010FFFE")
330        self.assertEqual(chr(0x0010FFFF), "\U0010FFFF")
331        self.assertRaises(ValueError, chr, -1)
332        self.assertRaises(ValueError, chr, 0x00110000)
333        self.assertRaises(ValueError, chr, 1<<24)
334        self.assertRaises(ValueError, chr, 2**32-1)
335        self.assertRaises(ValueError, chr, -2**32)
336        self.assertRaises(ValueError, chr, 2**1000)
337        self.assertRaises(ValueError, chr, -2**1000)
338
339    def test_cmp(self):
340        self.assertTrue(not hasattr(builtins, "cmp"))
341
342    def test_compile(self):
343        compile('print(1)\n', '', 'exec')
344        bom = b'\xef\xbb\xbf'
345        compile(bom + b'print(1)\n', '', 'exec')
346        compile(source='pass', filename='?', mode='exec')
347        compile(dont_inherit=False, filename='tmp', source='0', mode='eval')
348        compile('pass', '?', dont_inherit=True, mode='exec')
349        compile(memoryview(b"text"), "name", "exec")
350        self.assertRaises(TypeError, compile)
351        self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'badmode')
352        self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'single', 0xff)
353        self.assertRaises(TypeError, compile, 'pass', '?', 'exec',
354                          mode='eval', source='0', filename='tmp')
355        compile('print("\xe5")\n', '', 'exec')
356        self.assertRaises(SyntaxError, compile, chr(0), 'f', 'exec')
357        self.assertRaises(ValueError, compile, str('a = 1'), 'f', 'bad')
358
359        # test the optimize argument
360
361        codestr = '''def f():
362        """doc"""
363        debug_enabled = False
364        if __debug__:
365            debug_enabled = True
366        try:
367            assert False
368        except AssertionError:
369            return (True, f.__doc__, debug_enabled, __debug__)
370        else:
371            return (False, f.__doc__, debug_enabled, __debug__)
372        '''
373        def f(): """doc"""
374        values = [(-1, __debug__, f.__doc__, __debug__, __debug__),
375                  (0, True, 'doc', True, True),
376                  (1, False, 'doc', False, False),
377                  (2, False, None, False, False)]
378        for optval, *expected in values:
379            with self.subTest(optval=optval):
380            # test both direct compilation and compilation via AST
381                codeobjs = []
382                codeobjs.append(compile(codestr, "<test>", "exec", optimize=optval))
383                tree = ast.parse(codestr)
384                codeobjs.append(compile(tree, "<test>", "exec", optimize=optval))
385                for code in codeobjs:
386                    ns = {}
387                    exec(code, ns)
388                    rv = ns['f']()
389                    self.assertEqual(rv, tuple(expected))
390
391    def test_compile_top_level_await_no_coro(self):
392        """Make sure top level non-await codes get the correct coroutine flags"""
393        modes = ('single', 'exec')
394        code_samples = [
395            '''def f():pass\n''',
396            '''[x for x in l]''',
397            '''{x for x in l}''',
398            '''(x for x in l)''',
399            '''{x:x for x in l}''',
400        ]
401        for mode, code_sample in product(modes, code_samples):
402            source = dedent(code_sample)
403            co = compile(source,
404                            '?',
405                            mode,
406                            flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)
407
408            self.assertNotEqual(co.co_flags & CO_COROUTINE, CO_COROUTINE,
409                                msg=f"source={source} mode={mode}")
410
411
412    @unittest.skipIf(
413        support.is_emscripten or support.is_wasi,
414        "socket.accept is broken"
415    )
416    def test_compile_top_level_await(self):
417        """Test whether code some top level await can be compiled.
418
419        Make sure it compiles only with the PyCF_ALLOW_TOP_LEVEL_AWAIT flag
420        set, and make sure the generated code object has the CO_COROUTINE flag
421        set in order to execute it with  `await eval(.....)` instead of exec,
422        or via a FunctionType.
423        """
424
425        # helper function just to check we can run top=level async-for
426        async def arange(n):
427            for i in range(n):
428                yield i
429
430        modes = ('single', 'exec')
431        code_samples = [
432            '''a = await asyncio.sleep(0, result=1)''',
433            '''async for i in arange(1):
434                   a = 1''',
435            '''async with asyncio.Lock() as l:
436                   a = 1''',
437            '''a = [x async for x in arange(2)][1]''',
438            '''a = 1 in {x async for x in arange(2)}''',
439            '''a = {x:1 async for x in arange(1)}[0]''',
440            '''a = [x async for x in arange(2) async for x in arange(2)][1]''',
441            '''a = [x async for x in (x async for x in arange(5))][1]''',
442            '''a, = [1 for x in {x async for x in arange(1)}]''',
443            '''a = [await asyncio.sleep(0, x) async for x in arange(2)][1]'''
444        ]
445        policy = maybe_get_event_loop_policy()
446        try:
447            for mode, code_sample in product(modes, code_samples):
448                source = dedent(code_sample)
449                with self.assertRaises(
450                        SyntaxError, msg=f"source={source} mode={mode}"):
451                    compile(source, '?', mode)
452
453                co = compile(source,
454                             '?',
455                             mode,
456                             flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)
457
458                self.assertEqual(co.co_flags & CO_COROUTINE, CO_COROUTINE,
459                                 msg=f"source={source} mode={mode}")
460
461                # test we can create and  advance a function type
462                globals_ = {'asyncio': asyncio, 'a': 0, 'arange': arange}
463                async_f = FunctionType(co, globals_)
464                asyncio.run(async_f())
465                self.assertEqual(globals_['a'], 1)
466
467                # test we can await-eval,
468                globals_ = {'asyncio': asyncio, 'a': 0, 'arange': arange}
469                asyncio.run(eval(co, globals_))
470                self.assertEqual(globals_['a'], 1)
471        finally:
472            asyncio.set_event_loop_policy(policy)
473
474    def test_compile_top_level_await_invalid_cases(self):
475         # helper function just to check we can run top=level async-for
476        async def arange(n):
477            for i in range(n):
478                yield i
479
480        modes = ('single', 'exec')
481        code_samples = [
482            '''def f():  await arange(10)\n''',
483            '''def f():  [x async for x in arange(10)]\n''',
484            '''def f():  [await x async for x in arange(10)]\n''',
485            '''def f():
486                   async for i in arange(1):
487                       a = 1
488            ''',
489            '''def f():
490                   async with asyncio.Lock() as l:
491                       a = 1
492            '''
493        ]
494        policy = maybe_get_event_loop_policy()
495        try:
496            for mode, code_sample in product(modes, code_samples):
497                source = dedent(code_sample)
498                with self.assertRaises(
499                        SyntaxError, msg=f"source={source} mode={mode}"):
500                    compile(source, '?', mode)
501
502                with self.assertRaises(
503                        SyntaxError, msg=f"source={source} mode={mode}"):
504                    co = compile(source,
505                             '?',
506                             mode,
507                             flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)
508        finally:
509            asyncio.set_event_loop_policy(policy)
510
511
512    def test_compile_async_generator(self):
513        """
514        With the PyCF_ALLOW_TOP_LEVEL_AWAIT flag added in 3.8, we want to
515        make sure AsyncGenerators are still properly not marked with the
516        CO_COROUTINE flag.
517        """
518        code = dedent("""async def ticker():
519                for i in range(10):
520                    yield i
521                    await asyncio.sleep(0)""")
522
523        co = compile(code, '?', 'exec', flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)
524        glob = {}
525        exec(co, glob)
526        self.assertEqual(type(glob['ticker']()), AsyncGeneratorType)
527
528    def test_compile_ast(self):
529        args = ("a*(1+2)", "f.py", "exec")
530        raw = compile(*args, flags = ast.PyCF_ONLY_AST).body[0]
531        opt1 = compile(*args, flags = ast.PyCF_OPTIMIZED_AST).body[0]
532        opt2 = compile(ast.parse(args[0]), *args[1:], flags = ast.PyCF_OPTIMIZED_AST).body[0]
533
534        for tree in (raw, opt1, opt2):
535            self.assertIsInstance(tree.value, ast.BinOp)
536            self.assertIsInstance(tree.value.op, ast.Mult)
537            self.assertIsInstance(tree.value.left, ast.Name)
538            self.assertEqual(tree.value.left.id, 'a')
539
540        raw_right = raw.value.right  # expect BinOp(1, '+', 2)
541        self.assertIsInstance(raw_right, ast.BinOp)
542        self.assertIsInstance(raw_right.left, ast.Constant)
543        self.assertEqual(raw_right.left.value, 1)
544        self.assertIsInstance(raw_right.right, ast.Constant)
545        self.assertEqual(raw_right.right.value, 2)
546
547        for opt in [opt1, opt2]:
548            opt_right = opt.value.right  # expect Constant(3)
549            self.assertIsInstance(opt_right, ast.Constant)
550            self.assertEqual(opt_right.value, 3)
551
552    def test_delattr(self):
553        sys.spam = 1
554        delattr(sys, 'spam')
555        self.assertRaises(TypeError, delattr)
556        self.assertRaises(TypeError, delattr, sys)
557        msg = r"^attribute name must be string, not 'int'$"
558        self.assertRaisesRegex(TypeError, msg, delattr, sys, 1)
559
560    def test_dir(self):
561        # dir(wrong number of arguments)
562        self.assertRaises(TypeError, dir, 42, 42)
563
564        # dir() - local scope
565        local_var = 1
566        self.assertIn('local_var', dir())
567
568        # dir(module)
569        self.assertIn('exit', dir(sys))
570
571        # dir(module_with_invalid__dict__)
572        class Foo(types.ModuleType):
573            __dict__ = 8
574        f = Foo("foo")
575        self.assertRaises(TypeError, dir, f)
576
577        # dir(type)
578        self.assertIn("strip", dir(str))
579        self.assertNotIn("__mro__", dir(str))
580
581        # dir(obj)
582        class Foo(object):
583            def __init__(self):
584                self.x = 7
585                self.y = 8
586                self.z = 9
587        f = Foo()
588        self.assertIn("y", dir(f))
589
590        # dir(obj_no__dict__)
591        class Foo(object):
592            __slots__ = []
593        f = Foo()
594        self.assertIn("__repr__", dir(f))
595
596        # dir(obj_no__class__with__dict__)
597        # (an ugly trick to cause getattr(f, "__class__") to fail)
598        class Foo(object):
599            __slots__ = ["__class__", "__dict__"]
600            def __init__(self):
601                self.bar = "wow"
602        f = Foo()
603        self.assertNotIn("__repr__", dir(f))
604        self.assertIn("bar", dir(f))
605
606        # dir(obj_using __dir__)
607        class Foo(object):
608            def __dir__(self):
609                return ["kan", "ga", "roo"]
610        f = Foo()
611        self.assertTrue(dir(f) == ["ga", "kan", "roo"])
612
613        # dir(obj__dir__tuple)
614        class Foo(object):
615            def __dir__(self):
616                return ("b", "c", "a")
617        res = dir(Foo())
618        self.assertIsInstance(res, list)
619        self.assertTrue(res == ["a", "b", "c"])
620
621        # dir(obj__dir__iterable)
622        class Foo(object):
623            def __dir__(self):
624                return {"b", "c", "a"}
625        res = dir(Foo())
626        self.assertIsInstance(res, list)
627        self.assertEqual(sorted(res), ["a", "b", "c"])
628
629        # dir(obj__dir__not_sequence)
630        class Foo(object):
631            def __dir__(self):
632                return 7
633        f = Foo()
634        self.assertRaises(TypeError, dir, f)
635
636        # dir(traceback)
637        try:
638            raise IndexError
639        except IndexError as e:
640            self.assertEqual(len(dir(e.__traceback__)), 4)
641
642        # test that object has a __dir__()
643        self.assertEqual(sorted([].__dir__()), dir([]))
644
645    def test___ne__(self):
646        self.assertFalse(None.__ne__(None))
647        self.assertIs(None.__ne__(0), NotImplemented)
648        self.assertIs(None.__ne__("abc"), NotImplemented)
649
650    def test_divmod(self):
651        self.assertEqual(divmod(12, 7), (1, 5))
652        self.assertEqual(divmod(-12, 7), (-2, 2))
653        self.assertEqual(divmod(12, -7), (-2, -2))
654        self.assertEqual(divmod(-12, -7), (1, -5))
655
656        self.assertEqual(divmod(-sys.maxsize-1, -1), (sys.maxsize+1, 0))
657
658        for num, denom, exp_result in [ (3.25, 1.0, (3.0, 0.25)),
659                                        (-3.25, 1.0, (-4.0, 0.75)),
660                                        (3.25, -1.0, (-4.0, -0.75)),
661                                        (-3.25, -1.0, (3.0, -0.25))]:
662            result = divmod(num, denom)
663            self.assertAlmostEqual(result[0], exp_result[0])
664            self.assertAlmostEqual(result[1], exp_result[1])
665
666        self.assertRaises(TypeError, divmod)
667
668    def test_eval(self):
669        self.assertEqual(eval('1+1'), 2)
670        self.assertEqual(eval(' 1+1\n'), 2)
671        globals = {'a': 1, 'b': 2}
672        locals = {'b': 200, 'c': 300}
673        self.assertEqual(eval('a', globals) , 1)
674        self.assertEqual(eval('a', globals, locals), 1)
675        self.assertEqual(eval('b', globals, locals), 200)
676        self.assertEqual(eval('c', globals, locals), 300)
677        globals = {'a': 1, 'b': 2}
678        locals = {'b': 200, 'c': 300}
679        bom = b'\xef\xbb\xbf'
680        self.assertEqual(eval(bom + b'a', globals, locals), 1)
681        self.assertEqual(eval('"\xe5"', globals), "\xe5")
682        self.assertRaises(TypeError, eval)
683        self.assertRaises(TypeError, eval, ())
684        self.assertRaises(SyntaxError, eval, bom[:2] + b'a')
685
686        class X:
687            def __getitem__(self, key):
688                raise ValueError
689        self.assertRaises(ValueError, eval, "foo", {}, X())
690
691    def test_eval_kwargs(self):
692        data = {"A_GLOBAL_VALUE": 456}
693        self.assertEqual(eval("globals()['A_GLOBAL_VALUE']", globals=data), 456)
694        self.assertEqual(eval("globals()['A_GLOBAL_VALUE']", locals=data), 123)
695
696    def test_general_eval(self):
697        # Tests that general mappings can be used for the locals argument
698
699        class M:
700            "Test mapping interface versus possible calls from eval()."
701            def __getitem__(self, key):
702                if key == 'a':
703                    return 12
704                raise KeyError
705            def keys(self):
706                return list('xyz')
707
708        m = M()
709        g = globals()
710        self.assertEqual(eval('a', g, m), 12)
711        self.assertRaises(NameError, eval, 'b', g, m)
712        self.assertEqual(eval('dir()', g, m), list('xyz'))
713        self.assertEqual(eval('globals()', g, m), g)
714        self.assertEqual(eval('locals()', g, m), m)
715        self.assertRaises(TypeError, eval, 'a', m)
716        class A:
717            "Non-mapping"
718            pass
719        m = A()
720        self.assertRaises(TypeError, eval, 'a', g, m)
721
722        # Verify that dict subclasses work as well
723        class D(dict):
724            def __getitem__(self, key):
725                if key == 'a':
726                    return 12
727                return dict.__getitem__(self, key)
728            def keys(self):
729                return list('xyz')
730
731        d = D()
732        self.assertEqual(eval('a', g, d), 12)
733        self.assertRaises(NameError, eval, 'b', g, d)
734        self.assertEqual(eval('dir()', g, d), list('xyz'))
735        self.assertEqual(eval('globals()', g, d), g)
736        self.assertEqual(eval('locals()', g, d), d)
737
738        # Verify locals stores (used by list comps)
739        eval('[locals() for i in (2,3)]', g, d)
740        eval('[locals() for i in (2,3)]', g, collections.UserDict())
741
742        class SpreadSheet:
743            "Sample application showing nested, calculated lookups."
744            _cells = {}
745            def __setitem__(self, key, formula):
746                self._cells[key] = formula
747            def __getitem__(self, key):
748                return eval(self._cells[key], globals(), self)
749
750        ss = SpreadSheet()
751        ss['a1'] = '5'
752        ss['a2'] = 'a1*6'
753        ss['a3'] = 'a2*7'
754        self.assertEqual(ss['a3'], 210)
755
756        # Verify that dir() catches a non-list returned by eval
757        # SF bug #1004669
758        class C:
759            def __getitem__(self, item):
760                raise KeyError(item)
761            def keys(self):
762                return 1 # used to be 'a' but that's no longer an error
763        self.assertRaises(TypeError, eval, 'dir()', globals(), C())
764
765    def test_exec(self):
766        g = {}
767        exec('z = 1', g)
768        if '__builtins__' in g:
769            del g['__builtins__']
770        self.assertEqual(g, {'z': 1})
771
772        exec('z = 1+1', g)
773        if '__builtins__' in g:
774            del g['__builtins__']
775        self.assertEqual(g, {'z': 2})
776        g = {}
777        l = {}
778
779        with check_warnings():
780            warnings.filterwarnings("ignore", "global statement",
781                    module="<string>")
782            exec('global a; a = 1; b = 2', g, l)
783        if '__builtins__' in g:
784            del g['__builtins__']
785        if '__builtins__' in l:
786            del l['__builtins__']
787        self.assertEqual((g, l), ({'a': 1}, {'b': 2}))
788
789    def test_exec_kwargs(self):
790        g = {}
791        exec('global z\nz = 1', globals=g)
792        if '__builtins__' in g:
793            del g['__builtins__']
794        self.assertEqual(g, {'z': 1})
795
796        # if we only set locals, the global assignment will not
797        # reach this locals dictionary
798        g = {}
799        exec('global z\nz = 1', locals=g)
800        self.assertEqual(g, {})
801
802    def test_exec_globals(self):
803        code = compile("print('Hello World!')", "", "exec")
804        # no builtin function
805        self.assertRaisesRegex(NameError, "name 'print' is not defined",
806                               exec, code, {'__builtins__': {}})
807        # __builtins__ must be a mapping type
808        self.assertRaises(TypeError,
809                          exec, code, {'__builtins__': 123})
810
811    def test_exec_globals_frozen(self):
812        class frozendict_error(Exception):
813            pass
814
815        class frozendict(dict):
816            def __setitem__(self, key, value):
817                raise frozendict_error("frozendict is readonly")
818
819        # read-only builtins
820        if isinstance(__builtins__, types.ModuleType):
821            frozen_builtins = frozendict(__builtins__.__dict__)
822        else:
823            frozen_builtins = frozendict(__builtins__)
824        code = compile("__builtins__['superglobal']=2; print(superglobal)", "test", "exec")
825        self.assertRaises(frozendict_error,
826                          exec, code, {'__builtins__': frozen_builtins})
827
828        # no __build_class__ function
829        code = compile("class A: pass", "", "exec")
830        self.assertRaisesRegex(NameError, "__build_class__ not found",
831                               exec, code, {'__builtins__': {}})
832        # __build_class__ in a custom __builtins__
833        exec(code, {'__builtins__': frozen_builtins})
834        self.assertRaisesRegex(NameError, "__build_class__ not found",
835                               exec, code, {'__builtins__': frozendict()})
836
837        # read-only globals
838        namespace = frozendict({})
839        code = compile("x=1", "test", "exec")
840        self.assertRaises(frozendict_error,
841                          exec, code, namespace)
842
843    def test_exec_globals_error_on_get(self):
844        # custom `globals` or `builtins` can raise errors on item access
845        class setonlyerror(Exception):
846            pass
847
848        class setonlydict(dict):
849            def __getitem__(self, key):
850                raise setonlyerror
851
852        # globals' `__getitem__` raises
853        code = compile("globalname", "test", "exec")
854        self.assertRaises(setonlyerror,
855                          exec, code, setonlydict({'globalname': 1}))
856
857        # builtins' `__getitem__` raises
858        code = compile("superglobal", "test", "exec")
859        self.assertRaises(setonlyerror, exec, code,
860                          {'__builtins__': setonlydict({'superglobal': 1})})
861
862    def test_exec_globals_dict_subclass(self):
863        class customdict(dict):  # this one should not do anything fancy
864            pass
865
866        code = compile("superglobal", "test", "exec")
867        # works correctly
868        exec(code, {'__builtins__': customdict({'superglobal': 1})})
869        # custom builtins dict subclass is missing key
870        self.assertRaisesRegex(NameError, "name 'superglobal' is not defined",
871                               exec, code, {'__builtins__': customdict()})
872
873    def test_eval_builtins_mapping(self):
874        code = compile("superglobal", "test", "eval")
875        # works correctly
876        ns = {'__builtins__': types.MappingProxyType({'superglobal': 1})}
877        self.assertEqual(eval(code, ns), 1)
878        # custom builtins mapping is missing key
879        ns = {'__builtins__': types.MappingProxyType({})}
880        self.assertRaisesRegex(NameError, "name 'superglobal' is not defined",
881                               eval, code, ns)
882
883    def test_exec_builtins_mapping_import(self):
884        code = compile("import foo.bar", "test", "exec")
885        ns = {'__builtins__': types.MappingProxyType({})}
886        self.assertRaisesRegex(ImportError, "__import__ not found", exec, code, ns)
887        ns = {'__builtins__': types.MappingProxyType({'__import__': lambda *args: args})}
888        exec(code, ns)
889        self.assertEqual(ns['foo'], ('foo.bar', ns, ns, None, 0))
890
891    def test_eval_builtins_mapping_reduce(self):
892        # list_iterator.__reduce__() calls _PyEval_GetBuiltin("iter")
893        code = compile("x.__reduce__()", "test", "eval")
894        ns = {'__builtins__': types.MappingProxyType({}), 'x': iter([1, 2])}
895        self.assertRaisesRegex(AttributeError, "iter", eval, code, ns)
896        ns = {'__builtins__': types.MappingProxyType({'iter': iter}), 'x': iter([1, 2])}
897        self.assertEqual(eval(code, ns), (iter, ([1, 2],), 0))
898
899    def test_exec_redirected(self):
900        savestdout = sys.stdout
901        sys.stdout = None # Whatever that cannot flush()
902        try:
903            # Used to raise SystemError('error return without exception set')
904            exec('a')
905        except NameError:
906            pass
907        finally:
908            sys.stdout = savestdout
909
910    def test_exec_closure(self):
911        def function_without_closures():
912            return 3 * 5
913
914        result = 0
915        def make_closure_functions():
916            a = 2
917            b = 3
918            c = 5
919            def three_freevars():
920                nonlocal result
921                nonlocal a
922                nonlocal b
923                result = a*b
924            def four_freevars():
925                nonlocal result
926                nonlocal a
927                nonlocal b
928                nonlocal c
929                result = a*b*c
930            return three_freevars, four_freevars
931        three_freevars, four_freevars = make_closure_functions()
932
933        # "smoke" test
934        result = 0
935        exec(three_freevars.__code__,
936            three_freevars.__globals__,
937            closure=three_freevars.__closure__)
938        self.assertEqual(result, 6)
939
940        # should also work with a manually created closure
941        result = 0
942        my_closure = (CellType(35), CellType(72), three_freevars.__closure__[2])
943        exec(three_freevars.__code__,
944            three_freevars.__globals__,
945            closure=my_closure)
946        self.assertEqual(result, 2520)
947
948        # should fail: closure isn't allowed
949        # for functions without free vars
950        self.assertRaises(TypeError,
951            exec,
952            function_without_closures.__code__,
953            function_without_closures.__globals__,
954            closure=my_closure)
955
956        # should fail: closure required but wasn't specified
957        self.assertRaises(TypeError,
958            exec,
959            three_freevars.__code__,
960            three_freevars.__globals__,
961            closure=None)
962
963        # should fail: closure of wrong length
964        self.assertRaises(TypeError,
965            exec,
966            three_freevars.__code__,
967            three_freevars.__globals__,
968            closure=four_freevars.__closure__)
969
970        # should fail: closure using a list instead of a tuple
971        my_closure = list(my_closure)
972        self.assertRaises(TypeError,
973            exec,
974            three_freevars.__code__,
975            three_freevars.__globals__,
976            closure=my_closure)
977
978        # should fail: closure tuple with one non-cell-var
979        my_closure[0] = int
980        my_closure = tuple(my_closure)
981        self.assertRaises(TypeError,
982            exec,
983            three_freevars.__code__,
984            three_freevars.__globals__,
985            closure=my_closure)
986
987
988    def test_filter(self):
989        self.assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld'))
990        self.assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9])
991        self.assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2])
992        self.assertEqual(list(filter(None, Squares(10))), [1, 4, 9, 16, 25, 36, 49, 64, 81])
993        self.assertEqual(list(filter(lambda x: x%2, Squares(10))), [1, 9, 25, 49, 81])
994        def identity(item):
995            return 1
996        filter(identity, Squares(5))
997        self.assertRaises(TypeError, filter)
998        class BadSeq(object):
999            def __getitem__(self, index):
1000                if index<4:
1001                    return 42
1002                raise ValueError
1003        self.assertRaises(ValueError, list, filter(lambda x: x, BadSeq()))
1004        def badfunc():
1005            pass
1006        self.assertRaises(TypeError, list, filter(badfunc, range(5)))
1007
1008        # test bltinmodule.c::filtertuple()
1009        self.assertEqual(list(filter(None, (1, 2))), [1, 2])
1010        self.assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4])
1011        self.assertRaises(TypeError, list, filter(42, (1, 2)))
1012
1013    def test_filter_pickle(self):
1014        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1015            f1 = filter(filter_char, "abcdeabcde")
1016            f2 = filter(filter_char, "abcdeabcde")
1017            self.check_iter_pickle(f1, list(f2), proto)
1018
1019    @support.requires_resource('cpu')
1020    def test_filter_dealloc(self):
1021        # Tests recursive deallocation of nested filter objects using the
1022        # thrashcan mechanism. See gh-102356 for more details.
1023        max_iters = 1000000
1024        i = filter(bool, range(max_iters))
1025        for _ in range(max_iters):
1026            i = filter(bool, i)
1027        del i
1028        gc.collect()
1029
1030    def test_getattr(self):
1031        self.assertTrue(getattr(sys, 'stdout') is sys.stdout)
1032        self.assertRaises(TypeError, getattr)
1033        self.assertRaises(TypeError, getattr, sys)
1034        msg = r"^attribute name must be string, not 'int'$"
1035        self.assertRaisesRegex(TypeError, msg, getattr, sys, 1)
1036        self.assertRaisesRegex(TypeError, msg, getattr, sys, 1, 'spam')
1037        self.assertRaises(AttributeError, getattr, sys, chr(sys.maxunicode))
1038        # unicode surrogates are not encodable to the default encoding (utf8)
1039        self.assertRaises(AttributeError, getattr, 1, "\uDAD1\uD51E")
1040
1041    def test_hasattr(self):
1042        self.assertTrue(hasattr(sys, 'stdout'))
1043        self.assertRaises(TypeError, hasattr)
1044        self.assertRaises(TypeError, hasattr, sys)
1045        msg = r"^attribute name must be string, not 'int'$"
1046        self.assertRaisesRegex(TypeError, msg, hasattr, sys, 1)
1047        self.assertEqual(False, hasattr(sys, chr(sys.maxunicode)))
1048
1049        # Check that hasattr propagates all exceptions outside of
1050        # AttributeError.
1051        class A:
1052            def __getattr__(self, what):
1053                raise SystemExit
1054        self.assertRaises(SystemExit, hasattr, A(), "b")
1055        class B:
1056            def __getattr__(self, what):
1057                raise ValueError
1058        self.assertRaises(ValueError, hasattr, B(), "b")
1059
1060    def test_hash(self):
1061        hash(None)
1062        self.assertEqual(hash(1), hash(1))
1063        self.assertEqual(hash(1), hash(1.0))
1064        hash('spam')
1065        self.assertEqual(hash('spam'), hash(b'spam'))
1066        hash((0,1,2,3))
1067        def f(): pass
1068        hash(f)
1069        self.assertRaises(TypeError, hash, [])
1070        self.assertRaises(TypeError, hash, {})
1071        # Bug 1536021: Allow hash to return long objects
1072        class X:
1073            def __hash__(self):
1074                return 2**100
1075        self.assertEqual(type(hash(X())), int)
1076        class Z(int):
1077            def __hash__(self):
1078                return self
1079        self.assertEqual(hash(Z(42)), hash(42))
1080
1081    def test_hex(self):
1082        self.assertEqual(hex(16), '0x10')
1083        self.assertEqual(hex(-16), '-0x10')
1084        self.assertRaises(TypeError, hex, {})
1085
1086    def test_id(self):
1087        id(None)
1088        id(1)
1089        id(1.0)
1090        id('spam')
1091        id((0,1,2,3))
1092        id([0,1,2,3])
1093        id({'spam': 1, 'eggs': 2, 'ham': 3})
1094
1095    # Test input() later, alphabetized as if it were raw_input
1096
1097    def test_iter(self):
1098        self.assertRaises(TypeError, iter)
1099        self.assertRaises(TypeError, iter, 42, 42)
1100        lists = [("1", "2"), ["1", "2"], "12"]
1101        for l in lists:
1102            i = iter(l)
1103            self.assertEqual(next(i), '1')
1104            self.assertEqual(next(i), '2')
1105            self.assertRaises(StopIteration, next, i)
1106
1107    def test_isinstance(self):
1108        class C:
1109            pass
1110        class D(C):
1111            pass
1112        class E:
1113            pass
1114        c = C()
1115        d = D()
1116        e = E()
1117        self.assertTrue(isinstance(c, C))
1118        self.assertTrue(isinstance(d, C))
1119        self.assertTrue(not isinstance(e, C))
1120        self.assertTrue(not isinstance(c, D))
1121        self.assertTrue(not isinstance('foo', E))
1122        self.assertRaises(TypeError, isinstance, E, 'foo')
1123        self.assertRaises(TypeError, isinstance)
1124
1125    def test_issubclass(self):
1126        class C:
1127            pass
1128        class D(C):
1129            pass
1130        class E:
1131            pass
1132        c = C()
1133        d = D()
1134        e = E()
1135        self.assertTrue(issubclass(D, C))
1136        self.assertTrue(issubclass(C, C))
1137        self.assertTrue(not issubclass(C, D))
1138        self.assertRaises(TypeError, issubclass, 'foo', E)
1139        self.assertRaises(TypeError, issubclass, E, 'foo')
1140        self.assertRaises(TypeError, issubclass)
1141
1142    def test_len(self):
1143        self.assertEqual(len('123'), 3)
1144        self.assertEqual(len(()), 0)
1145        self.assertEqual(len((1, 2, 3, 4)), 4)
1146        self.assertEqual(len([1, 2, 3, 4]), 4)
1147        self.assertEqual(len({}), 0)
1148        self.assertEqual(len({'a':1, 'b': 2}), 2)
1149        class BadSeq:
1150            def __len__(self):
1151                raise ValueError
1152        self.assertRaises(ValueError, len, BadSeq())
1153        class InvalidLen:
1154            def __len__(self):
1155                return None
1156        self.assertRaises(TypeError, len, InvalidLen())
1157        class FloatLen:
1158            def __len__(self):
1159                return 4.5
1160        self.assertRaises(TypeError, len, FloatLen())
1161        class NegativeLen:
1162            def __len__(self):
1163                return -10
1164        self.assertRaises(ValueError, len, NegativeLen())
1165        class HugeLen:
1166            def __len__(self):
1167                return sys.maxsize + 1
1168        self.assertRaises(OverflowError, len, HugeLen())
1169        class HugeNegativeLen:
1170            def __len__(self):
1171                return -sys.maxsize-10
1172        self.assertRaises(ValueError, len, HugeNegativeLen())
1173        class NoLenMethod(object): pass
1174        self.assertRaises(TypeError, len, NoLenMethod())
1175
1176    def test_map(self):
1177        self.assertEqual(
1178            list(map(lambda x: x*x, range(1,4))),
1179            [1, 4, 9]
1180        )
1181        try:
1182            from math import sqrt
1183        except ImportError:
1184            def sqrt(x):
1185                return pow(x, 0.5)
1186        self.assertEqual(
1187            list(map(lambda x: list(map(sqrt, x)), [[16, 4], [81, 9]])),
1188            [[4.0, 2.0], [9.0, 3.0]]
1189        )
1190        self.assertEqual(
1191            list(map(lambda x, y: x+y, [1,3,2], [9,1,4])),
1192            [10, 4, 6]
1193        )
1194
1195        def plus(*v):
1196            accu = 0
1197            for i in v: accu = accu + i
1198            return accu
1199        self.assertEqual(
1200            list(map(plus, [1, 3, 7])),
1201            [1, 3, 7]
1202        )
1203        self.assertEqual(
1204            list(map(plus, [1, 3, 7], [4, 9, 2])),
1205            [1+4, 3+9, 7+2]
1206        )
1207        self.assertEqual(
1208            list(map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])),
1209            [1+4+1, 3+9+1, 7+2+0]
1210        )
1211        self.assertEqual(
1212            list(map(int, Squares(10))),
1213            [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
1214        )
1215        def Max(a, b):
1216            if a is None:
1217                return b
1218            if b is None:
1219                return a
1220            return max(a, b)
1221        self.assertEqual(
1222            list(map(Max, Squares(3), Squares(2))),
1223            [0, 1]
1224        )
1225        self.assertRaises(TypeError, map)
1226        self.assertRaises(TypeError, map, lambda x: x, 42)
1227        class BadSeq:
1228            def __iter__(self):
1229                raise ValueError
1230                yield None
1231        self.assertRaises(ValueError, list, map(lambda x: x, BadSeq()))
1232        def badfunc(x):
1233            raise RuntimeError
1234        self.assertRaises(RuntimeError, list, map(badfunc, range(5)))
1235
1236    def test_map_pickle(self):
1237        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1238            m1 = map(map_char, "Is this the real life?")
1239            m2 = map(map_char, "Is this the real life?")
1240            self.check_iter_pickle(m1, list(m2), proto)
1241
1242    def test_max(self):
1243        self.assertEqual(max('123123'), '3')
1244        self.assertEqual(max(1, 2, 3), 3)
1245        self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)
1246        self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)
1247
1248        self.assertEqual(max(1, 2, 3.0), 3.0)
1249        self.assertEqual(max(1, 2.0, 3), 3)
1250        self.assertEqual(max(1.0, 2, 3), 3)
1251
1252        with self.assertRaisesRegex(
1253            TypeError,
1254            'max expected at least 1 argument, got 0'
1255        ):
1256            max()
1257
1258        self.assertRaises(TypeError, max, 42)
1259        with self.assertRaisesRegex(
1260            ValueError,
1261            r'max\(\) iterable argument is empty'
1262        ):
1263            max(())
1264        class BadSeq:
1265            def __getitem__(self, index):
1266                raise ValueError
1267        self.assertRaises(ValueError, max, BadSeq())
1268
1269        for stmt in (
1270            "max(key=int)",                 # no args
1271            "max(default=None)",
1272            "max(1, 2, default=None)",      # require container for default
1273            "max(default=None, key=int)",
1274            "max(1, key=int)",              # single arg not iterable
1275            "max(1, 2, keystone=int)",      # wrong keyword
1276            "max(1, 2, key=int, abc=int)",  # two many keywords
1277            "max(1, 2, key=1)",             # keyfunc is not callable
1278            ):
1279            try:
1280                exec(stmt, globals())
1281            except TypeError:
1282                pass
1283            else:
1284                self.fail(stmt)
1285
1286        self.assertEqual(max((1,), key=neg), 1)     # one elem iterable
1287        self.assertEqual(max((1,2), key=neg), 1)    # two elem iterable
1288        self.assertEqual(max(1, 2, key=neg), 1)     # two elems
1289
1290        self.assertEqual(max((), default=None), None)    # zero elem iterable
1291        self.assertEqual(max((1,), default=None), 1)     # one elem iterable
1292        self.assertEqual(max((1,2), default=None), 2)    # two elem iterable
1293
1294        self.assertEqual(max((), default=1, key=neg), 1)
1295        self.assertEqual(max((1, 2), default=3, key=neg), 1)
1296
1297        self.assertEqual(max((1, 2), key=None), 2)
1298
1299        data = [random.randrange(200) for i in range(100)]
1300        keys = dict((elem, random.randrange(50)) for elem in data)
1301        f = keys.__getitem__
1302        self.assertEqual(max(data, key=f),
1303                         sorted(reversed(data), key=f)[-1])
1304
1305    def test_min(self):
1306        self.assertEqual(min('123123'), '1')
1307        self.assertEqual(min(1, 2, 3), 1)
1308        self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1)
1309        self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1)
1310
1311        self.assertEqual(min(1, 2, 3.0), 1)
1312        self.assertEqual(min(1, 2.0, 3), 1)
1313        self.assertEqual(min(1.0, 2, 3), 1.0)
1314
1315        with self.assertRaisesRegex(
1316            TypeError,
1317            'min expected at least 1 argument, got 0'
1318        ):
1319            min()
1320
1321        self.assertRaises(TypeError, min, 42)
1322        with self.assertRaisesRegex(
1323            ValueError,
1324            r'min\(\) iterable argument is empty'
1325        ):
1326            min(())
1327        class BadSeq:
1328            def __getitem__(self, index):
1329                raise ValueError
1330        self.assertRaises(ValueError, min, BadSeq())
1331
1332        for stmt in (
1333            "min(key=int)",                 # no args
1334            "min(default=None)",
1335            "min(1, 2, default=None)",      # require container for default
1336            "min(default=None, key=int)",
1337            "min(1, key=int)",              # single arg not iterable
1338            "min(1, 2, keystone=int)",      # wrong keyword
1339            "min(1, 2, key=int, abc=int)",  # two many keywords
1340            "min(1, 2, key=1)",             # keyfunc is not callable
1341            ):
1342            try:
1343                exec(stmt, globals())
1344            except TypeError:
1345                pass
1346            else:
1347                self.fail(stmt)
1348
1349        self.assertEqual(min((1,), key=neg), 1)     # one elem iterable
1350        self.assertEqual(min((1,2), key=neg), 2)    # two elem iterable
1351        self.assertEqual(min(1, 2, key=neg), 2)     # two elems
1352
1353        self.assertEqual(min((), default=None), None)    # zero elem iterable
1354        self.assertEqual(min((1,), default=None), 1)     # one elem iterable
1355        self.assertEqual(min((1,2), default=None), 1)    # two elem iterable
1356
1357        self.assertEqual(min((), default=1, key=neg), 1)
1358        self.assertEqual(min((1, 2), default=1, key=neg), 2)
1359
1360        self.assertEqual(min((1, 2), key=None), 1)
1361
1362        data = [random.randrange(200) for i in range(100)]
1363        keys = dict((elem, random.randrange(50)) for elem in data)
1364        f = keys.__getitem__
1365        self.assertEqual(min(data, key=f),
1366                         sorted(data, key=f)[0])
1367
1368    def test_next(self):
1369        it = iter(range(2))
1370        self.assertEqual(next(it), 0)
1371        self.assertEqual(next(it), 1)
1372        self.assertRaises(StopIteration, next, it)
1373        self.assertRaises(StopIteration, next, it)
1374        self.assertEqual(next(it, 42), 42)
1375
1376        class Iter(object):
1377            def __iter__(self):
1378                return self
1379            def __next__(self):
1380                raise StopIteration
1381
1382        it = iter(Iter())
1383        self.assertEqual(next(it, 42), 42)
1384        self.assertRaises(StopIteration, next, it)
1385
1386        def gen():
1387            yield 1
1388            return
1389
1390        it = gen()
1391        self.assertEqual(next(it), 1)
1392        self.assertRaises(StopIteration, next, it)
1393        self.assertEqual(next(it, 42), 42)
1394
1395    def test_oct(self):
1396        self.assertEqual(oct(100), '0o144')
1397        self.assertEqual(oct(-100), '-0o144')
1398        self.assertRaises(TypeError, oct, ())
1399
1400    def write_testfile(self):
1401        # NB the first 4 lines are also used to test input, below
1402        fp = open(TESTFN, 'w', encoding="utf-8")
1403        self.addCleanup(unlink, TESTFN)
1404        with fp:
1405            fp.write('1+1\n')
1406            fp.write('The quick brown fox jumps over the lazy dog')
1407            fp.write('.\n')
1408            fp.write('Dear John\n')
1409            fp.write('XXX'*100)
1410            fp.write('YYY'*100)
1411
1412    def test_open(self):
1413        self.write_testfile()
1414        fp = open(TESTFN, encoding="utf-8")
1415        with fp:
1416            self.assertEqual(fp.readline(4), '1+1\n')
1417            self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n')
1418            self.assertEqual(fp.readline(4), 'Dear')
1419            self.assertEqual(fp.readline(100), ' John\n')
1420            self.assertEqual(fp.read(300), 'XXX'*100)
1421            self.assertEqual(fp.read(1000), 'YYY'*100)
1422
1423        # embedded null bytes and characters
1424        self.assertRaises(ValueError, open, 'a\x00b')
1425        self.assertRaises(ValueError, open, b'a\x00b')
1426
1427    @unittest.skipIf(sys.flags.utf8_mode, "utf-8 mode is enabled")
1428    def test_open_default_encoding(self):
1429        old_environ = dict(os.environ)
1430        try:
1431            # try to get a user preferred encoding different than the current
1432            # locale encoding to check that open() uses the current locale
1433            # encoding and not the user preferred encoding
1434            for key in ('LC_ALL', 'LANG', 'LC_CTYPE'):
1435                if key in os.environ:
1436                    del os.environ[key]
1437
1438            self.write_testfile()
1439            current_locale_encoding = locale.getencoding()
1440            with warnings.catch_warnings():
1441                warnings.simplefilter("ignore", EncodingWarning)
1442                fp = open(TESTFN, 'w')
1443            with fp:
1444                self.assertEqual(fp.encoding, current_locale_encoding)
1445        finally:
1446            os.environ.clear()
1447            os.environ.update(old_environ)
1448
1449    @support.requires_subprocess()
1450    def test_open_non_inheritable(self):
1451        fileobj = open(__file__, encoding="utf-8")
1452        with fileobj:
1453            self.assertFalse(os.get_inheritable(fileobj.fileno()))
1454
1455    def test_ord(self):
1456        self.assertEqual(ord(' '), 32)
1457        self.assertEqual(ord('A'), 65)
1458        self.assertEqual(ord('a'), 97)
1459        self.assertEqual(ord('\x80'), 128)
1460        self.assertEqual(ord('\xff'), 255)
1461
1462        self.assertEqual(ord(b' '), 32)
1463        self.assertEqual(ord(b'A'), 65)
1464        self.assertEqual(ord(b'a'), 97)
1465        self.assertEqual(ord(b'\x80'), 128)
1466        self.assertEqual(ord(b'\xff'), 255)
1467
1468        self.assertEqual(ord(chr(sys.maxunicode)), sys.maxunicode)
1469        self.assertRaises(TypeError, ord, 42)
1470
1471        self.assertEqual(ord(chr(0x10FFFF)), 0x10FFFF)
1472        self.assertEqual(ord("\U0000FFFF"), 0x0000FFFF)
1473        self.assertEqual(ord("\U00010000"), 0x00010000)
1474        self.assertEqual(ord("\U00010001"), 0x00010001)
1475        self.assertEqual(ord("\U000FFFFE"), 0x000FFFFE)
1476        self.assertEqual(ord("\U000FFFFF"), 0x000FFFFF)
1477        self.assertEqual(ord("\U00100000"), 0x00100000)
1478        self.assertEqual(ord("\U00100001"), 0x00100001)
1479        self.assertEqual(ord("\U0010FFFE"), 0x0010FFFE)
1480        self.assertEqual(ord("\U0010FFFF"), 0x0010FFFF)
1481
1482    def test_pow(self):
1483        self.assertEqual(pow(0,0), 1)
1484        self.assertEqual(pow(0,1), 0)
1485        self.assertEqual(pow(1,0), 1)
1486        self.assertEqual(pow(1,1), 1)
1487
1488        self.assertEqual(pow(2,0), 1)
1489        self.assertEqual(pow(2,10), 1024)
1490        self.assertEqual(pow(2,20), 1024*1024)
1491        self.assertEqual(pow(2,30), 1024*1024*1024)
1492
1493        self.assertEqual(pow(-2,0), 1)
1494        self.assertEqual(pow(-2,1), -2)
1495        self.assertEqual(pow(-2,2), 4)
1496        self.assertEqual(pow(-2,3), -8)
1497
1498        self.assertAlmostEqual(pow(0.,0), 1.)
1499        self.assertAlmostEqual(pow(0.,1), 0.)
1500        self.assertAlmostEqual(pow(1.,0), 1.)
1501        self.assertAlmostEqual(pow(1.,1), 1.)
1502
1503        self.assertAlmostEqual(pow(2.,0), 1.)
1504        self.assertAlmostEqual(pow(2.,10), 1024.)
1505        self.assertAlmostEqual(pow(2.,20), 1024.*1024.)
1506        self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.)
1507
1508        self.assertAlmostEqual(pow(-2.,0), 1.)
1509        self.assertAlmostEqual(pow(-2.,1), -2.)
1510        self.assertAlmostEqual(pow(-2.,2), 4.)
1511        self.assertAlmostEqual(pow(-2.,3), -8.)
1512
1513        for x in 2, 2.0:
1514            for y in 10, 10.0:
1515                for z in 1000, 1000.0:
1516                    if isinstance(x, float) or \
1517                       isinstance(y, float) or \
1518                       isinstance(z, float):
1519                        self.assertRaises(TypeError, pow, x, y, z)
1520                    else:
1521                        self.assertAlmostEqual(pow(x, y, z), 24.0)
1522
1523        self.assertAlmostEqual(pow(-1, 0.5), 1j)
1524        self.assertAlmostEqual(pow(-1, 1/3), 0.5 + 0.8660254037844386j)
1525
1526        # See test_pow for additional tests for three-argument pow.
1527        self.assertEqual(pow(-1, -2, 3), 1)
1528        self.assertRaises(ValueError, pow, 1, 2, 0)
1529
1530        self.assertRaises(TypeError, pow)
1531
1532        # Test passing in arguments as keywords.
1533        self.assertEqual(pow(0, exp=0), 1)
1534        self.assertEqual(pow(base=2, exp=4), 16)
1535        self.assertEqual(pow(base=5, exp=2, mod=14), 11)
1536        twopow = partial(pow, base=2)
1537        self.assertEqual(twopow(exp=5), 32)
1538        fifth_power = partial(pow, exp=5)
1539        self.assertEqual(fifth_power(2), 32)
1540        mod10 = partial(pow, mod=10)
1541        self.assertEqual(mod10(2, 6), 4)
1542        self.assertEqual(mod10(exp=6, base=2), 4)
1543
1544    def test_input(self):
1545        self.write_testfile()
1546        fp = open(TESTFN, encoding="utf-8")
1547        savestdin = sys.stdin
1548        savestdout = sys.stdout # Eats the echo
1549        try:
1550            sys.stdin = fp
1551            sys.stdout = BitBucket()
1552            self.assertEqual(input(), "1+1")
1553            self.assertEqual(input(), 'The quick brown fox jumps over the lazy dog.')
1554            self.assertEqual(input('testing\n'), 'Dear John')
1555
1556            # SF 1535165: don't segfault on closed stdin
1557            # sys.stdout must be a regular file for triggering
1558            sys.stdout = savestdout
1559            sys.stdin.close()
1560            self.assertRaises(ValueError, input)
1561
1562            sys.stdout = BitBucket()
1563            sys.stdin = io.StringIO("NULL\0")
1564            self.assertRaises(TypeError, input, 42, 42)
1565            sys.stdin = io.StringIO("    'whitespace'")
1566            self.assertEqual(input(), "    'whitespace'")
1567            sys.stdin = io.StringIO()
1568            self.assertRaises(EOFError, input)
1569
1570            del sys.stdout
1571            self.assertRaises(RuntimeError, input, 'prompt')
1572            del sys.stdin
1573            self.assertRaises(RuntimeError, input, 'prompt')
1574        finally:
1575            sys.stdin = savestdin
1576            sys.stdout = savestdout
1577            fp.close()
1578
1579    # test_int(): see test_int.py for tests of built-in function int().
1580
1581    def test_repr(self):
1582        self.assertEqual(repr(''), '\'\'')
1583        self.assertEqual(repr(0), '0')
1584        self.assertEqual(repr(()), '()')
1585        self.assertEqual(repr([]), '[]')
1586        self.assertEqual(repr({}), '{}')
1587        a = []
1588        a.append(a)
1589        self.assertEqual(repr(a), '[[...]]')
1590        a = {}
1591        a[0] = a
1592        self.assertEqual(repr(a), '{0: {...}}')
1593
1594    def test_round(self):
1595        self.assertEqual(round(0.0), 0.0)
1596        self.assertEqual(type(round(0.0)), int)
1597        self.assertEqual(round(1.0), 1.0)
1598        self.assertEqual(round(10.0), 10.0)
1599        self.assertEqual(round(1000000000.0), 1000000000.0)
1600        self.assertEqual(round(1e20), 1e20)
1601
1602        self.assertEqual(round(-1.0), -1.0)
1603        self.assertEqual(round(-10.0), -10.0)
1604        self.assertEqual(round(-1000000000.0), -1000000000.0)
1605        self.assertEqual(round(-1e20), -1e20)
1606
1607        self.assertEqual(round(0.1), 0.0)
1608        self.assertEqual(round(1.1), 1.0)
1609        self.assertEqual(round(10.1), 10.0)
1610        self.assertEqual(round(1000000000.1), 1000000000.0)
1611
1612        self.assertEqual(round(-1.1), -1.0)
1613        self.assertEqual(round(-10.1), -10.0)
1614        self.assertEqual(round(-1000000000.1), -1000000000.0)
1615
1616        self.assertEqual(round(0.9), 1.0)
1617        self.assertEqual(round(9.9), 10.0)
1618        self.assertEqual(round(999999999.9), 1000000000.0)
1619
1620        self.assertEqual(round(-0.9), -1.0)
1621        self.assertEqual(round(-9.9), -10.0)
1622        self.assertEqual(round(-999999999.9), -1000000000.0)
1623
1624        self.assertEqual(round(-8.0, -1), -10.0)
1625        self.assertEqual(type(round(-8.0, -1)), float)
1626
1627        self.assertEqual(type(round(-8.0, 0)), float)
1628        self.assertEqual(type(round(-8.0, 1)), float)
1629
1630        # Check even / odd rounding behaviour
1631        self.assertEqual(round(5.5), 6)
1632        self.assertEqual(round(6.5), 6)
1633        self.assertEqual(round(-5.5), -6)
1634        self.assertEqual(round(-6.5), -6)
1635
1636        # Check behavior on ints
1637        self.assertEqual(round(0), 0)
1638        self.assertEqual(round(8), 8)
1639        self.assertEqual(round(-8), -8)
1640        self.assertEqual(type(round(0)), int)
1641        self.assertEqual(type(round(-8, -1)), int)
1642        self.assertEqual(type(round(-8, 0)), int)
1643        self.assertEqual(type(round(-8, 1)), int)
1644
1645        # test new kwargs
1646        self.assertEqual(round(number=-8.0, ndigits=-1), -10.0)
1647
1648        self.assertRaises(TypeError, round)
1649
1650        # test generic rounding delegation for reals
1651        class TestRound:
1652            def __round__(self):
1653                return 23
1654
1655        class TestNoRound:
1656            pass
1657
1658        self.assertEqual(round(TestRound()), 23)
1659
1660        self.assertRaises(TypeError, round, 1, 2, 3)
1661        self.assertRaises(TypeError, round, TestNoRound())
1662
1663        t = TestNoRound()
1664        t.__round__ = lambda *args: args
1665        self.assertRaises(TypeError, round, t)
1666        self.assertRaises(TypeError, round, t, 0)
1667
1668    # Some versions of glibc for alpha have a bug that affects
1669    # float -> integer rounding (floor, ceil, rint, round) for
1670    # values in the range [2**52, 2**53).  See:
1671    #
1672    #   http://sources.redhat.com/bugzilla/show_bug.cgi?id=5350
1673    #
1674    # We skip this test on Linux/alpha if it would fail.
1675    linux_alpha = (platform.system().startswith('Linux') and
1676                   platform.machine().startswith('alpha'))
1677    system_round_bug = round(5e15+1) != 5e15+1
1678    @unittest.skipIf(linux_alpha and system_round_bug,
1679                     "test will fail;  failure is probably due to a "
1680                     "buggy system round function")
1681    def test_round_large(self):
1682        # Issue #1869: integral floats should remain unchanged
1683        self.assertEqual(round(5e15-1), 5e15-1)
1684        self.assertEqual(round(5e15), 5e15)
1685        self.assertEqual(round(5e15+1), 5e15+1)
1686        self.assertEqual(round(5e15+2), 5e15+2)
1687        self.assertEqual(round(5e15+3), 5e15+3)
1688
1689    def test_bug_27936(self):
1690        # Verify that ndigits=None means the same as passing in no argument
1691        for x in [1234,
1692                  1234.56,
1693                  decimal.Decimal('1234.56'),
1694                  fractions.Fraction(123456, 100)]:
1695            self.assertEqual(round(x, None), round(x))
1696            self.assertEqual(type(round(x, None)), type(round(x)))
1697
1698    def test_setattr(self):
1699        setattr(sys, 'spam', 1)
1700        self.assertEqual(sys.spam, 1)
1701        self.assertRaises(TypeError, setattr)
1702        self.assertRaises(TypeError, setattr, sys)
1703        self.assertRaises(TypeError, setattr, sys, 'spam')
1704        msg = r"^attribute name must be string, not 'int'$"
1705        self.assertRaisesRegex(TypeError, msg, setattr, sys, 1, 'spam')
1706
1707    # test_str(): see test_str.py and test_bytes.py for str() tests.
1708
1709    def test_sum(self):
1710        self.assertEqual(sum([]), 0)
1711        self.assertEqual(sum(list(range(2,8))), 27)
1712        self.assertEqual(sum(iter(list(range(2,8)))), 27)
1713        self.assertEqual(sum(Squares(10)), 285)
1714        self.assertEqual(sum(iter(Squares(10))), 285)
1715        self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])
1716
1717        self.assertEqual(sum(range(10), 1000), 1045)
1718        self.assertEqual(sum(range(10), start=1000), 1045)
1719        self.assertEqual(sum(range(10), 2**31-5), 2**31+40)
1720        self.assertEqual(sum(range(10), 2**63-5), 2**63+40)
1721
1722        self.assertEqual(sum(i % 2 != 0 for i in range(10)), 5)
1723        self.assertEqual(sum((i % 2 != 0 for i in range(10)), 2**31-3),
1724                         2**31+2)
1725        self.assertEqual(sum((i % 2 != 0 for i in range(10)), 2**63-3),
1726                         2**63+2)
1727        self.assertIs(sum([], False), False)
1728
1729        self.assertEqual(sum(i / 2 for i in range(10)), 22.5)
1730        self.assertEqual(sum((i / 2 for i in range(10)), 1000), 1022.5)
1731        self.assertEqual(sum((i / 2 for i in range(10)), 1000.25), 1022.75)
1732        self.assertEqual(sum([0.5, 1]), 1.5)
1733        self.assertEqual(sum([1, 0.5]), 1.5)
1734        self.assertEqual(repr(sum([-0.0])), '0.0')
1735        self.assertEqual(repr(sum([-0.0], -0.0)), '-0.0')
1736        self.assertEqual(repr(sum([], -0.0)), '-0.0')
1737        self.assertTrue(math.isinf(sum([float("inf"), float("inf")])))
1738        self.assertTrue(math.isinf(sum([1e308, 1e308])))
1739
1740        self.assertRaises(TypeError, sum)
1741        self.assertRaises(TypeError, sum, 42)
1742        self.assertRaises(TypeError, sum, ['a', 'b', 'c'])
1743        self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '')
1744        self.assertRaises(TypeError, sum, [b'a', b'c'], b'')
1745        values = [bytearray(b'a'), bytearray(b'b')]
1746        self.assertRaises(TypeError, sum, values, bytearray(b''))
1747        self.assertRaises(TypeError, sum, [[1], [2], [3]])
1748        self.assertRaises(TypeError, sum, [{2:3}])
1749        self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3})
1750        self.assertRaises(TypeError, sum, [], '')
1751        self.assertRaises(TypeError, sum, [], b'')
1752        self.assertRaises(TypeError, sum, [], bytearray())
1753
1754        class BadSeq:
1755            def __getitem__(self, index):
1756                raise ValueError
1757        self.assertRaises(ValueError, sum, BadSeq())
1758
1759        empty = []
1760        sum(([x] for x in range(10)), empty)
1761        self.assertEqual(empty, [])
1762
1763    @requires_IEEE_754
1764    @unittest.skipIf(HAVE_DOUBLE_ROUNDING,
1765                         "sum accuracy not guaranteed on machines with double rounding")
1766    @support.cpython_only    # Other implementations may choose a different algorithm
1767    def test_sum_accuracy(self):
1768        self.assertEqual(sum([0.1] * 10), 1.0)
1769        self.assertEqual(sum([1.0, 10E100, 1.0, -10E100]), 2.0)
1770
1771    def test_type(self):
1772        self.assertEqual(type(''),  type('123'))
1773        self.assertNotEqual(type(''), type(()))
1774
1775    # We don't want self in vars(), so these are static methods
1776
1777    @staticmethod
1778    def get_vars_f0():
1779        return vars()
1780
1781    @staticmethod
1782    def get_vars_f2():
1783        BuiltinTest.get_vars_f0()
1784        a = 1
1785        b = 2
1786        return vars()
1787
1788    class C_get_vars(object):
1789        def getDict(self):
1790            return {'a':2}
1791        __dict__ = property(fget=getDict)
1792
1793    def test_vars(self):
1794        self.assertEqual(set(vars()), set(dir()))
1795        self.assertEqual(set(vars(sys)), set(dir(sys)))
1796        self.assertEqual(self.get_vars_f0(), {})
1797        self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2})
1798        self.assertRaises(TypeError, vars, 42, 42)
1799        self.assertRaises(TypeError, vars, 42)
1800        self.assertEqual(vars(self.C_get_vars()), {'a':2})
1801
1802    def iter_error(self, iterable, error):
1803        """Collect `iterable` into a list, catching an expected `error`."""
1804        items = []
1805        with self.assertRaises(error):
1806            for item in iterable:
1807                items.append(item)
1808        return items
1809
1810    def test_zip(self):
1811        a = (1, 2, 3)
1812        b = (4, 5, 6)
1813        t = [(1, 4), (2, 5), (3, 6)]
1814        self.assertEqual(list(zip(a, b)), t)
1815        b = [4, 5, 6]
1816        self.assertEqual(list(zip(a, b)), t)
1817        b = (4, 5, 6, 7)
1818        self.assertEqual(list(zip(a, b)), t)
1819        class I:
1820            def __getitem__(self, i):
1821                if i < 0 or i > 2: raise IndexError
1822                return i + 4
1823        self.assertEqual(list(zip(a, I())), t)
1824        self.assertEqual(list(zip()), [])
1825        self.assertEqual(list(zip(*[])), [])
1826        self.assertRaises(TypeError, zip, None)
1827        class G:
1828            pass
1829        self.assertRaises(TypeError, zip, a, G())
1830        self.assertRaises(RuntimeError, zip, a, TestFailingIter())
1831
1832        # Make sure zip doesn't try to allocate a billion elements for the
1833        # result list when one of its arguments doesn't say how long it is.
1834        # A MemoryError is the most likely failure mode.
1835        class SequenceWithoutALength:
1836            def __getitem__(self, i):
1837                if i == 5:
1838                    raise IndexError
1839                else:
1840                    return i
1841        self.assertEqual(
1842            list(zip(SequenceWithoutALength(), range(2**30))),
1843            list(enumerate(range(5)))
1844        )
1845
1846        class BadSeq:
1847            def __getitem__(self, i):
1848                if i == 5:
1849                    raise ValueError
1850                else:
1851                    return i
1852        self.assertRaises(ValueError, list, zip(BadSeq(), BadSeq()))
1853
1854    def test_zip_pickle(self):
1855        a = (1, 2, 3)
1856        b = (4, 5, 6)
1857        t = [(1, 4), (2, 5), (3, 6)]
1858        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1859            z1 = zip(a, b)
1860            self.check_iter_pickle(z1, t, proto)
1861
1862    def test_zip_pickle_strict(self):
1863        a = (1, 2, 3)
1864        b = (4, 5, 6)
1865        t = [(1, 4), (2, 5), (3, 6)]
1866        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1867            z1 = zip(a, b, strict=True)
1868            self.check_iter_pickle(z1, t, proto)
1869
1870    def test_zip_pickle_strict_fail(self):
1871        a = (1, 2, 3)
1872        b = (4, 5, 6, 7)
1873        t = [(1, 4), (2, 5), (3, 6)]
1874        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1875            z1 = zip(a, b, strict=True)
1876            z2 = pickle.loads(pickle.dumps(z1, proto))
1877            self.assertEqual(self.iter_error(z1, ValueError), t)
1878            self.assertEqual(self.iter_error(z2, ValueError), t)
1879
1880    def test_zip_bad_iterable(self):
1881        exception = TypeError()
1882
1883        class BadIterable:
1884            def __iter__(self):
1885                raise exception
1886
1887        with self.assertRaises(TypeError) as cm:
1888            zip(BadIterable())
1889
1890        self.assertIs(cm.exception, exception)
1891
1892    def test_zip_strict(self):
1893        self.assertEqual(tuple(zip((1, 2, 3), 'abc', strict=True)),
1894                         ((1, 'a'), (2, 'b'), (3, 'c')))
1895        self.assertRaises(ValueError, tuple,
1896                          zip((1, 2, 3, 4), 'abc', strict=True))
1897        self.assertRaises(ValueError, tuple,
1898                          zip((1, 2), 'abc', strict=True))
1899        self.assertRaises(ValueError, tuple,
1900                          zip((1, 2), (1, 2), 'abc', strict=True))
1901
1902    def test_zip_strict_iterators(self):
1903        x = iter(range(5))
1904        y = [0]
1905        z = iter(range(5))
1906        self.assertRaises(ValueError, list,
1907                          (zip(x, y, z, strict=True)))
1908        self.assertEqual(next(x), 2)
1909        self.assertEqual(next(z), 1)
1910
1911    def test_zip_strict_error_handling(self):
1912
1913        class Error(Exception):
1914            pass
1915
1916        class Iter:
1917            def __init__(self, size):
1918                self.size = size
1919            def __iter__(self):
1920                return self
1921            def __next__(self):
1922                self.size -= 1
1923                if self.size < 0:
1924                    raise Error
1925                return self.size
1926
1927        l1 = self.iter_error(zip("AB", Iter(1), strict=True), Error)
1928        self.assertEqual(l1, [("A", 0)])
1929        l2 = self.iter_error(zip("AB", Iter(2), "A", strict=True), ValueError)
1930        self.assertEqual(l2, [("A", 1, "A")])
1931        l3 = self.iter_error(zip("AB", Iter(2), "ABC", strict=True), Error)
1932        self.assertEqual(l3, [("A", 1, "A"), ("B", 0, "B")])
1933        l4 = self.iter_error(zip("AB", Iter(3), strict=True), ValueError)
1934        self.assertEqual(l4, [("A", 2), ("B", 1)])
1935        l5 = self.iter_error(zip(Iter(1), "AB", strict=True), Error)
1936        self.assertEqual(l5, [(0, "A")])
1937        l6 = self.iter_error(zip(Iter(2), "A", strict=True), ValueError)
1938        self.assertEqual(l6, [(1, "A")])
1939        l7 = self.iter_error(zip(Iter(2), "ABC", strict=True), Error)
1940        self.assertEqual(l7, [(1, "A"), (0, "B")])
1941        l8 = self.iter_error(zip(Iter(3), "AB", strict=True), ValueError)
1942        self.assertEqual(l8, [(2, "A"), (1, "B")])
1943
1944    def test_zip_strict_error_handling_stopiteration(self):
1945
1946        class Iter:
1947            def __init__(self, size):
1948                self.size = size
1949            def __iter__(self):
1950                return self
1951            def __next__(self):
1952                self.size -= 1
1953                if self.size < 0:
1954                    raise StopIteration
1955                return self.size
1956
1957        l1 = self.iter_error(zip("AB", Iter(1), strict=True), ValueError)
1958        self.assertEqual(l1, [("A", 0)])
1959        l2 = self.iter_error(zip("AB", Iter(2), "A", strict=True), ValueError)
1960        self.assertEqual(l2, [("A", 1, "A")])
1961        l3 = self.iter_error(zip("AB", Iter(2), "ABC", strict=True), ValueError)
1962        self.assertEqual(l3, [("A", 1, "A"), ("B", 0, "B")])
1963        l4 = self.iter_error(zip("AB", Iter(3), strict=True), ValueError)
1964        self.assertEqual(l4, [("A", 2), ("B", 1)])
1965        l5 = self.iter_error(zip(Iter(1), "AB", strict=True), ValueError)
1966        self.assertEqual(l5, [(0, "A")])
1967        l6 = self.iter_error(zip(Iter(2), "A", strict=True), ValueError)
1968        self.assertEqual(l6, [(1, "A")])
1969        l7 = self.iter_error(zip(Iter(2), "ABC", strict=True), ValueError)
1970        self.assertEqual(l7, [(1, "A"), (0, "B")])
1971        l8 = self.iter_error(zip(Iter(3), "AB", strict=True), ValueError)
1972        self.assertEqual(l8, [(2, "A"), (1, "B")])
1973
1974    @support.cpython_only
1975    def test_zip_result_gc(self):
1976        # bpo-42536: zip's tuple-reuse speed trick breaks the GC's assumptions
1977        # about what can be untracked. Make sure we re-track result tuples
1978        # whenever we reuse them.
1979        it = zip([[]])
1980        gc.collect()
1981        # That GC collection probably untracked the recycled internal result
1982        # tuple, which is initialized to (None,). Make sure it's re-tracked when
1983        # it's mutated and returned from __next__:
1984        self.assertTrue(gc.is_tracked(next(it)))
1985
1986    def test_format(self):
1987        # Test the basic machinery of the format() builtin.  Don't test
1988        #  the specifics of the various formatters
1989        self.assertEqual(format(3, ''), '3')
1990
1991        # Returns some classes to use for various tests.  There's
1992        #  an old-style version, and a new-style version
1993        def classes_new():
1994            class A(object):
1995                def __init__(self, x):
1996                    self.x = x
1997                def __format__(self, format_spec):
1998                    return str(self.x) + format_spec
1999            class DerivedFromA(A):
2000                pass
2001
2002            class Simple(object): pass
2003            class DerivedFromSimple(Simple):
2004                def __init__(self, x):
2005                    self.x = x
2006                def __format__(self, format_spec):
2007                    return str(self.x) + format_spec
2008            class DerivedFromSimple2(DerivedFromSimple): pass
2009            return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2
2010
2011        def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2):
2012            self.assertEqual(format(A(3), 'spec'), '3spec')
2013            self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec')
2014            self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc')
2015            self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'),
2016                             '10abcdef')
2017
2018        class_test(*classes_new())
2019
2020        def empty_format_spec(value):
2021            # test that:
2022            #  format(x, '') == str(x)
2023            #  format(x) == str(x)
2024            self.assertEqual(format(value, ""), str(value))
2025            self.assertEqual(format(value), str(value))
2026
2027        # for builtin types, format(x, "") == str(x)
2028        empty_format_spec(17**13)
2029        empty_format_spec(1.0)
2030        empty_format_spec(3.1415e104)
2031        empty_format_spec(-3.1415e104)
2032        empty_format_spec(3.1415e-104)
2033        empty_format_spec(-3.1415e-104)
2034        empty_format_spec(object)
2035        empty_format_spec(None)
2036
2037        # TypeError because self.__format__ returns the wrong type
2038        class BadFormatResult:
2039            def __format__(self, format_spec):
2040                return 1.0
2041        self.assertRaises(TypeError, format, BadFormatResult(), "")
2042
2043        # TypeError because format_spec is not unicode or str
2044        self.assertRaises(TypeError, format, object(), 4)
2045        self.assertRaises(TypeError, format, object(), object())
2046
2047        # tests for object.__format__ really belong elsewhere, but
2048        #  there's no good place to put them
2049        x = object().__format__('')
2050        self.assertTrue(x.startswith('<object object at'))
2051
2052        # first argument to object.__format__ must be string
2053        self.assertRaises(TypeError, object().__format__, 3)
2054        self.assertRaises(TypeError, object().__format__, object())
2055        self.assertRaises(TypeError, object().__format__, None)
2056
2057        # --------------------------------------------------------------------
2058        # Issue #7994: object.__format__ with a non-empty format string is
2059        # disallowed
2060        class A:
2061            def __format__(self, fmt_str):
2062                return format('', fmt_str)
2063
2064        self.assertEqual(format(A()), '')
2065        self.assertEqual(format(A(), ''), '')
2066        self.assertEqual(format(A(), 's'), '')
2067
2068        class B:
2069            pass
2070
2071        class C(object):
2072            pass
2073
2074        for cls in [object, B, C]:
2075            obj = cls()
2076            self.assertEqual(format(obj), str(obj))
2077            self.assertEqual(format(obj, ''), str(obj))
2078            with self.assertRaisesRegex(TypeError,
2079                                        r'\b%s\b' % re.escape(cls.__name__)):
2080                format(obj, 's')
2081        # --------------------------------------------------------------------
2082
2083        # make sure we can take a subclass of str as a format spec
2084        class DerivedFromStr(str): pass
2085        self.assertEqual(format(0, DerivedFromStr('10')), '         0')
2086
2087    def test_bin(self):
2088        self.assertEqual(bin(0), '0b0')
2089        self.assertEqual(bin(1), '0b1')
2090        self.assertEqual(bin(-1), '-0b1')
2091        self.assertEqual(bin(2**65), '0b1' + '0' * 65)
2092        self.assertEqual(bin(2**65-1), '0b' + '1' * 65)
2093        self.assertEqual(bin(-(2**65)), '-0b1' + '0' * 65)
2094        self.assertEqual(bin(-(2**65-1)), '-0b' + '1' * 65)
2095
2096    def test_bytearray_translate(self):
2097        x = bytearray(b"abc")
2098        self.assertRaises(ValueError, x.translate, b"1", 1)
2099        self.assertRaises(TypeError, x.translate, b"1"*256, 1)
2100
2101    def test_bytearray_extend_error(self):
2102        array = bytearray()
2103        bad_iter = map(int, "X")
2104        self.assertRaises(ValueError, array.extend, bad_iter)
2105
2106    def test_bytearray_join_with_misbehaving_iterator(self):
2107        # Issue #112625
2108        array = bytearray(b',')
2109        def iterator():
2110            array.clear()
2111            yield b'A'
2112            yield b'B'
2113        self.assertRaises(BufferError, array.join, iterator())
2114
2115    def test_bytearray_join_with_custom_iterator(self):
2116        # Issue #112625
2117        array = bytearray(b',')
2118        def iterator():
2119            yield b'A'
2120            yield b'B'
2121        self.assertEqual(bytearray(b'A,B'), array.join(iterator()))
2122
2123    def test_construct_singletons(self):
2124        for const in None, Ellipsis, NotImplemented:
2125            tp = type(const)
2126            self.assertIs(tp(), const)
2127            self.assertRaises(TypeError, tp, 1, 2)
2128            self.assertRaises(TypeError, tp, a=1, b=2)
2129
2130    def test_warning_notimplemented(self):
2131        # Issue #35712: NotImplemented is a sentinel value that should never
2132        # be evaluated in a boolean context (virtually all such use cases
2133        # are a result of accidental misuse implementing rich comparison
2134        # operations in terms of one another).
2135        # For the time being, it will continue to evaluate as a true value, but
2136        # issue a deprecation warning (with the eventual intent to make it
2137        # a TypeError).
2138        self.assertWarns(DeprecationWarning, bool, NotImplemented)
2139        with self.assertWarns(DeprecationWarning):
2140            self.assertTrue(NotImplemented)
2141        with self.assertWarns(DeprecationWarning):
2142            self.assertFalse(not NotImplemented)
2143
2144    def test_singleton_attribute_access(self):
2145        for singleton in (NotImplemented, Ellipsis):
2146            with self.subTest(singleton):
2147                self.assertIs(type(singleton), singleton.__class__)
2148                self.assertIs(type(singleton).__class__, type)
2149
2150                # Missing instance attributes:
2151                with self.assertRaises(AttributeError):
2152                    singleton.prop = 1
2153                with self.assertRaises(AttributeError):
2154                    singleton.prop
2155
2156                # Missing class attributes:
2157                with self.assertRaises(TypeError):
2158                    type(singleton).prop = 1
2159                with self.assertRaises(AttributeError):
2160                    type(singleton).prop
2161
2162
2163class TestBreakpoint(unittest.TestCase):
2164    def setUp(self):
2165        # These tests require a clean slate environment.  For example, if the
2166        # test suite is run with $PYTHONBREAKPOINT set to something else, it
2167        # will mess up these tests.  Similarly for sys.breakpointhook.
2168        # Cleaning the slate here means you can't use breakpoint() to debug
2169        # these tests, but I think that's okay.  Just use pdb.set_trace() if
2170        # you must.
2171        self.resources = ExitStack()
2172        self.addCleanup(self.resources.close)
2173        self.env = self.resources.enter_context(EnvironmentVarGuard())
2174        del self.env['PYTHONBREAKPOINT']
2175        self.resources.enter_context(
2176            swap_attr(sys, 'breakpointhook', sys.__breakpointhook__))
2177
2178    def test_breakpoint(self):
2179        with patch('pdb.set_trace') as mock:
2180            breakpoint()
2181        mock.assert_called_once()
2182
2183    def test_breakpoint_with_breakpointhook_set(self):
2184        my_breakpointhook = MagicMock()
2185        sys.breakpointhook = my_breakpointhook
2186        breakpoint()
2187        my_breakpointhook.assert_called_once_with()
2188
2189    def test_breakpoint_with_breakpointhook_reset(self):
2190        my_breakpointhook = MagicMock()
2191        sys.breakpointhook = my_breakpointhook
2192        breakpoint()
2193        my_breakpointhook.assert_called_once_with()
2194        # Reset the hook and it will not be called again.
2195        sys.breakpointhook = sys.__breakpointhook__
2196        with patch('pdb.set_trace') as mock:
2197            breakpoint()
2198            mock.assert_called_once_with()
2199        my_breakpointhook.assert_called_once_with()
2200
2201    def test_breakpoint_with_args_and_keywords(self):
2202        my_breakpointhook = MagicMock()
2203        sys.breakpointhook = my_breakpointhook
2204        breakpoint(1, 2, 3, four=4, five=5)
2205        my_breakpointhook.assert_called_once_with(1, 2, 3, four=4, five=5)
2206
2207    def test_breakpoint_with_passthru_error(self):
2208        def my_breakpointhook():
2209            pass
2210        sys.breakpointhook = my_breakpointhook
2211        self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5)
2212
2213    @unittest.skipIf(sys.flags.ignore_environment, '-E was given')
2214    def test_envar_good_path_builtin(self):
2215        self.env['PYTHONBREAKPOINT'] = 'int'
2216        with patch('builtins.int') as mock:
2217            breakpoint('7')
2218            mock.assert_called_once_with('7')
2219
2220    @unittest.skipIf(sys.flags.ignore_environment, '-E was given')
2221    def test_envar_good_path_other(self):
2222        self.env['PYTHONBREAKPOINT'] = 'sys.exit'
2223        with patch('sys.exit') as mock:
2224            breakpoint()
2225            mock.assert_called_once_with()
2226
2227    @unittest.skipIf(sys.flags.ignore_environment, '-E was given')
2228    def test_envar_good_path_noop_0(self):
2229        self.env['PYTHONBREAKPOINT'] = '0'
2230        with patch('pdb.set_trace') as mock:
2231            breakpoint()
2232            mock.assert_not_called()
2233
2234    def test_envar_good_path_empty_string(self):
2235        # PYTHONBREAKPOINT='' is the same as it not being set.
2236        self.env['PYTHONBREAKPOINT'] = ''
2237        with patch('pdb.set_trace') as mock:
2238            breakpoint()
2239            mock.assert_called_once_with()
2240
2241    @unittest.skipIf(sys.flags.ignore_environment, '-E was given')
2242    def test_envar_unimportable(self):
2243        for envar in (
2244                '.', '..', '.foo', 'foo.', '.int', 'int.',
2245                '.foo.bar', '..foo.bar', '/./',
2246                'nosuchbuiltin',
2247                'nosuchmodule.nosuchcallable',
2248                ):
2249            with self.subTest(envar=envar):
2250                self.env['PYTHONBREAKPOINT'] = envar
2251                mock = self.resources.enter_context(patch('pdb.set_trace'))
2252                w = self.resources.enter_context(check_warnings(quiet=True))
2253                breakpoint()
2254                self.assertEqual(
2255                    str(w.message),
2256                    f'Ignoring unimportable $PYTHONBREAKPOINT: "{envar}"')
2257                self.assertEqual(w.category, RuntimeWarning)
2258                mock.assert_not_called()
2259
2260    def test_envar_ignored_when_hook_is_set(self):
2261        self.env['PYTHONBREAKPOINT'] = 'sys.exit'
2262        with patch('sys.exit') as mock:
2263            sys.breakpointhook = int
2264            breakpoint()
2265            mock.assert_not_called()
2266
2267    def test_runtime_error_when_hook_is_lost(self):
2268        del sys.breakpointhook
2269        with self.assertRaises(RuntimeError):
2270            breakpoint()
2271
2272
2273@unittest.skipUnless(pty, "the pty and signal modules must be available")
2274class PtyTests(unittest.TestCase):
2275    """Tests that use a pseudo terminal to guarantee stdin and stdout are
2276    terminals in the test environment"""
2277
2278    @staticmethod
2279    def handle_sighup(signum, frame):
2280        # bpo-40140: if the process is the session leader, os.close(fd)
2281        # of "pid, fd = pty.fork()" can raise SIGHUP signal:
2282        # just ignore the signal.
2283        pass
2284
2285    def run_child(self, child, terminal_input):
2286        old_sighup = signal.signal(signal.SIGHUP, self.handle_sighup)
2287        try:
2288            return self._run_child(child, terminal_input)
2289        finally:
2290            signal.signal(signal.SIGHUP, old_sighup)
2291
2292    def _run_child(self, child, terminal_input):
2293        r, w = os.pipe()  # Pipe test results from child back to parent
2294        try:
2295            pid, fd = pty.fork()
2296        except (OSError, AttributeError) as e:
2297            os.close(r)
2298            os.close(w)
2299            self.skipTest("pty.fork() raised {}".format(e))
2300            raise
2301
2302        if pid == 0:
2303            # Child
2304            try:
2305                os.close(r)
2306                with open(w, "w") as wpipe:
2307                    child(wpipe)
2308            except:
2309                traceback.print_exc()
2310            finally:
2311                # We don't want to return to unittest...
2312                os._exit(0)
2313
2314        # Parent
2315        os.close(w)
2316        os.write(fd, terminal_input)
2317
2318        # Get results from the pipe
2319        with open(r, encoding="utf-8") as rpipe:
2320            lines = []
2321            while True:
2322                line = rpipe.readline().strip()
2323                if line == "":
2324                    # The other end was closed => the child exited
2325                    break
2326                lines.append(line)
2327
2328        # Check the result was got and corresponds to the user's terminal input
2329        if len(lines) != 2:
2330            # Something went wrong, try to get at stderr
2331            # Beware of Linux raising EIO when the slave is closed
2332            child_output = bytearray()
2333            while True:
2334                try:
2335                    chunk = os.read(fd, 3000)
2336                except OSError:  # Assume EIO
2337                    break
2338                if not chunk:
2339                    break
2340                child_output.extend(chunk)
2341            os.close(fd)
2342            child_output = child_output.decode("ascii", "ignore")
2343            self.fail("got %d lines in pipe but expected 2, child output was:\n%s"
2344                      % (len(lines), child_output))
2345
2346        # bpo-40155: Close the PTY before waiting for the child process
2347        # completion, otherwise the child process hangs on AIX.
2348        os.close(fd)
2349
2350        support.wait_process(pid, exitcode=0)
2351
2352        return lines
2353
2354    def check_input_tty(self, prompt, terminal_input, stdio_encoding=None, *,
2355                        expected=None,
2356                        stdin_errors='surrogateescape',
2357                        stdout_errors='replace'):
2358        if not sys.stdin.isatty() or not sys.stdout.isatty():
2359            self.skipTest("stdin and stdout must be ttys")
2360        def child(wpipe):
2361            # Check the error handlers are accounted for
2362            if stdio_encoding:
2363                sys.stdin = io.TextIOWrapper(sys.stdin.detach(),
2364                                             encoding=stdio_encoding,
2365                                             errors=stdin_errors)
2366                sys.stdout = io.TextIOWrapper(sys.stdout.detach(),
2367                                              encoding=stdio_encoding,
2368                                              errors=stdout_errors)
2369            print("tty =", sys.stdin.isatty() and sys.stdout.isatty(), file=wpipe)
2370            try:
2371                print(ascii(input(prompt)), file=wpipe)
2372            except BaseException as e:
2373                print(ascii(f'{e.__class__.__name__}: {e!s}'), file=wpipe)
2374        with self.detach_readline():
2375            lines = self.run_child(child, terminal_input + b"\r\n")
2376        # Check we did exercise the GNU readline path
2377        self.assertIn(lines[0], {'tty = True', 'tty = False'})
2378        if lines[0] != 'tty = True':
2379            self.skipTest("standard IO in should have been a tty")
2380        input_result = eval(lines[1])   # ascii() -> eval() roundtrip
2381        if expected is None:
2382            if stdio_encoding:
2383                expected = terminal_input.decode(stdio_encoding, 'surrogateescape')
2384            else:
2385                expected = terminal_input.decode(sys.stdin.encoding)  # what else?
2386        self.assertEqual(input_result, expected)
2387
2388    @contextlib.contextmanager
2389    def detach_readline(self):
2390        # bpo-13886: When the readline module is loaded, PyOS_Readline() uses
2391        # the readline implementation. In some cases, the Python readline
2392        # callback rlhandler() is called by readline with a string without
2393        # non-ASCII characters.
2394        # Unlink readline temporarily from PyOS_Readline() for those tests,
2395        # since test_builtin is not intended to test
2396        # the readline module, but the builtins module.
2397        if "readline" in sys.modules:
2398            c = import_module("ctypes")
2399            fp_api = "PyOS_ReadlineFunctionPointer"
2400            prev_value = c.c_void_p.in_dll(c.pythonapi, fp_api).value
2401            c.c_void_p.in_dll(c.pythonapi, fp_api).value = None
2402            try:
2403                yield
2404            finally:
2405                c.c_void_p.in_dll(c.pythonapi, fp_api).value = prev_value
2406        else:
2407            yield
2408
2409    def test_input_tty(self):
2410        # Test input() functionality when wired to a tty
2411        self.check_input_tty("prompt", b"quux")
2412
2413    def test_input_tty_non_ascii(self):
2414        # Check stdin/stdout encoding is used when invoking PyOS_Readline()
2415        self.check_input_tty("prompté", b"quux\xc3\xa9", "utf-8")
2416
2417    def test_input_tty_non_ascii_unicode_errors(self):
2418        # Check stdin/stdout error handler is used when invoking PyOS_Readline()
2419        self.check_input_tty("prompté", b"quux\xe9", "ascii")
2420
2421    def test_input_tty_null_in_prompt(self):
2422        self.check_input_tty("prompt\0", b"",
2423                expected='ValueError: input: prompt string cannot contain '
2424                         'null characters')
2425
2426    def test_input_tty_nonencodable_prompt(self):
2427        self.check_input_tty("prompté", b"quux", "ascii", stdout_errors='strict',
2428                expected="UnicodeEncodeError: 'ascii' codec can't encode "
2429                         "character '\\xe9' in position 6: ordinal not in "
2430                         "range(128)")
2431
2432    def test_input_tty_nondecodable_input(self):
2433        self.check_input_tty("prompt", b"quux\xe9", "ascii", stdin_errors='strict',
2434                expected="UnicodeDecodeError: 'ascii' codec can't decode "
2435                         "byte 0xe9 in position 4: ordinal not in "
2436                         "range(128)")
2437
2438    def test_input_no_stdout_fileno(self):
2439        # Issue #24402: If stdin is the original terminal but stdout.fileno()
2440        # fails, do not use the original stdout file descriptor
2441        def child(wpipe):
2442            print("stdin.isatty():", sys.stdin.isatty(), file=wpipe)
2443            sys.stdout = io.StringIO()  # Does not support fileno()
2444            input("prompt")
2445            print("captured:", ascii(sys.stdout.getvalue()), file=wpipe)
2446        lines = self.run_child(child, b"quux\r")
2447        expected = (
2448            "stdin.isatty(): True",
2449            "captured: 'prompt'",
2450        )
2451        self.assertSequenceEqual(lines, expected)
2452
2453class TestSorted(unittest.TestCase):
2454
2455    def test_basic(self):
2456        data = list(range(100))
2457        copy = data[:]
2458        random.shuffle(copy)
2459        self.assertEqual(data, sorted(copy))
2460        self.assertNotEqual(data, copy)
2461
2462        data.reverse()
2463        random.shuffle(copy)
2464        self.assertEqual(data, sorted(copy, key=lambda x: -x))
2465        self.assertNotEqual(data, copy)
2466        random.shuffle(copy)
2467        self.assertEqual(data, sorted(copy, reverse=True))
2468        self.assertNotEqual(data, copy)
2469
2470    def test_bad_arguments(self):
2471        # Issue #29327: The first argument is positional-only.
2472        sorted([])
2473        with self.assertRaises(TypeError):
2474            sorted(iterable=[])
2475        # Other arguments are keyword-only
2476        sorted([], key=None)
2477        with self.assertRaises(TypeError):
2478            sorted([], None)
2479
2480    def test_inputtypes(self):
2481        s = 'abracadabra'
2482        types = [list, tuple, str]
2483        for T in types:
2484            self.assertEqual(sorted(s), sorted(T(s)))
2485
2486        s = ''.join(set(s))  # unique letters only
2487        types = [str, set, frozenset, list, tuple, dict.fromkeys]
2488        for T in types:
2489            self.assertEqual(sorted(s), sorted(T(s)))
2490
2491    def test_baddecorator(self):
2492        data = 'The quick Brown fox Jumped over The lazy Dog'.split()
2493        self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0)
2494
2495
2496class ShutdownTest(unittest.TestCase):
2497
2498    def test_cleanup(self):
2499        # Issue #19255: builtins are still available at shutdown
2500        code = """if 1:
2501            import builtins
2502            import sys
2503
2504            class C:
2505                def __del__(self):
2506                    print("before")
2507                    # Check that builtins still exist
2508                    len(())
2509                    print("after")
2510
2511            c = C()
2512            # Make this module survive until builtins and sys are cleaned
2513            builtins.here = sys.modules[__name__]
2514            sys.here = sys.modules[__name__]
2515            # Create a reference loop so that this module needs to go
2516            # through a GC phase.
2517            here = sys.modules[__name__]
2518            """
2519        # Issue #20599: Force ASCII encoding to get a codec implemented in C,
2520        # otherwise the codec may be unloaded before C.__del__() is called, and
2521        # so print("before") fails because the codec cannot be used to encode
2522        # "before" to sys.stdout.encoding. For example, on Windows,
2523        # sys.stdout.encoding is the OEM code page and these code pages are
2524        # implemented in Python
2525        rc, out, err = assert_python_ok("-c", code,
2526                                        PYTHONIOENCODING="ascii")
2527        self.assertEqual(["before", "after"], out.decode().splitlines())
2528
2529
2530@cpython_only
2531class ImmortalTests(unittest.TestCase):
2532
2533    if sys.maxsize < (1 << 32):
2534        IMMORTAL_REFCOUNT = (1 << 30) - 1
2535    else:
2536        IMMORTAL_REFCOUNT = (1 << 32) - 1
2537
2538    IMMORTALS = (None, True, False, Ellipsis, NotImplemented, *range(-5, 257))
2539
2540    def assert_immortal(self, immortal):
2541        with self.subTest(immortal):
2542            self.assertEqual(sys.getrefcount(immortal), self.IMMORTAL_REFCOUNT)
2543
2544    def test_immortals(self):
2545        for immortal in self.IMMORTALS:
2546            self.assert_immortal(immortal)
2547
2548    def test_list_repeat_respect_immortality(self):
2549        refs = list(self.IMMORTALS) * 42
2550        for immortal in self.IMMORTALS:
2551            self.assert_immortal(immortal)
2552
2553    def test_tuple_repeat_respect_immortality(self):
2554        refs = tuple(self.IMMORTALS) * 42
2555        for immortal in self.IMMORTALS:
2556            self.assert_immortal(immortal)
2557
2558
2559class TestType(unittest.TestCase):
2560    def test_new_type(self):
2561        A = type('A', (), {})
2562        self.assertEqual(A.__name__, 'A')
2563        self.assertEqual(A.__qualname__, 'A')
2564        self.assertEqual(A.__module__, __name__)
2565        self.assertEqual(A.__bases__, (object,))
2566        self.assertIs(A.__base__, object)
2567        self.assertNotIn('__firstlineno__', A.__dict__)
2568        x = A()
2569        self.assertIs(type(x), A)
2570        self.assertIs(x.__class__, A)
2571
2572        class B:
2573            def ham(self):
2574                return 'ham%d' % self
2575        C = type('C', (B, int), {'spam': lambda self: 'spam%s' % self})
2576        self.assertEqual(C.__name__, 'C')
2577        self.assertEqual(C.__qualname__, 'C')
2578        self.assertEqual(C.__module__, __name__)
2579        self.assertEqual(C.__bases__, (B, int))
2580        self.assertIs(C.__base__, int)
2581        self.assertIn('spam', C.__dict__)
2582        self.assertNotIn('ham', C.__dict__)
2583        x = C(42)
2584        self.assertEqual(x, 42)
2585        self.assertIs(type(x), C)
2586        self.assertIs(x.__class__, C)
2587        self.assertEqual(x.ham(), 'ham42')
2588        self.assertEqual(x.spam(), 'spam42')
2589        self.assertEqual(x.to_bytes(2, 'little'), b'\x2a\x00')
2590
2591    def test_type_nokwargs(self):
2592        with self.assertRaises(TypeError):
2593            type('a', (), {}, x=5)
2594        with self.assertRaises(TypeError):
2595            type('a', (), dict={})
2596
2597    def test_type_name(self):
2598        for name in 'A', '\xc4', '\U0001f40d', 'B.A', '42', '':
2599            with self.subTest(name=name):
2600                A = type(name, (), {})
2601                self.assertEqual(A.__name__, name)
2602                self.assertEqual(A.__qualname__, name)
2603                self.assertEqual(A.__module__, __name__)
2604        with self.assertRaises(ValueError):
2605            type('A\x00B', (), {})
2606        with self.assertRaises(UnicodeEncodeError):
2607            type('A\udcdcB', (), {})
2608        with self.assertRaises(TypeError):
2609            type(b'A', (), {})
2610
2611        C = type('C', (), {})
2612        for name in 'A', '\xc4', '\U0001f40d', 'B.A', '42', '':
2613            with self.subTest(name=name):
2614                C.__name__ = name
2615                self.assertEqual(C.__name__, name)
2616                self.assertEqual(C.__qualname__, 'C')
2617                self.assertEqual(C.__module__, __name__)
2618
2619        A = type('C', (), {})
2620        with self.assertRaises(ValueError):
2621            A.__name__ = 'A\x00B'
2622        self.assertEqual(A.__name__, 'C')
2623        with self.assertRaises(UnicodeEncodeError):
2624            A.__name__ = 'A\udcdcB'
2625        self.assertEqual(A.__name__, 'C')
2626        with self.assertRaises(TypeError):
2627            A.__name__ = b'A'
2628        self.assertEqual(A.__name__, 'C')
2629
2630    def test_type_qualname(self):
2631        A = type('A', (), {'__qualname__': 'B.C'})
2632        self.assertEqual(A.__name__, 'A')
2633        self.assertEqual(A.__qualname__, 'B.C')
2634        self.assertEqual(A.__module__, __name__)
2635        with self.assertRaises(TypeError):
2636            type('A', (), {'__qualname__': b'B'})
2637        self.assertEqual(A.__qualname__, 'B.C')
2638
2639        A.__qualname__ = 'D.E'
2640        self.assertEqual(A.__name__, 'A')
2641        self.assertEqual(A.__qualname__, 'D.E')
2642        with self.assertRaises(TypeError):
2643            A.__qualname__ = b'B'
2644        self.assertEqual(A.__qualname__, 'D.E')
2645
2646    def test_type_firstlineno(self):
2647        A = type('A', (), {'__firstlineno__': 42})
2648        self.assertEqual(A.__name__, 'A')
2649        self.assertEqual(A.__module__, __name__)
2650        self.assertEqual(A.__dict__['__firstlineno__'], 42)
2651        A.__module__ = 'testmodule'
2652        self.assertEqual(A.__module__, 'testmodule')
2653        self.assertNotIn('__firstlineno__', A.__dict__)
2654        A.__firstlineno__ = 43
2655        self.assertEqual(A.__dict__['__firstlineno__'], 43)
2656
2657    def test_type_typeparams(self):
2658        class A[T]:
2659            pass
2660        T, = A.__type_params__
2661        self.assertIsInstance(T, typing.TypeVar)
2662        A.__type_params__ = "whatever"
2663        self.assertEqual(A.__type_params__, "whatever")
2664        with self.assertRaises(TypeError):
2665            del A.__type_params__
2666        self.assertEqual(A.__type_params__, "whatever")
2667
2668    def test_type_doc(self):
2669        for doc in 'x', '\xc4', '\U0001f40d', 'x\x00y', b'x', 42, None:
2670            A = type('A', (), {'__doc__': doc})
2671            self.assertEqual(A.__doc__, doc)
2672        with self.assertRaises(UnicodeEncodeError):
2673            type('A', (), {'__doc__': 'x\udcdcy'})
2674
2675        A = type('A', (), {})
2676        self.assertEqual(A.__doc__, None)
2677        for doc in 'x', '\xc4', '\U0001f40d', 'x\x00y', 'x\udcdcy', b'x', 42, None:
2678            A.__doc__ = doc
2679            self.assertEqual(A.__doc__, doc)
2680
2681    def test_bad_args(self):
2682        with self.assertRaises(TypeError):
2683            type()
2684        with self.assertRaises(TypeError):
2685            type('A', ())
2686        with self.assertRaises(TypeError):
2687            type('A', (), {}, ())
2688        with self.assertRaises(TypeError):
2689            type('A', (), dict={})
2690        with self.assertRaises(TypeError):
2691            type('A', [], {})
2692        with self.assertRaises(TypeError):
2693            type('A', (), types.MappingProxyType({}))
2694        with self.assertRaises(TypeError):
2695            type('A', (None,), {})
2696        with self.assertRaises(TypeError):
2697            type('A', (bool,), {})
2698        with self.assertRaises(TypeError):
2699            type('A', (int, str), {})
2700
2701    def test_bad_slots(self):
2702        with self.assertRaises(TypeError):
2703            type('A', (), {'__slots__': b'x'})
2704        with self.assertRaises(TypeError):
2705            type('A', (int,), {'__slots__': 'x'})
2706        with self.assertRaises(TypeError):
2707            type('A', (), {'__slots__': ''})
2708        with self.assertRaises(TypeError):
2709            type('A', (), {'__slots__': '42'})
2710        with self.assertRaises(TypeError):
2711            type('A', (), {'__slots__': 'x\x00y'})
2712        with self.assertRaises(ValueError):
2713            type('A', (), {'__slots__': 'x', 'x': 0})
2714        with self.assertRaises(TypeError):
2715            type('A', (), {'__slots__': ('__dict__', '__dict__')})
2716        with self.assertRaises(TypeError):
2717            type('A', (), {'__slots__': ('__weakref__', '__weakref__')})
2718
2719        class B:
2720            pass
2721        with self.assertRaises(TypeError):
2722            type('A', (B,), {'__slots__': '__dict__'})
2723        with self.assertRaises(TypeError):
2724            type('A', (B,), {'__slots__': '__weakref__'})
2725
2726    def test_namespace_order(self):
2727        # bpo-34320: namespace should preserve order
2728        od = collections.OrderedDict([('a', 1), ('b', 2)])
2729        od.move_to_end('a')
2730        expected = list(od.items())
2731
2732        C = type('C', (), od)
2733        self.assertEqual(list(C.__dict__.items())[:2], [('b', 2), ('a', 1)])
2734
2735
2736def load_tests(loader, tests, pattern):
2737    from doctest import DocTestSuite
2738    tests.addTest(DocTestSuite(builtins))
2739    return tests
2740
2741if __name__ == "__main__":
2742    unittest.main()
2743