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