(root)/
Python-3.11.7/
Lib/
test/
test_sys.py
       1  import builtins
       2  import codecs
       3  import gc
       4  import locale
       5  import operator
       6  import os
       7  import struct
       8  import subprocess
       9  import sys
      10  import sysconfig
      11  import test.support
      12  from test import support
      13  from test.support import os_helper
      14  from test.support.script_helper import assert_python_ok, assert_python_failure
      15  from test.support import threading_helper
      16  from test.support import import_helper
      17  import textwrap
      18  import unittest
      19  import warnings
      20  
      21  
      22  # count the number of test runs, used to create unique
      23  # strings to intern in test_intern()
      24  INTERN_NUMRUNS = 0
      25  
      26  DICT_KEY_STRUCT_FORMAT = 'n2BI2n'
      27  
      28  class ESC[4;38;5;81mDisplayHookTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
      29  
      30      def test_original_displayhook(self):
      31          dh = sys.__displayhook__
      32  
      33          with support.captured_stdout() as out:
      34              dh(42)
      35  
      36          self.assertEqual(out.getvalue(), "42\n")
      37          self.assertEqual(builtins._, 42)
      38  
      39          del builtins._
      40  
      41          with support.captured_stdout() as out:
      42              dh(None)
      43  
      44          self.assertEqual(out.getvalue(), "")
      45          self.assertTrue(not hasattr(builtins, "_"))
      46  
      47          # sys.displayhook() requires arguments
      48          self.assertRaises(TypeError, dh)
      49  
      50          stdout = sys.stdout
      51          try:
      52              del sys.stdout
      53              self.assertRaises(RuntimeError, dh, 42)
      54          finally:
      55              sys.stdout = stdout
      56  
      57      def test_lost_displayhook(self):
      58          displayhook = sys.displayhook
      59          try:
      60              del sys.displayhook
      61              code = compile("42", "<string>", "single")
      62              self.assertRaises(RuntimeError, eval, code)
      63          finally:
      64              sys.displayhook = displayhook
      65  
      66      def test_custom_displayhook(self):
      67          def baddisplayhook(obj):
      68              raise ValueError
      69  
      70          with support.swap_attr(sys, 'displayhook', baddisplayhook):
      71              code = compile("42", "<string>", "single")
      72              self.assertRaises(ValueError, eval, code)
      73  
      74  class ESC[4;38;5;81mActiveExceptionTests(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
      75      def test_exc_info_no_exception(self):
      76          self.assertEqual(sys.exc_info(), (None, None, None))
      77  
      78      def test_sys_exception_no_exception(self):
      79          self.assertEqual(sys.exception(), None)
      80  
      81      def test_exc_info_with_exception_instance(self):
      82          def f():
      83              raise ValueError(42)
      84  
      85          try:
      86              f()
      87          except Exception as e_:
      88              e = e_
      89              exc_info = sys.exc_info()
      90  
      91          self.assertIsInstance(e, ValueError)
      92          self.assertIs(exc_info[0], ValueError)
      93          self.assertIs(exc_info[1], e)
      94          self.assertIs(exc_info[2], e.__traceback__)
      95  
      96      def test_exc_info_with_exception_type(self):
      97          def f():
      98              raise ValueError
      99  
     100          try:
     101              f()
     102          except Exception as e_:
     103              e = e_
     104              exc_info = sys.exc_info()
     105  
     106          self.assertIsInstance(e, ValueError)
     107          self.assertIs(exc_info[0], ValueError)
     108          self.assertIs(exc_info[1], e)
     109          self.assertIs(exc_info[2], e.__traceback__)
     110  
     111      def test_sys_exception_with_exception_instance(self):
     112          def f():
     113              raise ValueError(42)
     114  
     115          try:
     116              f()
     117          except Exception as e_:
     118              e = e_
     119              exc = sys.exception()
     120  
     121          self.assertIsInstance(e, ValueError)
     122          self.assertIs(exc, e)
     123  
     124      def test_sys_exception_with_exception_type(self):
     125          def f():
     126              raise ValueError
     127  
     128          try:
     129              f()
     130          except Exception as e_:
     131              e = e_
     132              exc = sys.exception()
     133  
     134          self.assertIsInstance(e, ValueError)
     135          self.assertIs(exc, e)
     136  
     137  
     138  class ESC[4;38;5;81mExceptHookTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
     139  
     140      def test_original_excepthook(self):
     141          try:
     142              raise ValueError(42)
     143          except ValueError as exc:
     144              with support.captured_stderr() as err:
     145                  sys.__excepthook__(*sys.exc_info())
     146  
     147          self.assertTrue(err.getvalue().endswith("ValueError: 42\n"))
     148  
     149          self.assertRaises(TypeError, sys.__excepthook__)
     150  
     151      def test_excepthook_bytes_filename(self):
     152          # bpo-37467: sys.excepthook() must not crash if a filename
     153          # is a bytes string
     154          with warnings.catch_warnings():
     155              warnings.simplefilter('ignore', BytesWarning)
     156  
     157              try:
     158                  raise SyntaxError("msg", (b"bytes_filename", 123, 0, "text"))
     159              except SyntaxError as exc:
     160                  with support.captured_stderr() as err:
     161                      sys.__excepthook__(*sys.exc_info())
     162  
     163          err = err.getvalue()
     164          self.assertIn("""  File "b'bytes_filename'", line 123\n""", err)
     165          self.assertIn("""    text\n""", err)
     166          self.assertTrue(err.endswith("SyntaxError: msg\n"))
     167  
     168      def test_excepthook(self):
     169          with test.support.captured_output("stderr") as stderr:
     170              sys.excepthook(1, '1', 1)
     171          self.assertTrue("TypeError: print_exception(): Exception expected for " \
     172                           "value, str found" in stderr.getvalue())
     173  
     174      # FIXME: testing the code for a lost or replaced excepthook in
     175      # Python/pythonrun.c::PyErr_PrintEx() is tricky.
     176  
     177  
     178  class ESC[4;38;5;81mSysModuleTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
     179  
     180      def tearDown(self):
     181          test.support.reap_children()
     182  
     183      def test_exit(self):
     184          # call with two arguments
     185          self.assertRaises(TypeError, sys.exit, 42, 42)
     186  
     187          # call without argument
     188          with self.assertRaises(SystemExit) as cm:
     189              sys.exit()
     190          self.assertIsNone(cm.exception.code)
     191  
     192          rc, out, err = assert_python_ok('-c', 'import sys; sys.exit()')
     193          self.assertEqual(rc, 0)
     194          self.assertEqual(out, b'')
     195          self.assertEqual(err, b'')
     196  
     197          # call with integer argument
     198          with self.assertRaises(SystemExit) as cm:
     199              sys.exit(42)
     200          self.assertEqual(cm.exception.code, 42)
     201  
     202          # call with tuple argument with one entry
     203          # entry will be unpacked
     204          with self.assertRaises(SystemExit) as cm:
     205              sys.exit((42,))
     206          self.assertEqual(cm.exception.code, 42)
     207  
     208          # call with string argument
     209          with self.assertRaises(SystemExit) as cm:
     210              sys.exit("exit")
     211          self.assertEqual(cm.exception.code, "exit")
     212  
     213          # call with tuple argument with two entries
     214          with self.assertRaises(SystemExit) as cm:
     215              sys.exit((17, 23))
     216          self.assertEqual(cm.exception.code, (17, 23))
     217  
     218          # test that the exit machinery handles SystemExits properly
     219          rc, out, err = assert_python_failure('-c', 'raise SystemExit(47)')
     220          self.assertEqual(rc, 47)
     221          self.assertEqual(out, b'')
     222          self.assertEqual(err, b'')
     223  
     224          def check_exit_message(code, expected, **env_vars):
     225              rc, out, err = assert_python_failure('-c', code, **env_vars)
     226              self.assertEqual(rc, 1)
     227              self.assertEqual(out, b'')
     228              self.assertTrue(err.startswith(expected),
     229                  "%s doesn't start with %s" % (ascii(err), ascii(expected)))
     230  
     231          # test that stderr buffer is flushed before the exit message is written
     232          # into stderr
     233          check_exit_message(
     234              r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")',
     235              b"unflushed,message")
     236  
     237          # test that the exit message is written with backslashreplace error
     238          # handler to stderr
     239          check_exit_message(
     240              r'import sys; sys.exit("surrogates:\uDCFF")',
     241              b"surrogates:\\udcff")
     242  
     243          # test that the unicode message is encoded to the stderr encoding
     244          # instead of the default encoding (utf8)
     245          check_exit_message(
     246              r'import sys; sys.exit("h\xe9")',
     247              b"h\xe9", PYTHONIOENCODING='latin-1')
     248  
     249      def test_getdefaultencoding(self):
     250          self.assertRaises(TypeError, sys.getdefaultencoding, 42)
     251          # can't check more than the type, as the user might have changed it
     252          self.assertIsInstance(sys.getdefaultencoding(), str)
     253  
     254      # testing sys.settrace() is done in test_sys_settrace.py
     255      # testing sys.setprofile() is done in test_sys_setprofile.py
     256  
     257      def test_switchinterval(self):
     258          self.assertRaises(TypeError, sys.setswitchinterval)
     259          self.assertRaises(TypeError, sys.setswitchinterval, "a")
     260          self.assertRaises(ValueError, sys.setswitchinterval, -1.0)
     261          self.assertRaises(ValueError, sys.setswitchinterval, 0.0)
     262          orig = sys.getswitchinterval()
     263          # sanity check
     264          self.assertTrue(orig < 0.5, orig)
     265          try:
     266              for n in 0.00001, 0.05, 3.0, orig:
     267                  sys.setswitchinterval(n)
     268                  self.assertAlmostEqual(sys.getswitchinterval(), n)
     269          finally:
     270              sys.setswitchinterval(orig)
     271  
     272      def test_getrecursionlimit(self):
     273          limit = sys.getrecursionlimit()
     274          self.assertIsInstance(limit, int)
     275          self.assertGreater(limit, 1)
     276  
     277          self.assertRaises(TypeError, sys.getrecursionlimit, 42)
     278  
     279      def test_setrecursionlimit(self):
     280          old_limit = sys.getrecursionlimit()
     281          try:
     282              sys.setrecursionlimit(10_005)
     283              self.assertEqual(sys.getrecursionlimit(), 10_005)
     284  
     285              self.assertRaises(TypeError, sys.setrecursionlimit)
     286              self.assertRaises(ValueError, sys.setrecursionlimit, -42)
     287          finally:
     288              sys.setrecursionlimit(old_limit)
     289  
     290      def test_recursionlimit_recovery(self):
     291          if hasattr(sys, 'gettrace') and sys.gettrace():
     292              self.skipTest('fatal error if run with a trace function')
     293  
     294          old_limit = sys.getrecursionlimit()
     295          def f():
     296              f()
     297          try:
     298              for depth in (50, 75, 100, 250, 1000):
     299                  try:
     300                      sys.setrecursionlimit(depth)
     301                  except RecursionError:
     302                      # Issue #25274: The recursion limit is too low at the
     303                      # current recursion depth
     304                      continue
     305  
     306                  # Issue #5392: test stack overflow after hitting recursion
     307                  # limit twice
     308                  with self.assertRaises(RecursionError):
     309                      f()
     310                  with self.assertRaises(RecursionError):
     311                      f()
     312          finally:
     313              sys.setrecursionlimit(old_limit)
     314  
     315      @test.support.cpython_only
     316      def test_setrecursionlimit_to_depth(self):
     317          # Issue #25274: Setting a low recursion limit must be blocked if the
     318          # current recursion depth is already higher than limit.
     319  
     320          old_limit = sys.getrecursionlimit()
     321          try:
     322              depth = support.get_recursion_depth()
     323              with self.subTest(limit=sys.getrecursionlimit(), depth=depth):
     324                  # depth + 2 is OK
     325                  sys.setrecursionlimit(depth + 2)
     326  
     327                  # reset the limit to be able to call self.assertRaises()
     328                  # context manager
     329                  sys.setrecursionlimit(old_limit)
     330                  with self.assertRaises(RecursionError) as cm:
     331                      sys.setrecursionlimit(depth + 1)
     332                  self.assertRegex(str(cm.exception),
     333                                   "cannot set the recursion limit to [0-9]+ "
     334                                   "at the recursion depth [0-9]+: "
     335                                   "the limit is too low")
     336          finally:
     337              sys.setrecursionlimit(old_limit)
     338  
     339      def test_getwindowsversion(self):
     340          # Raise SkipTest if sys doesn't have getwindowsversion attribute
     341          test.support.get_attribute(sys, "getwindowsversion")
     342          v = sys.getwindowsversion()
     343          self.assertEqual(len(v), 5)
     344          self.assertIsInstance(v[0], int)
     345          self.assertIsInstance(v[1], int)
     346          self.assertIsInstance(v[2], int)
     347          self.assertIsInstance(v[3], int)
     348          self.assertIsInstance(v[4], str)
     349          self.assertRaises(IndexError, operator.getitem, v, 5)
     350          self.assertIsInstance(v.major, int)
     351          self.assertIsInstance(v.minor, int)
     352          self.assertIsInstance(v.build, int)
     353          self.assertIsInstance(v.platform, int)
     354          self.assertIsInstance(v.service_pack, str)
     355          self.assertIsInstance(v.service_pack_minor, int)
     356          self.assertIsInstance(v.service_pack_major, int)
     357          self.assertIsInstance(v.suite_mask, int)
     358          self.assertIsInstance(v.product_type, int)
     359          self.assertEqual(v[0], v.major)
     360          self.assertEqual(v[1], v.minor)
     361          self.assertEqual(v[2], v.build)
     362          self.assertEqual(v[3], v.platform)
     363          self.assertEqual(v[4], v.service_pack)
     364  
     365          # This is how platform.py calls it. Make sure tuple
     366          #  still has 5 elements
     367          maj, min, buildno, plat, csd = sys.getwindowsversion()
     368  
     369      def test_call_tracing(self):
     370          self.assertRaises(TypeError, sys.call_tracing, type, 2)
     371  
     372      @unittest.skipUnless(hasattr(sys, "setdlopenflags"),
     373                           'test needs sys.setdlopenflags()')
     374      def test_dlopenflags(self):
     375          self.assertTrue(hasattr(sys, "getdlopenflags"))
     376          self.assertRaises(TypeError, sys.getdlopenflags, 42)
     377          oldflags = sys.getdlopenflags()
     378          self.assertRaises(TypeError, sys.setdlopenflags)
     379          sys.setdlopenflags(oldflags+1)
     380          self.assertEqual(sys.getdlopenflags(), oldflags+1)
     381          sys.setdlopenflags(oldflags)
     382  
     383      @test.support.refcount_test
     384      def test_refcount(self):
     385          # n here must be a global in order for this test to pass while
     386          # tracing with a python function.  Tracing calls PyFrame_FastToLocals
     387          # which will add a copy of any locals to the frame object, causing
     388          # the reference count to increase by 2 instead of 1.
     389          global n
     390          self.assertRaises(TypeError, sys.getrefcount)
     391          c = sys.getrefcount(None)
     392          n = None
     393          self.assertEqual(sys.getrefcount(None), c+1)
     394          del n
     395          self.assertEqual(sys.getrefcount(None), c)
     396          if hasattr(sys, "gettotalrefcount"):
     397              self.assertIsInstance(sys.gettotalrefcount(), int)
     398  
     399      def test_getframe(self):
     400          self.assertRaises(TypeError, sys._getframe, 42, 42)
     401          self.assertRaises(ValueError, sys._getframe, 2000000000)
     402          self.assertTrue(
     403              SysModuleTest.test_getframe.__code__ \
     404              is sys._getframe().f_code
     405          )
     406  
     407      # sys._current_frames() is a CPython-only gimmick.
     408      @threading_helper.reap_threads
     409      @threading_helper.requires_working_threading()
     410      def test_current_frames(self):
     411          import threading
     412          import traceback
     413  
     414          # Spawn a thread that blocks at a known place.  Then the main
     415          # thread does sys._current_frames(), and verifies that the frames
     416          # returned make sense.
     417          entered_g = threading.Event()
     418          leave_g = threading.Event()
     419          thread_info = []  # the thread's id
     420  
     421          def f123():
     422              g456()
     423  
     424          def g456():
     425              thread_info.append(threading.get_ident())
     426              entered_g.set()
     427              leave_g.wait()
     428  
     429          t = threading.Thread(target=f123)
     430          t.start()
     431          entered_g.wait()
     432  
     433          # At this point, t has finished its entered_g.set(), although it's
     434          # impossible to guess whether it's still on that line or has moved on
     435          # to its leave_g.wait().
     436          self.assertEqual(len(thread_info), 1)
     437          thread_id = thread_info[0]
     438  
     439          d = sys._current_frames()
     440          for tid in d:
     441              self.assertIsInstance(tid, int)
     442              self.assertGreater(tid, 0)
     443  
     444          main_id = threading.get_ident()
     445          self.assertIn(main_id, d)
     446          self.assertIn(thread_id, d)
     447  
     448          # Verify that the captured main-thread frame is _this_ frame.
     449          frame = d.pop(main_id)
     450          self.assertTrue(frame is sys._getframe())
     451  
     452          # Verify that the captured thread frame is blocked in g456, called
     453          # from f123.  This is a little tricky, since various bits of
     454          # threading.py are also in the thread's call stack.
     455          frame = d.pop(thread_id)
     456          stack = traceback.extract_stack(frame)
     457          for i, (filename, lineno, funcname, sourceline) in enumerate(stack):
     458              if funcname == "f123":
     459                  break
     460          else:
     461              self.fail("didn't find f123() on thread's call stack")
     462  
     463          self.assertEqual(sourceline, "g456()")
     464  
     465          # And the next record must be for g456().
     466          filename, lineno, funcname, sourceline = stack[i+1]
     467          self.assertEqual(funcname, "g456")
     468          self.assertIn(sourceline, ["leave_g.wait()", "entered_g.set()"])
     469  
     470          # Reap the spawned thread.
     471          leave_g.set()
     472          t.join()
     473  
     474      @threading_helper.reap_threads
     475      @threading_helper.requires_working_threading()
     476      def test_current_exceptions(self):
     477          import threading
     478          import traceback
     479  
     480          # Spawn a thread that blocks at a known place.  Then the main
     481          # thread does sys._current_frames(), and verifies that the frames
     482          # returned make sense.
     483          entered_g = threading.Event()
     484          leave_g = threading.Event()
     485          thread_info = []  # the thread's id
     486  
     487          def f123():
     488              g456()
     489  
     490          def g456():
     491              thread_info.append(threading.get_ident())
     492              entered_g.set()
     493              while True:
     494                  try:
     495                      raise ValueError("oops")
     496                  except ValueError:
     497                      if leave_g.wait(timeout=support.LONG_TIMEOUT):
     498                          break
     499  
     500          t = threading.Thread(target=f123)
     501          t.start()
     502          entered_g.wait()
     503  
     504          # At this point, t has finished its entered_g.set(), although it's
     505          # impossible to guess whether it's still on that line or has moved on
     506          # to its leave_g.wait().
     507          self.assertEqual(len(thread_info), 1)
     508          thread_id = thread_info[0]
     509  
     510          d = sys._current_exceptions()
     511          for tid in d:
     512              self.assertIsInstance(tid, int)
     513              self.assertGreater(tid, 0)
     514  
     515          main_id = threading.get_ident()
     516          self.assertIn(main_id, d)
     517          self.assertIn(thread_id, d)
     518          self.assertEqual((None, None, None), d.pop(main_id))
     519  
     520          # Verify that the captured thread frame is blocked in g456, called
     521          # from f123.  This is a little tricky, since various bits of
     522          # threading.py are also in the thread's call stack.
     523          exc_type, exc_value, exc_tb = d.pop(thread_id)
     524          stack = traceback.extract_stack(exc_tb.tb_frame)
     525          for i, (filename, lineno, funcname, sourceline) in enumerate(stack):
     526              if funcname == "f123":
     527                  break
     528          else:
     529              self.fail("didn't find f123() on thread's call stack")
     530  
     531          self.assertEqual(sourceline, "g456()")
     532  
     533          # And the next record must be for g456().
     534          filename, lineno, funcname, sourceline = stack[i+1]
     535          self.assertEqual(funcname, "g456")
     536          self.assertTrue(sourceline.startswith("if leave_g.wait("))
     537  
     538          # Reap the spawned thread.
     539          leave_g.set()
     540          t.join()
     541  
     542      def test_attributes(self):
     543          self.assertIsInstance(sys.api_version, int)
     544          self.assertIsInstance(sys.argv, list)
     545          for arg in sys.argv:
     546              self.assertIsInstance(arg, str)
     547          self.assertIsInstance(sys.orig_argv, list)
     548          for arg in sys.orig_argv:
     549              self.assertIsInstance(arg, str)
     550          self.assertIn(sys.byteorder, ("little", "big"))
     551          self.assertIsInstance(sys.builtin_module_names, tuple)
     552          self.assertIsInstance(sys.copyright, str)
     553          self.assertIsInstance(sys.exec_prefix, str)
     554          self.assertIsInstance(sys.base_exec_prefix, str)
     555          self.assertIsInstance(sys.executable, str)
     556          self.assertEqual(len(sys.float_info), 11)
     557          self.assertEqual(sys.float_info.radix, 2)
     558          self.assertEqual(len(sys.int_info), 4)
     559          self.assertTrue(sys.int_info.bits_per_digit % 5 == 0)
     560          self.assertTrue(sys.int_info.sizeof_digit >= 1)
     561          self.assertGreaterEqual(sys.int_info.default_max_str_digits, 500)
     562          self.assertGreaterEqual(sys.int_info.str_digits_check_threshold, 100)
     563          self.assertGreater(sys.int_info.default_max_str_digits,
     564                             sys.int_info.str_digits_check_threshold)
     565          self.assertEqual(type(sys.int_info.bits_per_digit), int)
     566          self.assertEqual(type(sys.int_info.sizeof_digit), int)
     567          self.assertIsInstance(sys.int_info.default_max_str_digits, int)
     568          self.assertIsInstance(sys.int_info.str_digits_check_threshold, int)
     569          self.assertIsInstance(sys.hexversion, int)
     570  
     571          self.assertEqual(len(sys.hash_info), 9)
     572          self.assertLess(sys.hash_info.modulus, 2**sys.hash_info.width)
     573          # sys.hash_info.modulus should be a prime; we do a quick
     574          # probable primality test (doesn't exclude the possibility of
     575          # a Carmichael number)
     576          for x in range(1, 100):
     577              self.assertEqual(
     578                  pow(x, sys.hash_info.modulus-1, sys.hash_info.modulus),
     579                  1,
     580                  "sys.hash_info.modulus {} is a non-prime".format(
     581                      sys.hash_info.modulus)
     582                  )
     583          self.assertIsInstance(sys.hash_info.inf, int)
     584          self.assertIsInstance(sys.hash_info.nan, int)
     585          self.assertIsInstance(sys.hash_info.imag, int)
     586          algo = sysconfig.get_config_var("Py_HASH_ALGORITHM")
     587          if sys.hash_info.algorithm in {"fnv", "siphash13", "siphash24"}:
     588              self.assertIn(sys.hash_info.hash_bits, {32, 64})
     589              self.assertIn(sys.hash_info.seed_bits, {32, 64, 128})
     590  
     591              if algo == 1:
     592                  self.assertEqual(sys.hash_info.algorithm, "siphash24")
     593              elif algo == 2:
     594                  self.assertEqual(sys.hash_info.algorithm, "fnv")
     595              elif algo == 3:
     596                  self.assertEqual(sys.hash_info.algorithm, "siphash13")
     597              else:
     598                  self.assertIn(sys.hash_info.algorithm, {"fnv", "siphash13", "siphash24"})
     599          else:
     600              # PY_HASH_EXTERNAL
     601              self.assertEqual(algo, 0)
     602          self.assertGreaterEqual(sys.hash_info.cutoff, 0)
     603          self.assertLess(sys.hash_info.cutoff, 8)
     604  
     605          self.assertIsInstance(sys.maxsize, int)
     606          self.assertIsInstance(sys.maxunicode, int)
     607          self.assertEqual(sys.maxunicode, 0x10FFFF)
     608          self.assertIsInstance(sys.platform, str)
     609          self.assertIsInstance(sys.prefix, str)
     610          self.assertIsInstance(sys.base_prefix, str)
     611          self.assertIsInstance(sys.platlibdir, str)
     612          self.assertIsInstance(sys.version, str)
     613          vi = sys.version_info
     614          self.assertIsInstance(vi[:], tuple)
     615          self.assertEqual(len(vi), 5)
     616          self.assertIsInstance(vi[0], int)
     617          self.assertIsInstance(vi[1], int)
     618          self.assertIsInstance(vi[2], int)
     619          self.assertIn(vi[3], ("alpha", "beta", "candidate", "final"))
     620          self.assertIsInstance(vi[4], int)
     621          self.assertIsInstance(vi.major, int)
     622          self.assertIsInstance(vi.minor, int)
     623          self.assertIsInstance(vi.micro, int)
     624          self.assertIn(vi.releaselevel, ("alpha", "beta", "candidate", "final"))
     625          self.assertIsInstance(vi.serial, int)
     626          self.assertEqual(vi[0], vi.major)
     627          self.assertEqual(vi[1], vi.minor)
     628          self.assertEqual(vi[2], vi.micro)
     629          self.assertEqual(vi[3], vi.releaselevel)
     630          self.assertEqual(vi[4], vi.serial)
     631          self.assertTrue(vi > (1,0,0))
     632          self.assertIsInstance(sys.float_repr_style, str)
     633          self.assertIn(sys.float_repr_style, ('short', 'legacy'))
     634          if not sys.platform.startswith('win'):
     635              self.assertIsInstance(sys.abiflags, str)
     636  
     637      def test_thread_info(self):
     638          info = sys.thread_info
     639          self.assertEqual(len(info), 3)
     640          self.assertIn(info.name, ('nt', 'pthread', 'pthread-stubs', 'solaris', None))
     641          self.assertIn(info.lock, ('semaphore', 'mutex+cond', None))
     642          if sys.platform.startswith(("linux", "freebsd")):
     643              self.assertEqual(info.name, "pthread")
     644          elif sys.platform == "win32":
     645              self.assertEqual(info.name, "nt")
     646          elif sys.platform == "emscripten":
     647              self.assertIn(info.name, {"pthread", "pthread-stubs"})
     648          elif sys.platform == "wasi":
     649              self.assertEqual(info.name, "pthread-stubs")
     650  
     651      @unittest.skipUnless(support.is_emscripten, "only available on Emscripten")
     652      def test_emscripten_info(self):
     653          self.assertEqual(len(sys._emscripten_info), 4)
     654          self.assertIsInstance(sys._emscripten_info.emscripten_version, tuple)
     655          self.assertIsInstance(sys._emscripten_info.runtime, (str, type(None)))
     656          self.assertIsInstance(sys._emscripten_info.pthreads, bool)
     657          self.assertIsInstance(sys._emscripten_info.shared_memory, bool)
     658  
     659      def test_43581(self):
     660          # Can't use sys.stdout, as this is a StringIO object when
     661          # the test runs under regrtest.
     662          self.assertEqual(sys.__stdout__.encoding, sys.__stderr__.encoding)
     663  
     664      def test_intern(self):
     665          global INTERN_NUMRUNS
     666          INTERN_NUMRUNS += 1
     667          self.assertRaises(TypeError, sys.intern)
     668          s = "never interned before" + str(INTERN_NUMRUNS)
     669          self.assertTrue(sys.intern(s) is s)
     670          s2 = s.swapcase().swapcase()
     671          self.assertTrue(sys.intern(s2) is s)
     672  
     673          # Subclasses of string can't be interned, because they
     674          # provide too much opportunity for insane things to happen.
     675          # We don't want them in the interned dict and if they aren't
     676          # actually interned, we don't want to create the appearance
     677          # that they are by allowing intern() to succeed.
     678          class ESC[4;38;5;81mS(ESC[4;38;5;149mstr):
     679              def __hash__(self):
     680                  return 123
     681  
     682          self.assertRaises(TypeError, sys.intern, S("abc"))
     683  
     684      def test_sys_flags(self):
     685          self.assertTrue(sys.flags)
     686          attrs = ("debug",
     687                   "inspect", "interactive", "optimize",
     688                   "dont_write_bytecode", "no_user_site", "no_site",
     689                   "ignore_environment", "verbose", "bytes_warning", "quiet",
     690                   "hash_randomization", "isolated", "dev_mode", "utf8_mode",
     691                   "warn_default_encoding", "safe_path", "int_max_str_digits")
     692          for attr in attrs:
     693              self.assertTrue(hasattr(sys.flags, attr), attr)
     694              attr_type = bool if attr in ("dev_mode", "safe_path") else int
     695              self.assertEqual(type(getattr(sys.flags, attr)), attr_type, attr)
     696          self.assertTrue(repr(sys.flags))
     697          self.assertEqual(len(sys.flags), len(attrs))
     698  
     699          self.assertIn(sys.flags.utf8_mode, {0, 1, 2})
     700  
     701      def assert_raise_on_new_sys_type(self, sys_attr):
     702          # Users are intentionally prevented from creating new instances of
     703          # sys.flags, sys.version_info, and sys.getwindowsversion.
     704          arg = sys_attr
     705          attr_type = type(sys_attr)
     706          with self.assertRaises(TypeError):
     707              attr_type(arg)
     708          with self.assertRaises(TypeError):
     709              attr_type.__new__(attr_type, arg)
     710  
     711      def test_sys_flags_no_instantiation(self):
     712          self.assert_raise_on_new_sys_type(sys.flags)
     713  
     714      def test_sys_version_info_no_instantiation(self):
     715          self.assert_raise_on_new_sys_type(sys.version_info)
     716  
     717      def test_sys_getwindowsversion_no_instantiation(self):
     718          # Skip if not being run on Windows.
     719          test.support.get_attribute(sys, "getwindowsversion")
     720          self.assert_raise_on_new_sys_type(sys.getwindowsversion())
     721  
     722      @test.support.cpython_only
     723      def test_clear_type_cache(self):
     724          sys._clear_type_cache()
     725  
     726      @support.requires_subprocess()
     727      def test_ioencoding(self):
     728          env = dict(os.environ)
     729  
     730          # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424,
     731          # not representable in ASCII.
     732  
     733          env["PYTHONIOENCODING"] = "cp424"
     734          p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'],
     735                               stdout = subprocess.PIPE, env=env)
     736          out = p.communicate()[0].strip()
     737          expected = ("\xa2" + os.linesep).encode("cp424")
     738          self.assertEqual(out, expected)
     739  
     740          env["PYTHONIOENCODING"] = "ascii:replace"
     741          p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'],
     742                               stdout = subprocess.PIPE, env=env)
     743          out = p.communicate()[0].strip()
     744          self.assertEqual(out, b'?')
     745  
     746          env["PYTHONIOENCODING"] = "ascii"
     747          p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'],
     748                               stdout=subprocess.PIPE, stderr=subprocess.PIPE,
     749                               env=env)
     750          out, err = p.communicate()
     751          self.assertEqual(out, b'')
     752          self.assertIn(b'UnicodeEncodeError:', err)
     753          self.assertIn(rb"'\xa2'", err)
     754  
     755          env["PYTHONIOENCODING"] = "ascii:"
     756          p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'],
     757                               stdout=subprocess.PIPE, stderr=subprocess.PIPE,
     758                               env=env)
     759          out, err = p.communicate()
     760          self.assertEqual(out, b'')
     761          self.assertIn(b'UnicodeEncodeError:', err)
     762          self.assertIn(rb"'\xa2'", err)
     763  
     764          env["PYTHONIOENCODING"] = ":surrogateescape"
     765          p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xdcbd))'],
     766                               stdout=subprocess.PIPE, env=env)
     767          out = p.communicate()[0].strip()
     768          self.assertEqual(out, b'\xbd')
     769  
     770      @unittest.skipUnless(os_helper.FS_NONASCII,
     771                           'requires OS support of non-ASCII encodings')
     772      @unittest.skipUnless(sys.getfilesystemencoding() == locale.getpreferredencoding(False),
     773                           'requires FS encoding to match locale')
     774      @support.requires_subprocess()
     775      def test_ioencoding_nonascii(self):
     776          env = dict(os.environ)
     777  
     778          env["PYTHONIOENCODING"] = ""
     779          p = subprocess.Popen([sys.executable, "-c",
     780                                  'print(%a)' % os_helper.FS_NONASCII],
     781                                  stdout=subprocess.PIPE, env=env)
     782          out = p.communicate()[0].strip()
     783          self.assertEqual(out, os.fsencode(os_helper.FS_NONASCII))
     784  
     785      @unittest.skipIf(sys.base_prefix != sys.prefix,
     786                       'Test is not venv-compatible')
     787      @support.requires_subprocess()
     788      def test_executable(self):
     789          # sys.executable should be absolute
     790          self.assertEqual(os.path.abspath(sys.executable), sys.executable)
     791  
     792          # Issue #7774: Ensure that sys.executable is an empty string if argv[0]
     793          # has been set to a non existent program name and Python is unable to
     794          # retrieve the real program name
     795  
     796          # For a normal installation, it should work without 'cwd'
     797          # argument. For test runs in the build directory, see #7774.
     798          python_dir = os.path.dirname(os.path.realpath(sys.executable))
     799          p = subprocess.Popen(
     800              ["nonexistent", "-c",
     801               'import sys; print(sys.executable.encode("ascii", "backslashreplace"))'],
     802              executable=sys.executable, stdout=subprocess.PIPE, cwd=python_dir)
     803          stdout = p.communicate()[0]
     804          executable = stdout.strip().decode("ASCII")
     805          p.wait()
     806          self.assertIn(executable, ["b''", repr(sys.executable.encode("ascii", "backslashreplace"))])
     807  
     808      def check_fsencoding(self, fs_encoding, expected=None):
     809          self.assertIsNotNone(fs_encoding)
     810          codecs.lookup(fs_encoding)
     811          if expected:
     812              self.assertEqual(fs_encoding, expected)
     813  
     814      def test_getfilesystemencoding(self):
     815          fs_encoding = sys.getfilesystemencoding()
     816          if sys.platform == 'darwin':
     817              expected = 'utf-8'
     818          else:
     819              expected = None
     820          self.check_fsencoding(fs_encoding, expected)
     821  
     822      def c_locale_get_error_handler(self, locale, isolated=False, encoding=None):
     823          # Force the POSIX locale
     824          env = os.environ.copy()
     825          env["LC_ALL"] = locale
     826          env["PYTHONCOERCECLOCALE"] = "0"
     827          code = '\n'.join((
     828              'import sys',
     829              'def dump(name):',
     830              '    std = getattr(sys, name)',
     831              '    print("%s: %s" % (name, std.errors))',
     832              'dump("stdin")',
     833              'dump("stdout")',
     834              'dump("stderr")',
     835          ))
     836          args = [sys.executable, "-X", "utf8=0", "-c", code]
     837          if isolated:
     838              args.append("-I")
     839          if encoding is not None:
     840              env['PYTHONIOENCODING'] = encoding
     841          else:
     842              env.pop('PYTHONIOENCODING', None)
     843          p = subprocess.Popen(args,
     844                                stdout=subprocess.PIPE,
     845                                stderr=subprocess.STDOUT,
     846                                env=env,
     847                                universal_newlines=True)
     848          stdout, stderr = p.communicate()
     849          return stdout
     850  
     851      def check_locale_surrogateescape(self, locale):
     852          out = self.c_locale_get_error_handler(locale, isolated=True)
     853          self.assertEqual(out,
     854                           'stdin: surrogateescape\n'
     855                           'stdout: surrogateescape\n'
     856                           'stderr: backslashreplace\n')
     857  
     858          # replace the default error handler
     859          out = self.c_locale_get_error_handler(locale, encoding=':ignore')
     860          self.assertEqual(out,
     861                           'stdin: ignore\n'
     862                           'stdout: ignore\n'
     863                           'stderr: backslashreplace\n')
     864  
     865          # force the encoding
     866          out = self.c_locale_get_error_handler(locale, encoding='iso8859-1')
     867          self.assertEqual(out,
     868                           'stdin: strict\n'
     869                           'stdout: strict\n'
     870                           'stderr: backslashreplace\n')
     871          out = self.c_locale_get_error_handler(locale, encoding='iso8859-1:')
     872          self.assertEqual(out,
     873                           'stdin: strict\n'
     874                           'stdout: strict\n'
     875                           'stderr: backslashreplace\n')
     876  
     877          # have no any effect
     878          out = self.c_locale_get_error_handler(locale, encoding=':')
     879          self.assertEqual(out,
     880                           'stdin: surrogateescape\n'
     881                           'stdout: surrogateescape\n'
     882                           'stderr: backslashreplace\n')
     883          out = self.c_locale_get_error_handler(locale, encoding='')
     884          self.assertEqual(out,
     885                           'stdin: surrogateescape\n'
     886                           'stdout: surrogateescape\n'
     887                           'stderr: backslashreplace\n')
     888  
     889      @support.requires_subprocess()
     890      def test_c_locale_surrogateescape(self):
     891          self.check_locale_surrogateescape('C')
     892  
     893      @support.requires_subprocess()
     894      def test_posix_locale_surrogateescape(self):
     895          self.check_locale_surrogateescape('POSIX')
     896  
     897      def test_implementation(self):
     898          # This test applies to all implementations equally.
     899  
     900          levels = {'alpha': 0xA, 'beta': 0xB, 'candidate': 0xC, 'final': 0xF}
     901  
     902          self.assertTrue(hasattr(sys.implementation, 'name'))
     903          self.assertTrue(hasattr(sys.implementation, 'version'))
     904          self.assertTrue(hasattr(sys.implementation, 'hexversion'))
     905          self.assertTrue(hasattr(sys.implementation, 'cache_tag'))
     906  
     907          version = sys.implementation.version
     908          self.assertEqual(version[:2], (version.major, version.minor))
     909  
     910          hexversion = (version.major << 24 | version.minor << 16 |
     911                        version.micro << 8 | levels[version.releaselevel] << 4 |
     912                        version.serial << 0)
     913          self.assertEqual(sys.implementation.hexversion, hexversion)
     914  
     915          # PEP 421 requires that .name be lower case.
     916          self.assertEqual(sys.implementation.name,
     917                           sys.implementation.name.lower())
     918  
     919      @test.support.cpython_only
     920      def test_debugmallocstats(self):
     921          # Test sys._debugmallocstats()
     922          from test.support.script_helper import assert_python_ok
     923          args = ['-c', 'import sys; sys._debugmallocstats()']
     924          ret, out, err = assert_python_ok(*args)
     925  
     926          # Output of sys._debugmallocstats() depends on configure flags.
     927          # The sysconfig vars are not available on Windows.
     928          if sys.platform != "win32":
     929              with_freelists = sysconfig.get_config_var("WITH_FREELISTS")
     930              with_pymalloc = sysconfig.get_config_var("WITH_PYMALLOC")
     931              if with_freelists:
     932                  self.assertIn(b"free PyDictObjects", err)
     933              if with_pymalloc:
     934                  self.assertIn(b'Small block threshold', err)
     935              if not with_freelists and not with_pymalloc:
     936                  self.assertFalse(err)
     937  
     938          # The function has no parameter
     939          self.assertRaises(TypeError, sys._debugmallocstats, True)
     940  
     941      @unittest.skipUnless(hasattr(sys, "getallocatedblocks"),
     942                           "sys.getallocatedblocks unavailable on this build")
     943      def test_getallocatedblocks(self):
     944          try:
     945              import _testcapi
     946          except ImportError:
     947              with_pymalloc = support.with_pymalloc()
     948          else:
     949              try:
     950                  alloc_name = _testcapi.pymem_getallocatorsname()
     951              except RuntimeError as exc:
     952                  # "cannot get allocators name" (ex: tracemalloc is used)
     953                  with_pymalloc = True
     954              else:
     955                  with_pymalloc = (alloc_name in ('pymalloc', 'pymalloc_debug'))
     956  
     957          # Some sanity checks
     958          a = sys.getallocatedblocks()
     959          self.assertIs(type(a), int)
     960          if with_pymalloc:
     961              self.assertGreater(a, 0)
     962          else:
     963              # When WITH_PYMALLOC isn't available, we don't know anything
     964              # about the underlying implementation: the function might
     965              # return 0 or something greater.
     966              self.assertGreaterEqual(a, 0)
     967          try:
     968              # While we could imagine a Python session where the number of
     969              # multiple buffer objects would exceed the sharing of references,
     970              # it is unlikely to happen in a normal test run.
     971              self.assertLess(a, sys.gettotalrefcount())
     972          except AttributeError:
     973              # gettotalrefcount() not available
     974              pass
     975          gc.collect()
     976          b = sys.getallocatedblocks()
     977          self.assertLessEqual(b, a)
     978          gc.collect()
     979          c = sys.getallocatedblocks()
     980          self.assertIn(c, range(b - 50, b + 50))
     981  
     982      def test_is_finalizing(self):
     983          self.assertIs(sys.is_finalizing(), False)
     984          # Don't use the atexit module because _Py_Finalizing is only set
     985          # after calling atexit callbacks
     986          code = """if 1:
     987              import sys
     988  
     989              class AtExit:
     990                  is_finalizing = sys.is_finalizing
     991                  print = print
     992  
     993                  def __del__(self):
     994                      self.print(self.is_finalizing(), flush=True)
     995  
     996              # Keep a reference in the __main__ module namespace, so the
     997              # AtExit destructor will be called at Python exit
     998              ref = AtExit()
     999          """
    1000          rc, stdout, stderr = assert_python_ok('-c', code)
    1001          self.assertEqual(stdout.rstrip(), b'True')
    1002  
    1003      def test_issue20602(self):
    1004          # sys.flags and sys.float_info were wiped during shutdown.
    1005          code = """if 1:
    1006              import sys
    1007              class A:
    1008                  def __del__(self, sys=sys):
    1009                      print(sys.flags)
    1010                      print(sys.float_info)
    1011              a = A()
    1012              """
    1013          rc, out, err = assert_python_ok('-c', code)
    1014          out = out.splitlines()
    1015          self.assertIn(b'sys.flags', out[0])
    1016          self.assertIn(b'sys.float_info', out[1])
    1017  
    1018      def test_sys_ignores_cleaning_up_user_data(self):
    1019          code = """if 1:
    1020              import struct, sys
    1021  
    1022              class C:
    1023                  def __init__(self):
    1024                      self.pack = struct.pack
    1025                  def __del__(self):
    1026                      self.pack('I', -42)
    1027  
    1028              sys.x = C()
    1029              """
    1030          rc, stdout, stderr = assert_python_ok('-c', code)
    1031          self.assertEqual(rc, 0)
    1032          self.assertEqual(stdout.rstrip(), b"")
    1033          self.assertEqual(stderr.rstrip(), b"")
    1034  
    1035      @unittest.skipUnless(hasattr(sys, 'getandroidapilevel'),
    1036                           'need sys.getandroidapilevel()')
    1037      def test_getandroidapilevel(self):
    1038          level = sys.getandroidapilevel()
    1039          self.assertIsInstance(level, int)
    1040          self.assertGreater(level, 0)
    1041  
    1042      @support.requires_subprocess()
    1043      def test_sys_tracebacklimit(self):
    1044          code = """if 1:
    1045              import sys
    1046              def f1():
    1047                  1 / 0
    1048              def f2():
    1049                  f1()
    1050              sys.tracebacklimit = %r
    1051              f2()
    1052          """
    1053          def check(tracebacklimit, expected):
    1054              p = subprocess.Popen([sys.executable, '-c', code % tracebacklimit],
    1055                                   stderr=subprocess.PIPE)
    1056              out = p.communicate()[1]
    1057              self.assertEqual(out.splitlines(), expected)
    1058  
    1059          traceback = [
    1060              b'Traceback (most recent call last):',
    1061              b'  File "<string>", line 8, in <module>',
    1062              b'  File "<string>", line 6, in f2',
    1063              b'  File "<string>", line 4, in f1',
    1064              b'ZeroDivisionError: division by zero'
    1065          ]
    1066          check(10, traceback)
    1067          check(3, traceback)
    1068          check(2, traceback[:1] + traceback[2:])
    1069          check(1, traceback[:1] + traceback[3:])
    1070          check(0, [traceback[-1]])
    1071          check(-1, [traceback[-1]])
    1072          check(1<<1000, traceback)
    1073          check(-1<<1000, [traceback[-1]])
    1074          check(None, traceback)
    1075  
    1076      def test_no_duplicates_in_meta_path(self):
    1077          self.assertEqual(len(sys.meta_path), len(set(sys.meta_path)))
    1078  
    1079      @unittest.skipUnless(hasattr(sys, "_enablelegacywindowsfsencoding"),
    1080                           'needs sys._enablelegacywindowsfsencoding()')
    1081      def test__enablelegacywindowsfsencoding(self):
    1082          code = ('import sys',
    1083                  'sys._enablelegacywindowsfsencoding()',
    1084                  'print(sys.getfilesystemencoding(), sys.getfilesystemencodeerrors())')
    1085          rc, out, err = assert_python_ok('-c', '; '.join(code))
    1086          out = out.decode('ascii', 'replace').rstrip()
    1087          self.assertEqual(out, 'mbcs replace')
    1088  
    1089      @support.requires_subprocess()
    1090      def test_orig_argv(self):
    1091          code = textwrap.dedent('''
    1092              import sys
    1093              print(sys.argv)
    1094              print(sys.orig_argv)
    1095          ''')
    1096          args = [sys.executable, '-I', '-X', 'utf8', '-c', code, 'arg']
    1097          proc = subprocess.run(args, check=True, capture_output=True, text=True)
    1098          expected = [
    1099              repr(['-c', 'arg']),  # sys.argv
    1100              repr(args),  # sys.orig_argv
    1101          ]
    1102          self.assertEqual(proc.stdout.rstrip().splitlines(), expected,
    1103                           proc)
    1104  
    1105      def test_module_names(self):
    1106          self.assertIsInstance(sys.stdlib_module_names, frozenset)
    1107          for name in sys.stdlib_module_names:
    1108              self.assertIsInstance(name, str)
    1109  
    1110      def test_stdlib_dir(self):
    1111          os = import_helper.import_fresh_module('os')
    1112          marker = getattr(os, '__file__', None)
    1113          if marker and not os.path.exists(marker):
    1114              marker = None
    1115          expected = os.path.dirname(marker) if marker else None
    1116          self.assertEqual(os.path.normpath(sys._stdlib_dir),
    1117                           os.path.normpath(expected))
    1118  
    1119  
    1120  @test.support.cpython_only
    1121  class ESC[4;38;5;81mUnraisableHookTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
    1122      def write_unraisable_exc(self, exc, err_msg, obj):
    1123          import _testcapi
    1124          import types
    1125          err_msg2 = f"Exception ignored {err_msg}"
    1126          try:
    1127              _testcapi.write_unraisable_exc(exc, err_msg, obj)
    1128              return types.SimpleNamespace(exc_type=type(exc),
    1129                                           exc_value=exc,
    1130                                           exc_traceback=exc.__traceback__,
    1131                                           err_msg=err_msg2,
    1132                                           object=obj)
    1133          finally:
    1134              # Explicitly break any reference cycle
    1135              exc = None
    1136  
    1137      def test_original_unraisablehook(self):
    1138          for err_msg in (None, "original hook"):
    1139              with self.subTest(err_msg=err_msg):
    1140                  obj = "an object"
    1141  
    1142                  with test.support.captured_output("stderr") as stderr:
    1143                      with test.support.swap_attr(sys, 'unraisablehook',
    1144                                                  sys.__unraisablehook__):
    1145                          self.write_unraisable_exc(ValueError(42), err_msg, obj)
    1146  
    1147                  err = stderr.getvalue()
    1148                  if err_msg is not None:
    1149                      self.assertIn(f'Exception ignored {err_msg}: {obj!r}\n', err)
    1150                  else:
    1151                      self.assertIn(f'Exception ignored in: {obj!r}\n', err)
    1152                  self.assertIn('Traceback (most recent call last):\n', err)
    1153                  self.assertIn('ValueError: 42\n', err)
    1154  
    1155      def test_original_unraisablehook_err(self):
    1156          # bpo-22836: PyErr_WriteUnraisable() should give sensible reports
    1157          class ESC[4;38;5;81mBrokenDel:
    1158              def __del__(self):
    1159                  exc = ValueError("del is broken")
    1160                  # The following line is included in the traceback report:
    1161                  raise exc
    1162  
    1163          class ESC[4;38;5;81mBrokenStrException(ESC[4;38;5;149mException):
    1164              def __str__(self):
    1165                  raise Exception("str() is broken")
    1166  
    1167          class ESC[4;38;5;81mBrokenExceptionDel:
    1168              def __del__(self):
    1169                  exc = BrokenStrException()
    1170                  # The following line is included in the traceback report:
    1171                  raise exc
    1172  
    1173          for test_class in (BrokenDel, BrokenExceptionDel):
    1174              with self.subTest(test_class):
    1175                  obj = test_class()
    1176                  with test.support.captured_stderr() as stderr, \
    1177                       test.support.swap_attr(sys, 'unraisablehook',
    1178                                              sys.__unraisablehook__):
    1179                      # Trigger obj.__del__()
    1180                      del obj
    1181  
    1182                  report = stderr.getvalue()
    1183                  self.assertIn("Exception ignored", report)
    1184                  self.assertIn(test_class.__del__.__qualname__, report)
    1185                  self.assertIn("test_sys.py", report)
    1186                  self.assertIn("raise exc", report)
    1187                  if test_class is BrokenExceptionDel:
    1188                      self.assertIn("BrokenStrException", report)
    1189                      self.assertIn("<exception str() failed>", report)
    1190                  else:
    1191                      self.assertIn("ValueError", report)
    1192                      self.assertIn("del is broken", report)
    1193                  self.assertTrue(report.endswith("\n"))
    1194  
    1195      def test_original_unraisablehook_exception_qualname(self):
    1196          # See bpo-41031, bpo-45083.
    1197          # Check that the exception is printed with its qualified name
    1198          # rather than just classname, and the module names appears
    1199          # unless it is one of the hard-coded exclusions.
    1200          class ESC[4;38;5;81mA:
    1201              class ESC[4;38;5;81mB:
    1202                  class ESC[4;38;5;81mX(ESC[4;38;5;149mException):
    1203                      pass
    1204  
    1205          for moduleName in 'builtins', '__main__', 'some_module':
    1206              with self.subTest(moduleName=moduleName):
    1207                  A.B.X.__module__ = moduleName
    1208                  with test.support.captured_stderr() as stderr, test.support.swap_attr(
    1209                      sys, 'unraisablehook', sys.__unraisablehook__
    1210                  ):
    1211                      expected = self.write_unraisable_exc(
    1212                          A.B.X(), "msg", "obj"
    1213                      )
    1214                  report = stderr.getvalue()
    1215                  self.assertIn(A.B.X.__qualname__, report)
    1216                  if moduleName in ['builtins', '__main__']:
    1217                      self.assertNotIn(moduleName + '.', report)
    1218                  else:
    1219                      self.assertIn(moduleName + '.', report)
    1220  
    1221      def test_original_unraisablehook_wrong_type(self):
    1222          exc = ValueError(42)
    1223          with test.support.swap_attr(sys, 'unraisablehook',
    1224                                      sys.__unraisablehook__):
    1225              with self.assertRaises(TypeError):
    1226                  sys.unraisablehook(exc)
    1227  
    1228      def test_custom_unraisablehook(self):
    1229          hook_args = None
    1230  
    1231          def hook_func(args):
    1232              nonlocal hook_args
    1233              hook_args = args
    1234  
    1235          obj = object()
    1236          try:
    1237              with test.support.swap_attr(sys, 'unraisablehook', hook_func):
    1238                  expected = self.write_unraisable_exc(ValueError(42),
    1239                                                       "custom hook", obj)
    1240                  for attr in "exc_type exc_value exc_traceback err_msg object".split():
    1241                      self.assertEqual(getattr(hook_args, attr),
    1242                                       getattr(expected, attr),
    1243                                       (hook_args, expected))
    1244          finally:
    1245              # expected and hook_args contain an exception: break reference cycle
    1246              expected = None
    1247              hook_args = None
    1248  
    1249      def test_custom_unraisablehook_fail(self):
    1250          def hook_func(*args):
    1251              raise Exception("hook_func failed")
    1252  
    1253          with test.support.captured_output("stderr") as stderr:
    1254              with test.support.swap_attr(sys, 'unraisablehook', hook_func):
    1255                  self.write_unraisable_exc(ValueError(42),
    1256                                            "custom hook fail", None)
    1257  
    1258          err = stderr.getvalue()
    1259          self.assertIn(f'Exception ignored in sys.unraisablehook: '
    1260                        f'{hook_func!r}\n',
    1261                        err)
    1262          self.assertIn('Traceback (most recent call last):\n', err)
    1263          self.assertIn('Exception: hook_func failed\n', err)
    1264  
    1265  
    1266  @test.support.cpython_only
    1267  class ESC[4;38;5;81mSizeofTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
    1268  
    1269      def setUp(self):
    1270          self.P = struct.calcsize('P')
    1271          self.longdigit = sys.int_info.sizeof_digit
    1272          import _testinternalcapi
    1273          self.gc_headsize = _testinternalcapi.SIZEOF_PYGC_HEAD
    1274  
    1275      check_sizeof = test.support.check_sizeof
    1276  
    1277      def test_gc_head_size(self):
    1278          # Check that the gc header size is added to objects tracked by the gc.
    1279          vsize = test.support.calcvobjsize
    1280          gc_header_size = self.gc_headsize
    1281          # bool objects are not gc tracked
    1282          self.assertEqual(sys.getsizeof(True), vsize('') + self.longdigit)
    1283          # but lists are
    1284          self.assertEqual(sys.getsizeof([]), vsize('Pn') + gc_header_size)
    1285  
    1286      def test_errors(self):
    1287          class ESC[4;38;5;81mBadSizeof:
    1288              def __sizeof__(self):
    1289                  raise ValueError
    1290          self.assertRaises(ValueError, sys.getsizeof, BadSizeof())
    1291  
    1292          class ESC[4;38;5;81mInvalidSizeof:
    1293              def __sizeof__(self):
    1294                  return None
    1295          self.assertRaises(TypeError, sys.getsizeof, InvalidSizeof())
    1296          sentinel = ["sentinel"]
    1297          self.assertIs(sys.getsizeof(InvalidSizeof(), sentinel), sentinel)
    1298  
    1299          class ESC[4;38;5;81mFloatSizeof:
    1300              def __sizeof__(self):
    1301                  return 4.5
    1302          self.assertRaises(TypeError, sys.getsizeof, FloatSizeof())
    1303          self.assertIs(sys.getsizeof(FloatSizeof(), sentinel), sentinel)
    1304  
    1305          class ESC[4;38;5;81mOverflowSizeof(ESC[4;38;5;149mint):
    1306              def __sizeof__(self):
    1307                  return int(self)
    1308          self.assertEqual(sys.getsizeof(OverflowSizeof(sys.maxsize)),
    1309                           sys.maxsize + self.gc_headsize)
    1310          with self.assertRaises(OverflowError):
    1311              sys.getsizeof(OverflowSizeof(sys.maxsize + 1))
    1312          with self.assertRaises(ValueError):
    1313              sys.getsizeof(OverflowSizeof(-1))
    1314          with self.assertRaises((ValueError, OverflowError)):
    1315              sys.getsizeof(OverflowSizeof(-sys.maxsize - 1))
    1316  
    1317      def test_default(self):
    1318          size = test.support.calcvobjsize
    1319          self.assertEqual(sys.getsizeof(True), size('') + self.longdigit)
    1320          self.assertEqual(sys.getsizeof(True, -1), size('') + self.longdigit)
    1321  
    1322      def test_objecttypes(self):
    1323          # check all types defined in Objects/
    1324          calcsize = struct.calcsize
    1325          size = test.support.calcobjsize
    1326          vsize = test.support.calcvobjsize
    1327          check = self.check_sizeof
    1328          # bool
    1329          check(True, vsize('') + self.longdigit)
    1330          check(False, vsize('') + self.longdigit)
    1331          # buffer
    1332          # XXX
    1333          # builtin_function_or_method
    1334          check(len, size('5P'))
    1335          # bytearray
    1336          samples = [b'', b'u'*100000]
    1337          for sample in samples:
    1338              x = bytearray(sample)
    1339              check(x, vsize('n2Pi') + x.__alloc__())
    1340          # bytearray_iterator
    1341          check(iter(bytearray()), size('nP'))
    1342          # bytes
    1343          check(b'', vsize('n') + 1)
    1344          check(b'x' * 10, vsize('n') + 11)
    1345          # cell
    1346          def get_cell():
    1347              x = 42
    1348              def inner():
    1349                  return x
    1350              return inner
    1351          check(get_cell().__closure__[0], size('P'))
    1352          # code
    1353          def check_code_size(a, expected_size):
    1354              self.assertGreaterEqual(sys.getsizeof(a), expected_size)
    1355          check_code_size(get_cell().__code__, size('6i13P'))
    1356          check_code_size(get_cell.__code__, size('6i13P'))
    1357          def get_cell2(x):
    1358              def inner():
    1359                  return x
    1360              return inner
    1361          check_code_size(get_cell2.__code__, size('6i13P') + calcsize('n'))
    1362          # complex
    1363          check(complex(0,1), size('2d'))
    1364          # method_descriptor (descriptor object)
    1365          check(str.lower, size('3PPP'))
    1366          # classmethod_descriptor (descriptor object)
    1367          # XXX
    1368          # member_descriptor (descriptor object)
    1369          import datetime
    1370          check(datetime.timedelta.days, size('3PP'))
    1371          # getset_descriptor (descriptor object)
    1372          import collections
    1373          check(collections.defaultdict.default_factory, size('3PP'))
    1374          # wrapper_descriptor (descriptor object)
    1375          check(int.__add__, size('3P2P'))
    1376          # method-wrapper (descriptor object)
    1377          check({}.__iter__, size('2P'))
    1378          # empty dict
    1379          check({}, size('nQ2P'))
    1380          # dict (string key)
    1381          check({"a": 1}, size('nQ2P') + calcsize(DICT_KEY_STRUCT_FORMAT) + 8 + (8*2//3)*calcsize('2P'))
    1382          longdict = {str(i): i for i in range(8)}
    1383          check(longdict, size('nQ2P') + calcsize(DICT_KEY_STRUCT_FORMAT) + 16 + (16*2//3)*calcsize('2P'))
    1384          # dict (non-string key)
    1385          check({1: 1}, size('nQ2P') + calcsize(DICT_KEY_STRUCT_FORMAT) + 8 + (8*2//3)*calcsize('n2P'))
    1386          longdict = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8}
    1387          check(longdict, size('nQ2P') + calcsize(DICT_KEY_STRUCT_FORMAT) + 16 + (16*2//3)*calcsize('n2P'))
    1388          # dictionary-keyview
    1389          check({}.keys(), size('P'))
    1390          # dictionary-valueview
    1391          check({}.values(), size('P'))
    1392          # dictionary-itemview
    1393          check({}.items(), size('P'))
    1394          # dictionary iterator
    1395          check(iter({}), size('P2nPn'))
    1396          # dictionary-keyiterator
    1397          check(iter({}.keys()), size('P2nPn'))
    1398          # dictionary-valueiterator
    1399          check(iter({}.values()), size('P2nPn'))
    1400          # dictionary-itemiterator
    1401          check(iter({}.items()), size('P2nPn'))
    1402          # dictproxy
    1403          class ESC[4;38;5;81mC(ESC[4;38;5;149mobject): pass
    1404          check(C.__dict__, size('P'))
    1405          # BaseException
    1406          check(BaseException(), size('6Pb'))
    1407          # UnicodeEncodeError
    1408          check(UnicodeEncodeError("", "", 0, 0, ""), size('6Pb 2P2nP'))
    1409          # UnicodeDecodeError
    1410          check(UnicodeDecodeError("", b"", 0, 0, ""), size('6Pb 2P2nP'))
    1411          # UnicodeTranslateError
    1412          check(UnicodeTranslateError("", 0, 1, ""), size('6Pb 2P2nP'))
    1413          # ellipses
    1414          check(Ellipsis, size(''))
    1415          # EncodingMap
    1416          import codecs, encodings.iso8859_3
    1417          x = codecs.charmap_build(encodings.iso8859_3.decoding_table)
    1418          check(x, size('32B2iB'))
    1419          # enumerate
    1420          check(enumerate([]), size('n4P'))
    1421          # reverse
    1422          check(reversed(''), size('nP'))
    1423          # float
    1424          check(float(0), size('d'))
    1425          # sys.floatinfo
    1426          check(sys.float_info, vsize('') + self.P * len(sys.float_info))
    1427          # frame
    1428          def func():
    1429              return sys._getframe()
    1430          x = func()
    1431          check(x, size('3Pi3c7P2ic??2P'))
    1432          # function
    1433          def func(): pass
    1434          check(func, size('14Pi'))
    1435          class ESC[4;38;5;81mc():
    1436              @staticmethod
    1437              def foo():
    1438                  pass
    1439              @classmethod
    1440              def bar(cls):
    1441                  pass
    1442              # staticmethod
    1443              check(foo, size('PP'))
    1444              # classmethod
    1445              check(bar, size('PP'))
    1446          # generator
    1447          def get_gen(): yield 1
    1448          check(get_gen(), size('P2P4P4c7P2ic??P'))
    1449          # iterator
    1450          check(iter('abc'), size('lP'))
    1451          # callable-iterator
    1452          import re
    1453          check(re.finditer('',''), size('2P'))
    1454          # list
    1455          check(list([]), vsize('Pn'))
    1456          check(list([1]), vsize('Pn') + 2*self.P)
    1457          check(list([1, 2]), vsize('Pn') + 2*self.P)
    1458          check(list([1, 2, 3]), vsize('Pn') + 4*self.P)
    1459          # sortwrapper (list)
    1460          # XXX
    1461          # cmpwrapper (list)
    1462          # XXX
    1463          # listiterator (list)
    1464          check(iter([]), size('lP'))
    1465          # listreverseiterator (list)
    1466          check(reversed([]), size('nP'))
    1467          # int
    1468          check(0, vsize('') + self.longdigit)
    1469          check(1, vsize('') + self.longdigit)
    1470          check(-1, vsize('') + self.longdigit)
    1471          PyLong_BASE = 2**sys.int_info.bits_per_digit
    1472          check(int(PyLong_BASE), vsize('') + 2*self.longdigit)
    1473          check(int(PyLong_BASE**2-1), vsize('') + 2*self.longdigit)
    1474          check(int(PyLong_BASE**2), vsize('') + 3*self.longdigit)
    1475          # module
    1476          check(unittest, size('PnPPP'))
    1477          # None
    1478          check(None, size(''))
    1479          # NotImplementedType
    1480          check(NotImplemented, size(''))
    1481          # object
    1482          check(object(), size(''))
    1483          # property (descriptor object)
    1484          class ESC[4;38;5;81mC(ESC[4;38;5;149mobject):
    1485              def getx(self): return self.__x
    1486              def setx(self, value): self.__x = value
    1487              def delx(self): del self.__x
    1488              x = property(getx, setx, delx, "")
    1489              check(x, size('5Pi'))
    1490          # PyCapsule
    1491          # XXX
    1492          # rangeiterator
    1493          check(iter(range(1)), size('4l'))
    1494          # reverse
    1495          check(reversed(''), size('nP'))
    1496          # range
    1497          check(range(1), size('4P'))
    1498          check(range(66000), size('4P'))
    1499          # set
    1500          # frozenset
    1501          PySet_MINSIZE = 8
    1502          samples = [[], range(10), range(50)]
    1503          s = size('3nP' + PySet_MINSIZE*'nP' + '2nP')
    1504          for sample in samples:
    1505              minused = len(sample)
    1506              if minused == 0: tmp = 1
    1507              # the computation of minused is actually a bit more complicated
    1508              # but this suffices for the sizeof test
    1509              minused = minused*2
    1510              newsize = PySet_MINSIZE
    1511              while newsize <= minused:
    1512                  newsize = newsize << 1
    1513              if newsize <= 8:
    1514                  check(set(sample), s)
    1515                  check(frozenset(sample), s)
    1516              else:
    1517                  check(set(sample), s + newsize*calcsize('nP'))
    1518                  check(frozenset(sample), s + newsize*calcsize('nP'))
    1519          # setiterator
    1520          check(iter(set()), size('P3n'))
    1521          # slice
    1522          check(slice(0), size('3P'))
    1523          # super
    1524          check(super(int), size('3P'))
    1525          # tuple
    1526          check((), vsize(''))
    1527          check((1,2,3), vsize('') + 3*self.P)
    1528          # type
    1529          # static type: PyTypeObject
    1530          fmt = 'P2nPI13Pl4Pn9Pn12PIP'
    1531          s = vsize('2P' + fmt)
    1532          check(int, s)
    1533          # class
    1534          s = vsize(fmt +                 # PyTypeObject
    1535                    '4P'                  # PyAsyncMethods
    1536                    '36P'                 # PyNumberMethods
    1537                    '3P'                  # PyMappingMethods
    1538                    '10P'                 # PySequenceMethods
    1539                    '2P'                  # PyBufferProcs
    1540                    '6P'
    1541                    '1P'                  # Specializer cache
    1542                    )
    1543          class ESC[4;38;5;81mnewstyleclass(ESC[4;38;5;149mobject): pass
    1544          # Separate block for PyDictKeysObject with 8 keys and 5 entries
    1545          check(newstyleclass, s + calcsize(DICT_KEY_STRUCT_FORMAT) + 64 + 42*calcsize("2P"))
    1546          # dict with shared keys
    1547          [newstyleclass() for _ in range(100)]
    1548          check(newstyleclass().__dict__, size('nQ2P') + self.P)
    1549          o = newstyleclass()
    1550          o.a = o.b = o.c = o.d = o.e = o.f = o.g = o.h = 1
    1551          # Separate block for PyDictKeysObject with 16 keys and 10 entries
    1552          check(newstyleclass, s + calcsize(DICT_KEY_STRUCT_FORMAT) + 64 + 42*calcsize("2P"))
    1553          # dict with shared keys
    1554          check(newstyleclass().__dict__, size('nQ2P') + self.P)
    1555          # unicode
    1556          # each tuple contains a string and its expected character size
    1557          # don't put any static strings here, as they may contain
    1558          # wchar_t or UTF-8 representations
    1559          samples = ['1'*100, '\xff'*50,
    1560                     '\u0100'*40, '\uffff'*100,
    1561                     '\U00010000'*30, '\U0010ffff'*100]
    1562          # also update field definitions in test_unicode.test_raiseMemError
    1563          asciifields = "nnbP"
    1564          compactfields = asciifields + "nPn"
    1565          unicodefields = compactfields + "P"
    1566          for s in samples:
    1567              maxchar = ord(max(s))
    1568              if maxchar < 128:
    1569                  L = size(asciifields) + len(s) + 1
    1570              elif maxchar < 256:
    1571                  L = size(compactfields) + len(s) + 1
    1572              elif maxchar < 65536:
    1573                  L = size(compactfields) + 2*(len(s) + 1)
    1574              else:
    1575                  L = size(compactfields) + 4*(len(s) + 1)
    1576              check(s, L)
    1577          # verify that the UTF-8 size is accounted for
    1578          s = chr(0x4000)   # 4 bytes canonical representation
    1579          check(s, size(compactfields) + 4)
    1580          # compile() will trigger the generation of the UTF-8
    1581          # representation as a side effect
    1582          compile(s, "<stdin>", "eval")
    1583          check(s, size(compactfields) + 4 + 4)
    1584          # TODO: add check that forces the presence of wchar_t representation
    1585          # TODO: add check that forces layout of unicodefields
    1586          # weakref
    1587          import weakref
    1588          check(weakref.ref(int), size('2Pn3P'))
    1589          # weakproxy
    1590          # XXX
    1591          # weakcallableproxy
    1592          check(weakref.proxy(int), size('2Pn3P'))
    1593  
    1594      def check_slots(self, obj, base, extra):
    1595          expected = sys.getsizeof(base) + struct.calcsize(extra)
    1596          if gc.is_tracked(obj) and not gc.is_tracked(base):
    1597              expected += self.gc_headsize
    1598          self.assertEqual(sys.getsizeof(obj), expected)
    1599  
    1600      def test_slots(self):
    1601          # check all subclassable types defined in Objects/ that allow
    1602          # non-empty __slots__
    1603          check = self.check_slots
    1604          class ESC[4;38;5;81mBA(ESC[4;38;5;149mbytearray):
    1605              __slots__ = 'a', 'b', 'c'
    1606          check(BA(), bytearray(), '3P')
    1607          class ESC[4;38;5;81mD(ESC[4;38;5;149mdict):
    1608              __slots__ = 'a', 'b', 'c'
    1609          check(D(x=[]), {'x': []}, '3P')
    1610          class ESC[4;38;5;81mL(ESC[4;38;5;149mlist):
    1611              __slots__ = 'a', 'b', 'c'
    1612          check(L(), [], '3P')
    1613          class ESC[4;38;5;81mS(ESC[4;38;5;149mset):
    1614              __slots__ = 'a', 'b', 'c'
    1615          check(S(), set(), '3P')
    1616          class ESC[4;38;5;81mFS(ESC[4;38;5;149mfrozenset):
    1617              __slots__ = 'a', 'b', 'c'
    1618          check(FS(), frozenset(), '3P')
    1619          from collections import OrderedDict
    1620          class ESC[4;38;5;81mOD(ESC[4;38;5;149mOrderedDict):
    1621              __slots__ = 'a', 'b', 'c'
    1622          check(OD(x=[]), OrderedDict(x=[]), '3P')
    1623  
    1624      def test_pythontypes(self):
    1625          # check all types defined in Python/
    1626          size = test.support.calcobjsize
    1627          vsize = test.support.calcvobjsize
    1628          check = self.check_sizeof
    1629          # _ast.AST
    1630          import _ast
    1631          check(_ast.AST(), size('P'))
    1632          try:
    1633              raise TypeError
    1634          except TypeError:
    1635              tb = sys.exc_info()[2]
    1636              # traceback
    1637              if tb is not None:
    1638                  check(tb, size('2P2i'))
    1639          # symtable entry
    1640          # XXX
    1641          # sys.flags
    1642          check(sys.flags, vsize('') + self.P * len(sys.flags))
    1643  
    1644      def test_asyncgen_hooks(self):
    1645          old = sys.get_asyncgen_hooks()
    1646          self.assertIsNone(old.firstiter)
    1647          self.assertIsNone(old.finalizer)
    1648  
    1649          firstiter = lambda *a: None
    1650          sys.set_asyncgen_hooks(firstiter=firstiter)
    1651          hooks = sys.get_asyncgen_hooks()
    1652          self.assertIs(hooks.firstiter, firstiter)
    1653          self.assertIs(hooks[0], firstiter)
    1654          self.assertIs(hooks.finalizer, None)
    1655          self.assertIs(hooks[1], None)
    1656  
    1657          finalizer = lambda *a: None
    1658          sys.set_asyncgen_hooks(finalizer=finalizer)
    1659          hooks = sys.get_asyncgen_hooks()
    1660          self.assertIs(hooks.firstiter, firstiter)
    1661          self.assertIs(hooks[0], firstiter)
    1662          self.assertIs(hooks.finalizer, finalizer)
    1663          self.assertIs(hooks[1], finalizer)
    1664  
    1665          sys.set_asyncgen_hooks(*old)
    1666          cur = sys.get_asyncgen_hooks()
    1667          self.assertIsNone(cur.firstiter)
    1668          self.assertIsNone(cur.finalizer)
    1669  
    1670      def test_changing_sys_stderr_and_removing_reference(self):
    1671          # If the default displayhook doesn't take a strong reference
    1672          # to sys.stderr the following code can crash. See bpo-43660
    1673          # for more details.
    1674          code = textwrap.dedent('''
    1675              import sys
    1676              class MyStderr:
    1677                  def write(self, s):
    1678                      sys.stderr = None
    1679              sys.stderr = MyStderr()
    1680              1/0
    1681          ''')
    1682          rc, out, err = assert_python_failure('-c', code)
    1683          self.assertEqual(out, b"")
    1684          self.assertEqual(err, b"")
    1685  
    1686  if __name__ == "__main__":
    1687      unittest.main()