Debian Codegraph @

lib-python/3/test/test_sys.py

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