Debian Codegraph @

Lib/test/test_sys.py

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