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