Debian Codegraph @

tests/test/support/__init__.py

raw symbols SCIP
1 """Supporting definitions for the Python regression tests."""
2
3 if __name__ != 'test.support':
4 raise ImportError('support must be imported from the test package')
5
6 import contextlib
7 import functools
8 import inspect
9 import logging
10 import _opcode
11 import os
12 import re
13 import stat
14 import sys
15 import sysconfig
16 import textwrap
17 import time
18 import types
19 import unittest
20 import warnings
21
22 annotationlib = object()
23
24 __all__ = [
25 # globals
26 "PIPE_MAX_SIZE", "verbose", "max_memuse", "use_resources", "failfast",
27 # exceptions
28 "Error", "TestFailed", "TestDidNotRun", "ResourceDenied",
29 # io
30 "record_original_stdout", "get_original_stdout", "captured_stdout",
31 "captured_stdin", "captured_stderr", "captured_output",
32 # unittest
33 "is_resource_enabled", "get_resource_value", "requires", "requires_resource",
34 "requires_freebsd_version",
35 "requires_gil_enabled", "requires_linux_version", "requires_mac_ver",
36 "check_syntax_error",
37 "requires_gzip", "requires_bz2", "requires_lzma", "requires_zstd",
38 "bigmemtest", "nomemtest", "bigaddrspacetest", "cpython_only", "get_attribute",
39 "requires_IEEE_754", "requires_zlib",
40 "has_fork_support", "requires_fork",
41 "has_subprocess_support", "requires_subprocess",
42 "has_socket_support", "requires_working_socket",
43 "anticipate_failure", "load_package_tests", "detect_api_mismatch",
44 "check__all__", "skip_if_buggy_ucrt_strfptime",
45 "check_disallow_instantiation", "check_sanitizer", "skip_if_sanitizer",
46 "requires_limited_api", "requires_specialization", "thread_unsafe",
47 "skip_if_unlimited_stack_size", "skip_if_huge_c_stack",
48 "run_with_limited_c_stack",
49 # sys
50 "MS_WINDOWS", "is_jython", "is_android", "is_emscripten", "is_wasi",
51 "is_apple_mobile", "check_impl_detail", "unix_shell", "setswitchinterval",
52 "support_remote_exec_only",
53 # os
54 "get_pagesize",
55 # network
56 "open_urlresource",
57 # processes
58 "reap_children",
59 # miscellaneous
60 "run_with_locale", "swap_item", "findfile", "infinite_recursion",
61 "swap_attr", "Matcher", "set_memlimit", "SuppressCrashReport", "sortdict",
62 "run_with_tz", "PGO", "missing_compiler_executable",
63 "ALWAYS_EQ", "NEVER_EQ", "LARGEST", "SMALLEST",
64 "LOOPBACK_TIMEOUT", "INTERNET_TIMEOUT", "SHORT_TIMEOUT", "LONG_TIMEOUT",
65 "Py_DEBUG", "exceeds_recursion_limit", "skip_on_s390x",
66 "requires_jit_enabled",
67 "requires_jit_disabled",
68 "force_not_colorized",
69 "force_not_colorized_test_class",
70 "make_clean_env",
71 "BrokenIter",
72 "in_systemd_nspawn_sync_suppressed",
73 "run_no_yield_async_fn", "run_yielding_async_fn", "async_yield",
74 "reset_code", "on_github_actions"
75 ]
76
77
78 # Timeout in seconds for tests using a network server listening on the network
79 # local loopback interface like 127.0.0.1.
80 #
81 # The timeout is long enough to prevent test failure: it takes into account
82 # that the client and the server can run in different threads or even different
83 # processes.
84 #
85 # The timeout should be long enough for connect(), recv() and send() methods
86 # of socket.socket.
87 LOOPBACK_TIMEOUT = 10.0
88
89 # Timeout in seconds for network requests going to the internet. The timeout is
90 # short enough to prevent a test to wait for too long if the internet request
91 # is blocked for whatever reason.
92 #
93 # Usually, a timeout using INTERNET_TIMEOUT should not mark a test as failed,
94 # but skip the test instead: see transient_internet().
95 INTERNET_TIMEOUT = 60.0
96
97 # Timeout in seconds to mark a test as failed if the test takes "too long".
98 #
99 # The timeout value depends on the regrtest --timeout command line option.
100 #
101 # If a test using SHORT_TIMEOUT starts to fail randomly on slow buildbots, use
102 # LONG_TIMEOUT instead.
103 SHORT_TIMEOUT = 30.0
104
105 # Timeout in seconds to detect when a test hangs.
106 #
107 # It is long enough to reduce the risk of test failure on the slowest Python
108 # buildbots. It should not be used to mark a test as failed if the test takes
109 # "too long". The timeout value depends on the regrtest --timeout command line
110 # option.
111 LONG_TIMEOUT = 5 * 60.0
112
113 # TEST_HOME_DIR refers to the top level directory of the "test" package
114 # that contains Python's regression test suite
115 TEST_SUPPORT_DIR = os.path.dirname(os.path.abspath(__file__))
116 TEST_HOME_DIR = os.path.dirname(TEST_SUPPORT_DIR)
117 STDLIB_DIR = os.path.dirname(TEST_HOME_DIR)
118 REPO_ROOT = os.path.dirname(STDLIB_DIR)
119
120
121 class Error(Exception):
122 """Base class for regression test exceptions."""
123
124 class TestFailed(Error):
125 """Test failed."""
126 def __init__(self, msg, *args, stats=None):
127 self.msg = msg
128 self.stats = stats
129 super().__init__(msg, *args)
130
131 def __str__(self):
132 return self.msg
133
134 class TestFailedWithDetails(TestFailed):
135 """Test failed."""
136 def __init__(self, msg, errors, failures, stats):
137 self.errors = errors
138 self.failures = failures
139 super().__init__(msg, errors, failures, stats=stats)
140
141 class TestDidNotRun(Error):
142 """Test did not run any subtests."""
143
144 class ResourceDenied(unittest.SkipTest):
145 """Test skipped because it requested a disallowed resource.
146
147 This is raised when a test calls requires() for a resource that
148 has not be enabled. It is used to distinguish between expected
149 and unexpected skips.
150 """
151
152 def anticipate_failure(condition):
153 """Decorator to mark a test that is known to be broken in some cases
154
155 Any use of this decorator should have a comment identifying the
156 associated tracker issue.
157 """
158 if condition:
159 return unittest.expectedFailure
160 return lambda f: f
161
162 def load_package_tests(pkg_dir, loader, standard_tests, pattern):
163 """Generic load_tests implementation for simple test packages.
164
165 Most packages can implement load_tests using this function as follows:
166
167 def load_tests(*args):
168 return load_package_tests(os.path.dirname(__file__), *args)
169 """
170 if pattern is None:
171 pattern = "test*"
172 top_dir = STDLIB_DIR
173 package_tests = loader.discover(start_dir=pkg_dir,
174 top_level_dir=top_dir,
175 pattern=pattern)
176 standard_tests.addTests(package_tests)
177 return standard_tests
178
179
180 def get_attribute(obj, name):
181 """Get an attribute, raising SkipTest if AttributeError is raised."""
182 try:
183 attribute = getattr(obj, name)
184 except AttributeError:
185 raise unittest.SkipTest("object %r has no attribute %r" % (obj, name))
186 else:
187 return attribute
188
189 verbose = 1 # Flag set to 0 by regrtest.py
190 use_resources = None # Flag set to {} by regrtest.py
191 max_memuse = 0 # Disable bigmem tests (they will still be run with
192 # small sizes, to make sure they work.)
193 real_max_memuse = 0
194 junit_xml_list = None # list of testsuite XML elements
195 failfast = False
196
197 # _original_stdout is meant to hold stdout at the time regrtest began.
198 # This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
199 # The point is to have some flavor of stdout the user can actually see.
200 _original_stdout = None
201 def record_original_stdout(stdout):
202 global _original_stdout
203 _original_stdout = stdout
204
205 def get_original_stdout():
206 return _original_stdout or sys.stdout
207
208
209 def _force_run(path, func, *args):
210 try:
211 return func(*args)
212 except FileNotFoundError as err:
213 # chmod() won't fix a missing file.
214 if verbose >= 2:
215 print('%s: %s' % (err.__class__.__name__, err))
216 raise
217 except OSError as err:
218 if verbose >= 2:
219 print('%s: %s' % (err.__class__.__name__, err))
220 print('re-run %s%r' % (func.__name__, args))
221 os.chmod(path, stat.S_IRWXU)
222 return func(*args)
223
224
225 # Check whether a gui is actually available
226 def _is_gui_available():
227 if hasattr(_is_gui_available, 'result'):
228 return _is_gui_available.result
229 import platform
230 reason = None
231 if sys.platform.startswith('win') and platform.win32_is_iot():
232 reason = "gui is not available on Windows IoT Core"
233 elif sys.platform.startswith('win'):
234 # if Python is running as a service (such as the buildbot service),
235 # gui interaction may be disallowed
236 import ctypes
237 import ctypes.wintypes
238 UOI_FLAGS = 1
239 WSF_VISIBLE = 0x0001
240 class USEROBJECTFLAGS(ctypes.Structure):
241 _fields_ = [("fInherit", ctypes.wintypes.BOOL),
242 ("fReserved", ctypes.wintypes.BOOL),
243 ("dwFlags", ctypes.wintypes.DWORD)]
244 dll = ctypes.windll.user32
245 h = dll.GetProcessWindowStation()
246 if not h:
247 raise ctypes.WinError()
248 uof = USEROBJECTFLAGS()
249 needed = ctypes.wintypes.DWORD()
250 res = dll.GetUserObjectInformationW(h,
251 UOI_FLAGS,
252 ctypes.byref(uof),
253 ctypes.sizeof(uof),
254 ctypes.byref(needed))
255 if not res:
256 raise ctypes.WinError()
257 if not bool(uof.dwFlags & WSF_VISIBLE):
258 reason = "gui not available (WSF_VISIBLE flag not set)"
259 elif sys.platform == 'darwin':
260 # The Aqua Tk implementations on OS X can abort the process if
261 # being called in an environment where a window server connection
262 # cannot be made, for instance when invoked by a buildbot or ssh
263 # process not running under the same user id as the current console
264 # user. To avoid that, raise an exception if the window manager
265 # connection is not available.
266 import subprocess
267 try:
268 rc = subprocess.run(["launchctl", "managername"],
269 capture_output=True, check=True)
270 managername = rc.stdout.decode("utf-8").strip()
271 except subprocess.CalledProcessError:
272 reason = "unable to detect macOS launchd job manager"
273 else:
274 if managername != "Aqua":
275 reason = f"{managername=} -- can only run in a macOS GUI session"
276
277 # check on every platform whether tkinter can actually do anything
278 if not reason:
279 try:
280 from tkinter import Tk
281 root = Tk()
282 root.withdraw()
283 root.update()
284 root.destroy()
285 except Exception as e:
286 err_string = str(e)
287 if len(err_string) > 50:
288 err_string = err_string[:50] + ' [...]'
289 reason = 'Tk unavailable due to {}: {}'.format(type(e).__name__,
290 err_string)
291
292 _is_gui_available.reason = reason
293 _is_gui_available.result = not reason
294
295 return _is_gui_available.result
296
297 def is_resource_enabled(resource):
298 """Test whether a resource is enabled.
299
300 Known resources are set by regrtest.py. If not running under regrtest.py,
301 all resources are assumed enabled unless use_resources has been set.
302 """
303 return use_resources is None or resource in use_resources
304
305 def get_resource_value(resource):
306 """Test whether a resource is enabled.
307
308 Known resources are set by regrtest.py. If not running under regrtest.py,
309 all resources are assumed enabled unless use_resources has been set.
310 """
311 if use_resources is None:
312 return None
313 return use_resources.get(resource)
314
315 def requires(resource, msg=None):
316 """Raise ResourceDenied if the specified resource is not available."""
317 if not is_resource_enabled(resource):
318 if msg is None:
319 msg = "Use of the %r resource not enabled" % resource
320 raise ResourceDenied(msg)
321 if resource in {"network", "urlfetch"} and not has_socket_support:
322 raise ResourceDenied("No socket support")
323 if resource == 'gui' and not _is_gui_available():
324 raise ResourceDenied(_is_gui_available.reason)
325
326 def _get_kernel_version(sysname="Linux"):
327 import platform
328 if platform.system() != sysname:
329 return None
330 version_txt = platform.release().split('-', 1)[0]
331 try:
332 return tuple(map(int, version_txt.split('.')))
333 except ValueError:
334 return None
335
336 def _requires_unix_version(sysname, min_version):
337 """Decorator raising SkipTest if the OS is `sysname` and the version is less
338 than `min_version`.
339
340 For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if
341 the FreeBSD version is less than 7.2.
342 """
343 import platform
344 min_version_txt = '.'.join(map(str, min_version))
345 version_txt = platform.release().split('-', 1)[0]
346 if platform.system() == sysname:
347 try:
348 version = tuple(map(int, version_txt.split('.')))
349 except ValueError:
350 skip = False
351 else:
352 skip = version < min_version
353 else:
354 skip = False
355
356 return unittest.skipIf(
357 skip,
358 f"{sysname} version {min_version_txt} or higher required, not "
359 f"{version_txt}"
360 )
361
362
363 def requires_freebsd_version(*min_version):
364 """Decorator raising SkipTest if the OS is FreeBSD and the FreeBSD version is
365 less than `min_version`.
366
367 For example, @requires_freebsd_version(7, 2) raises SkipTest if the FreeBSD
368 version is less than 7.2.
369 """
370 return _requires_unix_version('FreeBSD', min_version)
371
372 def requires_linux_version(*min_version):
373 """Decorator raising SkipTest if the OS is Linux and the Linux version is
374 less than `min_version`.
375
376 For example, @requires_linux_version(2, 6, 32) raises SkipTest if the Linux
377 version is less than 2.6.32.
378 """
379 return _requires_unix_version('Linux', min_version)
380
381 def requires_mac_ver(*min_version):
382 """Decorator raising SkipTest if the OS is Mac OS X and the OS X
383 version if less than min_version.
384
385 For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
386 is lesser than 10.5.
387 """
388 def decorator(func):
389 @functools.wraps(func)
390 def wrapper(*args, **kw):
391 if sys.platform == 'darwin':
392 import platform
393 version_txt = platform.mac_ver()[0]
394 try:
395 version = tuple(map(int, version_txt.split('.')))
396 except ValueError:
397 pass
398 else:
399 if version < min_version:
400 min_version_txt = '.'.join(map(str, min_version))
401 raise unittest.SkipTest(
402 "Mac OS X %s or higher required, not %s"
403 % (min_version_txt, version_txt))
404 return func(*args, **kw)
405 wrapper.min_version = min_version
406 return wrapper
407 return decorator
408
409
410 def thread_unsafe(reason):
411 """Mark a test as not thread safe. When the test runner is run with
412 --parallel-threads=N, the test will be run in a single thread."""
413 def decorator(test_item):
414 test_item.__unittest_thread_unsafe__ = True
415 # the reason is not currently used
416 test_item.__unittest_thread_unsafe__why__ = reason
417 return test_item
418 if isinstance(reason, types.FunctionType):
419 test_item = reason
420 reason = ''
421 return decorator(test_item)
422 return decorator
423
424
425 def skip_if_buildbot(reason=None):
426 """Decorator raising SkipTest if running on a buildbot."""
427 import getpass
428 if not reason:
429 reason = 'not suitable for buildbots'
430 try:
431 isbuildbot = getpass.getuser().lower() == 'buildbot'
432 except (KeyError, OSError) as err:
433 logging.getLogger(__name__).warning('getpass.getuser() failed %s.', err, exc_info=err)
434 isbuildbot = False
435 return unittest.skipIf(isbuildbot, reason)
436
437 def check_sanitizer(*, address=False, memory=False, ub=False, thread=False,
438 function=True):
439 """Returns True if Python is compiled with sanitizer support"""
440 if not (address or memory or ub or thread):
441 raise ValueError('At least one of address, memory, ub or thread must be True')
442
443
444 cflags = sysconfig.get_config_var('CFLAGS') or ''
445 config_args = sysconfig.get_config_var('CONFIG_ARGS') or ''
446 memory_sanitizer = (
447 '-fsanitize=memory' in cflags or
448 '--with-memory-sanitizer' in config_args
449 )
450 address_sanitizer = (
451 '-fsanitize=address' in cflags or
452 '--with-address-sanitizer' in config_args
453 )
454 ub_sanitizer = (
455 '-fsanitize=undefined' in cflags or
456 '--with-undefined-behavior-sanitizer' in config_args
457 )
458 thread_sanitizer = (
459 '-fsanitize=thread' in cflags or
460 '--with-thread-sanitizer' in config_args
461 )
462 function_sanitizer = (
463 '-fsanitize=function' in cflags
464 )
465 return (
466 (memory and memory_sanitizer) or
467 (address and address_sanitizer) or
468 (ub and ub_sanitizer) or
469 (thread and thread_sanitizer) or
470 (function and function_sanitizer)
471 )
472
473
474 def skip_if_sanitizer(reason=None, *, address=False, memory=False, ub=False, thread=False):
475 """Decorator raising SkipTest if running with a sanitizer active."""
476 if not reason:
477 reason = 'not working with sanitizers active'
478 skip = check_sanitizer(address=address, memory=memory, ub=ub, thread=thread)
479 return unittest.skipIf(skip, reason)
480
481 # gh-89363: True if fork() can hang if Python is built with Address Sanitizer
482 # (ASAN): libasan race condition, dead lock in pthread_create().
483 HAVE_ASAN_FORK_BUG = check_sanitizer(address=True)
484
485
486 def set_sanitizer_env_var(env, option):
487 for name in ('ASAN_OPTIONS', 'MSAN_OPTIONS', 'UBSAN_OPTIONS', 'TSAN_OPTIONS'):
488 if name in env:
489 env[name] += f':{option}'
490 else:
491 env[name] = option
492
493
494 def system_must_validate_cert(f):
495 """Skip the test on TLS certificate validation failures."""
496 @functools.wraps(f)
497 def dec(*args, **kwargs):
498 try:
499 f(*args, **kwargs)
500 except OSError as e:
501 if "CERTIFICATE_VERIFY_FAILED" in str(e):
502 raise unittest.SkipTest("system does not contain "
503 "necessary certificates")
504 raise
505 return dec
506
507 # A constant likely larger than the underlying OS pipe buffer size, to
508 # make writes blocking.
509 # Windows limit seems to be around 512 B, and many Unix kernels have a
510 # 64 KiB pipe buffer size or 16 * PAGE_SIZE: take a few megs to be sure.
511 # (see issue #17835 for a discussion of this number).
512 PIPE_MAX_SIZE = 4 * 1024 * 1024 + 1
513
514 # A constant likely larger than the underlying OS socket buffer size, to make
515 # writes blocking.
516 # The socket buffer sizes can usually be tuned system-wide (e.g. through sysctl
517 # on Linux), or on a per-socket basis (SO_SNDBUF/SO_RCVBUF). See issue #18643
518 # for a discussion of this number.
519 SOCK_MAX_SIZE = 16 * 1024 * 1024 + 1
520
521 # decorator for skipping tests on non-IEEE 754 platforms
522 requires_IEEE_754 = unittest.skipUnless(
523 float.__getformat__("double").startswith("IEEE"),
524 "test requires IEEE 754 doubles")
525
526 def requires_zlib(reason='requires zlib'):
527 try:
528 import zlib
529 except ImportError:
530 zlib = None
531 return unittest.skipUnless(zlib, reason)
532
533 def requires_gzip(reason='requires gzip'):
534 try:
535 import gzip
536 except ImportError:
537 gzip = None
538 return unittest.skipUnless(gzip, reason)
539
540 def requires_bz2(reason='requires bz2'):
541 try:
542 import bz2
543 except ImportError:
544 bz2 = None
545 return unittest.skipUnless(bz2, reason)
546
547 def requires_lzma(reason='requires lzma'):
548 try:
549 import lzma
550 except ImportError:
551 lzma = None
552 return unittest.skipUnless(lzma, reason)
553
554 def requires_zstd(reason='requires zstd'):
555 return unittest.skipUnless(True, reason)
556
557 def has_no_debug_ranges():
558 try:
559 import _testcapi
560 except ImportError:
561 raise unittest.SkipTest("_testinternalcapi required")
562 return not _testcapi.config_get('code_debug_ranges')
563
564 def requires_debug_ranges(reason='requires co_positions / debug_ranges'):
565 try:
566 skip = has_no_debug_ranges()
567 except unittest.SkipTest as e:
568 skip = True
569 reason = e.args[0] if e.args else reason
570 return unittest.skipIf(skip, reason)
571
572
573 MS_WINDOWS = (sys.platform == 'win32')
574
575 # Is not actually used in tests, but is kept for compatibility.
576 is_jython = sys.platform.startswith('java')
577
578 is_android = sys.platform == "android"
579
580 def skip_android_selinux(name):
581 return unittest.skipIf(
582 sys.platform == "android", f"Android blocks {name} with SELinux"
583 )
584
585 if sys.platform not in {"win32", "vxworks", "ios", "tvos", "watchos"}:
586 unix_shell = '/system/bin/sh' if is_android else '/bin/sh'
587 else:
588 unix_shell = None
589
590 # wasm32-emscripten and -wasi are POSIX-like but do not
591 # have subprocess or fork support.
592 is_emscripten = sys.platform == "emscripten"
593 is_wasi = sys.platform == "wasi"
594
595 # Use is_wasm32 as a generic check for WebAssembly platforms.
596 is_wasm32 = is_emscripten or is_wasi
597
598 def skip_emscripten_stack_overflow():
599 return unittest.skipIf(is_emscripten, "Exhausts stack on Emscripten")
600
601 def skip_wasi_stack_overflow():
602 return unittest.skipIf(is_wasi, "Exhausts stack on WASI")
603
604 is_apple_mobile = sys.platform in {"ios", "tvos", "watchos"}
605 is_apple = is_apple_mobile or sys.platform == "darwin"
606
607 has_fork_support = hasattr(os, "fork") and not (
608 # WASM and Apple mobile platforms do not support subprocesses.
609 is_emscripten
610 or is_wasi
611 or is_apple_mobile
612
613 # Although Android supports fork, it's unsafe to call it from Python because
614 # all Android apps are multi-threaded.
615 or is_android
616 )
617
618 def requires_fork():
619 return unittest.skipUnless(has_fork_support, "requires working os.fork()")
620
621 has_subprocess_support = not (
622 # WASM and Apple mobile platforms do not support subprocesses.
623 is_emscripten
624 or is_wasi
625 or is_apple_mobile
626
627 # Although Android supports subproceses, they're almost never useful in
628 # practice (see PEP 738). And most of the tests that use them are calling
629 # sys.executable, which won't work when Python is embedded in an Android app.
630 or is_android
631 )
632
633 def requires_subprocess():
634 """Used for subprocess, os.spawn calls, fd inheritance"""
635 return unittest.skipUnless(has_subprocess_support, "requires subprocess support")
636
637 # Emscripten's socket emulation and WASI sockets have limitations.
638 has_socket_support = not (
639 is_emscripten
640 or is_wasi
641 )
642
643 def requires_working_socket(*, module=False):
644 """Skip tests or modules that require working sockets
645
646 Can be used as a function/class decorator or to skip an entire module.
647 """
648 msg = "requires socket support"
649 if module:
650 if not has_socket_support:
651 raise unittest.SkipTest(msg)
652 else:
653 return unittest.skipUnless(has_socket_support, msg)
654
655 # Does strftime() support glibc extension like '%4Y'?
656 has_strftime_extensions = False
657 if sys.platform != "win32":
658 # bpo-47037: Windows debug builds crash with "Debug Assertion Failed"
659 try:
660 has_strftime_extensions = time.strftime("%4Y") != "%4Y"
661 except ValueError:
662 pass
663
664 # Define the URL of a dedicated HTTP server for the network tests.
665 # The URL must use clear-text HTTP: no redirection to encrypted HTTPS.
666 TEST_HTTP_URL = "http://www.pythontest.net"
667
668 # Set by libregrtest/main.py so we can skip tests that are not
669 # useful for PGO
670 PGO = False
671
672 # Set by libregrtest/main.py if we are running the extended (time consuming)
673 # PGO task. If this is True, PGO is also True.
674 PGO_EXTENDED = False
675
676 # TEST_DATA_DIR is used as a target download location for remote resources
677 TEST_DATA_DIR = os.path.join(TEST_HOME_DIR, "data")
678
679
680 def darwin_malloc_err_warning(test_name):
681 """Assure user that loud errors generated by macOS libc's malloc are
682 expected."""
683 if sys.platform != 'darwin':
684 return
685
686 import shutil
687 msg = ' NOTICE '
688 detail = (f'{test_name} may generate "malloc can\'t allocate region"\n'
689 'warnings on macOS systems. This behavior is known. Do not\n'
690 'report a bug unless tests are also failing.\n'
691 'See https://github.com/python/cpython/issues/85100')
692
693 padding, _ = shutil.get_terminal_size()
694 print(msg.center(padding, '-'))
695 print(detail)
696 print('-' * padding)
697
698
699 def findfile(filename, subdir=None):
700 """Try to find a file on sys.path or in the test directory. If it is not
701 found the argument passed to the function is returned (this does not
702 necessarily signal failure; could still be the legitimate path).
703
704 Setting *subdir* indicates a relative path to use to find the file
705 rather than looking directly in the path directories.
706 """
707 if os.path.isabs(filename):
708 return filename
709 if subdir is not None:
710 filename = os.path.join(subdir, filename)
711 path = [TEST_HOME_DIR] + sys.path
712 for dn in path:
713 fn = os.path.join(dn, filename)
714 if os.path.exists(fn): return fn
715 return filename
716
717
718 def sortdict(dict):
719 "Like repr(dict), but in sorted order."
720 items = sorted(dict.items())
721 reprpairs = ["%r: %r" % pair for pair in items]
722 withcommas = ", ".join(reprpairs)
723 return "{%s}" % withcommas
724
725
726 def run_code(code: str, extra_names: "dict[str, object] | None" = None) -> dict[str, object]:
727 """Run a piece of code after dedenting it, and return its global namespace."""
728 ns = {}
729 if extra_names:
730 ns.update(extra_names)
731 exec(textwrap.dedent(code), ns)
732 return ns
733
734
735 def check_syntax_error(testcase, statement, errtext='', *, lineno=None, offset=None):
736 with testcase.assertRaisesRegex(SyntaxError, errtext) as cm:
737 compile(statement, '<test string>', 'exec')
738 err = cm.exception
739 testcase.assertIsNotNone(err.lineno)
740 if lineno is not None:
741 testcase.assertEqual(err.lineno, lineno)
742 testcase.assertIsNotNone(err.offset)
743 if offset is not None:
744 testcase.assertEqual(err.offset, offset)
745
746
747 def open_urlresource(url, *args, **kw):
748 import urllib.request, urllib.parse
749 from .os_helper import unlink
750 try:
751 import gzip
752 except ImportError:
753 gzip = None
754
755 check = kw.pop('check', None)
756
757 filename = urllib.parse.urlparse(url)[2].split('/')[-1] # '/': it's URL!
758
759 fn = os.path.join(TEST_DATA_DIR, filename)
760
761 def check_valid_file(fn):
762 f = open(fn, *args, **kw)
763 if check is None:
764 return f
765 elif check(f):
766 f.seek(0)
767 return f
768 f.close()
769
770 if os.path.exists(fn):
771 f = check_valid_file(fn)
772 if f is not None:
773 return f
774 unlink(fn)
775
776 # Verify the requirement before downloading the file
777 requires('urlfetch')
778
779 if verbose:
780 print('\tfetching %s ...' % url, file=get_original_stdout())
781 opener = urllib.request.build_opener()
782 if gzip:
783 opener.addheaders.append(('Accept-Encoding', 'gzip'))
784 f = opener.open(url, timeout=INTERNET_TIMEOUT)
785 if gzip and f.headers.get('Content-Encoding') == 'gzip':
786 f = gzip.GzipFile(fileobj=f)
787 try:
788 with open(fn, "wb") as out:
789 s = f.read()
790 while s:
791 out.write(s)
792 s = f.read()
793 finally:
794 f.close()
795
796 f = check_valid_file(fn)
797 if f is not None:
798 return f
799 raise TestFailed('invalid resource %r' % fn)
800
801
802 @contextlib.contextmanager
803 def captured_output(stream_name):
804 """Return a context manager used by captured_stdout/stdin/stderr
805 that temporarily replaces the sys stream *stream_name* with a StringIO."""
806 import io
807 orig_stdout = getattr(sys, stream_name)
808 setattr(sys, stream_name, io.StringIO())
809 try:
810 yield getattr(sys, stream_name)
811 finally:
812 setattr(sys, stream_name, orig_stdout)
813
814 def captured_stdout():
815 """Capture the output of sys.stdout:
816
817 with captured_stdout() as stdout:
818 print("hello")
819 self.assertEqual(stdout.getvalue(), "hello\\n")
820 """
821 return captured_output("stdout")
822
823 def captured_stderr():
824 """Capture the output of sys.stderr:
825
826 with captured_stderr() as stderr:
827 print("hello", file=sys.stderr)
828 self.assertEqual(stderr.getvalue(), "hello\\n")
829 """
830 return captured_output("stderr")
831
832 def captured_stdin():
833 """Capture the input to sys.stdin:
834
835 with captured_stdin() as stdin:
836 stdin.write('hello\\n')
837 stdin.seek(0)
838 # call test code that consumes from sys.stdin
839 captured = input()
840 self.assertEqual(captured, "hello")
841 """
842 return captured_output("stdin")
843
844
845 def gc_collect():
846 """Force as many objects as possible to be collected.
847
848 In non-CPython implementations of Python, this is needed because timely
849 deallocation is not guaranteed by the garbage collector. (Even in CPython
850 this can be the case in case of reference cycles.) This means that __del__
851 methods may be called later than expected and weakrefs may remain alive for
852 longer than expected. This function tries its best to force all garbage
853 objects to disappear.
854 """
855 import gc
856 gc.collect()
857 gc.collect()
858 gc.collect()
859
860 @contextlib.contextmanager
861 def disable_gc():
862 import gc
863 have_gc = gc.isenabled()
864 gc.disable()
865 try:
866 yield
867 finally:
868 if have_gc:
869 gc.enable()
870
871 @contextlib.contextmanager
872 def gc_threshold(*args):
873 import gc
874 old_threshold = gc.get_threshold()
875 gc.set_threshold(*args)
876 try:
877 yield
878 finally:
879 gc.set_threshold(*old_threshold)
880
881 def python_is_optimized():
882 """Find if Python was built with optimizations."""
883 cflags = sysconfig.get_config_var('PY_CFLAGS') or ''
884 final_opt = ""
885 for opt in cflags.split():
886 if opt.startswith('-O'):
887 final_opt = opt
888 if sysconfig.get_config_var("CC") == "gcc":
889 non_opts = ('', '-O0', '-Og')
890 else:
891 non_opts = ('', '-O0')
892 return final_opt not in non_opts
893
894
895 def check_cflags_pgo():
896 # Check if Python was built with ./configure --enable-optimizations:
897 # with Profile Guided Optimization (PGO).
898 cflags_nodist = sysconfig.get_config_var('PY_CFLAGS_NODIST') or ''
899 pgo_options = [
900 # GCC
901 '-fprofile-use',
902 # clang: -fprofile-instr-use=code.profclangd
903 '-fprofile-instr-use',
904 # ICC
905 "-prof-use",
906 ]
907 PGO_PROF_USE_FLAG = sysconfig.get_config_var('PGO_PROF_USE_FLAG')
908 if PGO_PROF_USE_FLAG:
909 pgo_options.append(PGO_PROF_USE_FLAG)
910 return any(option in cflags_nodist for option in pgo_options)
911
912
913 def check_bolt_optimized():
914 # Always return false, if the platform is WASI,
915 # because BOLT optimization does not support WASM binary.
916 if is_wasi:
917 return False
918 config_args = sysconfig.get_config_var('CONFIG_ARGS') or ''
919 return '--enable-bolt' in config_args
920
921
922 Py_GIL_DISABLED = bool(sysconfig.get_config_var('Py_GIL_DISABLED'))
923
924 def requires_gil_enabled(msg="needs the GIL enabled"):
925 """Decorator for skipping tests on the free-threaded build."""
926 return unittest.skipIf(Py_GIL_DISABLED, msg)
927
928 def expected_failure_if_gil_disabled():
929 """Expect test failure if the GIL is disabled."""
930 if Py_GIL_DISABLED:
931 return unittest.expectedFailure
932 return lambda test_case: test_case
933
934 if Py_GIL_DISABLED:
935 _header = 'PHBBInP'
936 else:
937 _header = 'nP'
938 _align = '0n'
939 _vheader = _header + 'n'
940
941 def calcobjsize(fmt):
942 import struct
943 return struct.calcsize(_header + fmt + _align)
944
945 def calcvobjsize(fmt):
946 import struct
947 return struct.calcsize(_vheader + fmt + _align)
948
949
950 _TPFLAGS_STATIC_BUILTIN = 1<<1
951 _TPFLAGS_DISALLOW_INSTANTIATION = 1<<7
952 _TPFLAGS_IMMUTABLETYPE = 1<<8
953 _TPFLAGS_HEAPTYPE = 1<<9
954 _TPFLAGS_BASETYPE = 1<<10
955 _TPFLAGS_READY = 1<<12
956 _TPFLAGS_READYING = 1<<13
957 _TPFLAGS_HAVE_GC = 1<<14
958 _TPFLAGS_BASE_EXC_SUBCLASS = 1<<30
959 _TPFLAGS_TYPE_SUBCLASS = 1<<31
960
961 def check_sizeof(test, o, size):
962 try:
963 import _testinternalcapi
964 except ImportError:
965 raise unittest.SkipTest("_testinternalcapi required")
966 result = sys.getsizeof(o)
967 # add GC header size
968 if ((type(o) == type) and (o.__flags__ & _TPFLAGS_HEAPTYPE) or\
969 ((type(o) != type) and (type(o).__flags__ & _TPFLAGS_HAVE_GC))):
970 size += _testinternalcapi.SIZEOF_PYGC_HEAD
971 msg = 'wrong size for %s: got %d, expected %d' \
972 % (type(o), result, size)
973 test.assertEqual(result, size, msg)
974
975 def subTests(arg_names, arg_values, /, *, _do_cleanups=False):
976 """Run multiple subtests with different parameters.
977 """
978 single_param = False
979 if isinstance(arg_names, str):
980 arg_names = arg_names.replace(',',' ').split()
981 if len(arg_names) == 1:
982 single_param = True
983 arg_values = tuple(arg_values)
984 def decorator(func):
985 if isinstance(func, type):
986 raise TypeError('subTests() can only decorate methods, not classes')
987 @functools.wraps(func)
988 def wrapper(self, /, *args, **kwargs):
989 for values in arg_values:
990 if single_param:
991 values = (values,)
992 subtest_kwargs = dict(zip(arg_names, values))
993 with self.subTest(**subtest_kwargs):
994 func(self, *args, **kwargs, **subtest_kwargs)
995 if _do_cleanups:
996 self.doCleanups()
997 return wrapper
998 return decorator
999
1000 #=======================================================================
1001 # Decorator/context manager for running a code in a different locale,
1002 # correctly resetting it afterwards.
1003
1004 @contextlib.contextmanager
1005 def run_with_locale(catstr, *locales):
1006 try:
1007 import locale
1008 category = getattr(locale, catstr)
1009 orig_locale = locale.setlocale(category)
1010 except AttributeError:
1011 # if the test author gives us an invalid category string
1012 raise
1013 except Exception:
1014 # cannot retrieve original locale, so do nothing
1015 locale = orig_locale = None
1016 if '' not in locales:
1017 raise unittest.SkipTest('no locales')
1018 else:
1019 for loc in locales:
1020 try:
1021 locale.setlocale(category, loc)
1022 break
1023 except locale.Error:
1024 pass
1025 else:
1026 if '' not in locales:
1027 raise unittest.SkipTest(f'no locales {locales}')
1028
1029 try:
1030 yield
1031 finally:
1032 if locale and orig_locale:
1033 locale.setlocale(category, orig_locale)
1034
1035 #=======================================================================
1036 # Decorator for running a function in multiple locales (if they are
1037 # availasble) and resetting the original locale afterwards.
1038
1039 def run_with_locales(catstr, *locales):
1040 def deco(func):
1041 @functools.wraps(func)
1042 def wrapper(self, /, *args, **kwargs):
1043 dry_run = '' in locales
1044 try:
1045 import locale
1046 category = getattr(locale, catstr)
1047 orig_locale = locale.setlocale(category)
1048 except AttributeError:
1049 # if the test author gives us an invalid category string
1050 raise
1051 except Exception:
1052 # cannot retrieve original locale, so do nothing
1053 pass
1054 else:
1055 try:
1056 for loc in locales:
1057 with self.subTest(locale=loc):
1058 try:
1059 locale.setlocale(category, loc)
1060 except locale.Error:
1061 self.skipTest(f'no locale {loc!r}')
1062 else:
1063 dry_run = False
1064 func(self, *args, **kwargs)
1065 finally:
1066 locale.setlocale(category, orig_locale)
1067 if dry_run:
1068 # no locales available, so just run the test
1069 # with the current locale
1070 with self.subTest(locale=None):
1071 func(self, *args, **kwargs)
1072 return wrapper
1073 return deco
1074
1075 #=======================================================================
1076 # Decorator for running a function in a specific timezone, correctly
1077 # resetting it afterwards.
1078
1079 def run_with_tz(tz):
1080 def decorator(func):
1081 def inner(*args, **kwds):
1082 try:
1083 tzset = time.tzset
1084 except AttributeError:
1085 raise unittest.SkipTest("tzset required")
1086 if 'TZ' in os.environ:
1087 orig_tz = os.environ['TZ']
1088 else:
1089 orig_tz = None
1090 os.environ['TZ'] = tz
1091 tzset()
1092
1093 # now run the function, resetting the tz on exceptions
1094 try:
1095 return func(*args, **kwds)
1096 finally:
1097 if orig_tz is None:
1098 del os.environ['TZ']
1099 else:
1100 os.environ['TZ'] = orig_tz
1101 time.tzset()
1102
1103 inner.__name__ = func.__name__
1104 inner.__doc__ = func.__doc__
1105 return inner
1106 return decorator
1107
1108 #=======================================================================
1109 # Big-memory-test support. Separate from 'resources' because memory use
1110 # should be configurable.
1111
1112 # Some handy shorthands. Note that these are used for byte-limits as well
1113 # as size-limits, in the various bigmem tests
1114 _1M = 1024*1024
1115 _1G = 1024 * _1M
1116 _2G = 2 * _1G
1117 _4G = 4 * _1G
1118
1119 MAX_Py_ssize_t = sys.maxsize
1120
1121 def _parse_memlimit(limit: str) -> int:
1122 sizes = {
1123 'k': 1024,
1124 'm': _1M,
1125 'g': _1G,
1126 't': 1024*_1G,
1127 }
1128 m = re.match(r'(\d+(?:\.\d+)?) (K|M|G|T)b?$', limit,
1129 re.IGNORECASE | re.VERBOSE)
1130 if m is None:
1131 raise ValueError(f'Invalid memory limit: {limit!r}')
1132 return int(float(m.group(1)) * sizes[m.group(2).lower()])
1133
1134 def set_memlimit(limit: str) -> None:
1135 global max_memuse
1136 global real_max_memuse
1137 memlimit = _parse_memlimit(limit)
1138 if memlimit < _2G - 1:
1139 raise ValueError(f'Memory limit {limit!r} too low to be useful')
1140
1141 real_max_memuse = memlimit
1142 memlimit = min(memlimit, MAX_Py_ssize_t)
1143 max_memuse = memlimit
1144
1145
1146 class _MemoryWatchdog:
1147 """An object which periodically watches the process' memory consumption
1148 and prints it out.
1149 """
1150
1151 def __init__(self):
1152 self.procfile = '/proc/{pid}/statm'.format(pid=os.getpid())
1153 self.started = False
1154
1155 def start(self):
1156 import warnings
1157 try:
1158 f = open(self.procfile, 'r')
1159 except OSError as e:
1160 logging.getLogger(__name__).warning('/proc not available for stats: %s', e, exc_info=e)
1161 sys.stderr.flush()
1162 return
1163
1164 import subprocess
1165 with f:
1166 watchdog_script = findfile("memory_watchdog.py")
1167 self.mem_watchdog = subprocess.Popen([sys.executable, watchdog_script],
1168 stdin=f,
1169 stderr=subprocess.DEVNULL)
1170 self.started = True
1171
1172 def stop(self):
1173 if self.started:
1174 self.mem_watchdog.terminate()
1175 self.mem_watchdog.wait()
1176
1177
1178 def bigmemtest(size, memuse, dry_run=True):
1179 """Decorator for bigmem tests.
1180
1181 'size' is a requested size for the test (in arbitrary, test-interpreted
1182 units.) 'memuse' is the number of bytes per unit for the test, or a good
1183 estimate of it. For example, a test that needs two byte buffers, of 4 GiB
1184 each, could be decorated with @bigmemtest(size=_4G, memuse=2).
1185
1186 The 'size' argument is normally passed to the decorated test method as an
1187 extra argument. If 'dry_run' is true, the value passed to the test method
1188 may be less than the requested value. If 'dry_run' is false, it means the
1189 test doesn't support dummy runs when -M is not specified.
1190 """
1191 def decorator(f):
1192 def wrapper(self):
1193 size = wrapper.size
1194 memuse = wrapper.memuse
1195 if not real_max_memuse:
1196 maxsize = 5147
1197 else:
1198 maxsize = size
1199
1200 if ((real_max_memuse or not dry_run)
1201 and real_max_memuse < maxsize * memuse):
1202 raise unittest.SkipTest(
1203 "not enough memory: %.1fG minimum needed"
1204 % (size * memuse / (1024 ** 3)))
1205
1206 if real_max_memuse and verbose:
1207 print()
1208 print(" ... expected peak memory use: {peak:.1f}G"
1209 .format(peak=size * memuse / (1024 ** 3)))
1210 watchdog = _MemoryWatchdog()
1211 watchdog.start()
1212 else:
1213 watchdog = None
1214
1215 try:
1216 return f(self, maxsize)
1217 finally:
1218 if watchdog:
1219 watchdog.stop()
1220
1221 wrapper.size = size
1222 wrapper.memuse = memuse
1223 return wrapper
1224 return decorator
1225
1226 def nomemtest(f):
1227 """Check that we can use this test with `_testcapi.set_nomemory`."""
1228 from .import_helper import import_module
1229
1230 @functools.wraps(f)
1231 def internal(*args, **kwargs):
1232 import_module('_testcapi')
1233 return f(*args, **kwargs)
1234
1235 return unittest.skipIf(
1236 # Python built with Py_TRACE_REFS fail with a fatal error in
1237 # _PyRefchain_Trace() on memory allocation error.
1238 Py_TRACE_REFS,
1239 'cannot test Py_TRACE_REFS build',
1240 )(cpython_only(internal))
1241
1242 def bigaddrspacetest(f):
1243 """Decorator for tests that fill the address space."""
1244 def wrapper(self):
1245 if max_memuse < MAX_Py_ssize_t:
1246 if MAX_Py_ssize_t >= 2**63 - 1 and max_memuse >= 2**31:
1247 raise unittest.SkipTest(
1248 "not enough memory: try a 32-bit build instead")
1249 else:
1250 raise unittest.SkipTest(
1251 "not enough memory: %.1fG minimum needed"
1252 % (MAX_Py_ssize_t / (1024 ** 3)))
1253 else:
1254 return f(self)
1255 return wrapper
1256
1257 #=======================================================================
1258 # unittest integration.
1259
1260 def _id(obj):
1261 return obj
1262
1263 def requires_resource(resource):
1264 if resource == 'gui' and not _is_gui_available():
1265 return unittest.skip(_is_gui_available.reason)
1266 if is_resource_enabled(resource):
1267 return _id
1268 else:
1269 return unittest.skip("resource {0!r} is not enabled".format(resource))
1270
1271 def cpython_only(test):
1272 """
1273 Decorator for tests only applicable on CPython.
1274 """
1275 return impl_detail(cpython=True)(test)
1276
1277 def impl_detail(msg=None, **guards):
1278 if check_impl_detail(**guards):
1279 return _id
1280 if msg is None:
1281 guardnames, default = _parse_guards(guards)
1282 if default:
1283 msg = "implementation detail not available on {0}"
1284 else:
1285 msg = "implementation detail specific to {0}"
1286 guardnames = sorted(guardnames.keys())
1287 msg = msg.format(' or '.join(guardnames))
1288 return unittest.skip(msg)
1289
1290 def _parse_guards(guards):
1291 # Returns a tuple ({platform_name: run_me}, default_value)
1292 if not guards:
1293 return ({'cpython': True}, False)
1294 is_true = list(guards.values())[0]
1295 assert list(guards.values()) == [is_true] * len(guards) # all True or all False
1296 return (guards, not is_true)
1297
1298 # Use the following check to guard CPython's implementation-specific tests --
1299 # or to run them only on the implementation(s) guarded by the arguments.
1300 def check_impl_detail(**guards):
1301 """This function returns True or False depending on the host platform.
1302 Examples:
1303 if check_impl_detail(): # only on CPython (default)
1304 if check_impl_detail(jython=True): # only on Jython
1305 if check_impl_detail(cpython=False): # everywhere except on CPython
1306 """
1307 guards, default = _parse_guards(guards)
1308 return guards.get(sys.implementation.name, default)
1309
1310
1311 def no_tracing(func):
1312 """Decorator to temporarily turn off tracing for the duration of a test."""
1313 trace_wrapper = func
1314 if hasattr(sys, 'gettrace'):
1315 @functools.wraps(func)
1316 def trace_wrapper(*args, **kwargs):
1317 original_trace = sys.gettrace()
1318 try:
1319 sys.settrace(None)
1320 return func(*args, **kwargs)
1321 finally:
1322 sys.settrace(original_trace)
1323
1324 coverage_wrapper = trace_wrapper
1325 if 'test.cov' in sys.modules: # -Xpresite=test.cov used
1326 cov = sys.monitoring.COVERAGE_ID
1327 @functools.wraps(func)
1328 def coverage_wrapper(*args, **kwargs):
1329 original_events = sys.monitoring.get_events(cov)
1330 try:
1331 sys.monitoring.set_events(cov, 0)
1332 return trace_wrapper(*args, **kwargs)
1333 finally:
1334 sys.monitoring.set_events(cov, original_events)
1335
1336 return coverage_wrapper
1337
1338
1339 def no_rerun(reason):
1340 """Skip rerunning for a particular test.
1341
1342 WARNING: Use this decorator with care; skipping rerunning makes it
1343 impossible to find reference leaks. Provide a clear reason for skipping the
1344 test using the 'reason' parameter.
1345 """
1346 def deco(func):
1347 assert not isinstance(func, type), func
1348 _has_run = False
1349 def wrapper(self):
1350 nonlocal _has_run
1351 if _has_run:
1352 self.skipTest(reason)
1353 func(self)
1354 _has_run = True
1355 return wrapper
1356 return deco
1357
1358
1359 def refcount_test(test):
1360 """Decorator for tests which involve reference counting.
1361
1362 To start, the decorator does not run the test if is not run by CPython.
1363 After that, any trace function is unset during the test to prevent
1364 unexpected refcounts caused by the trace function.
1365
1366 """
1367 return no_tracing(cpython_only(test))
1368
1369
1370 def requires_limited_api(test):
1371 try:
1372 import _testcapi # noqa: F401
1373 import _testlimitedcapi # noqa: F401
1374 except ImportError:
1375 return unittest.skip('needs _testcapi and _testlimitedcapi modules')(test)
1376 return test
1377
1378
1379 # Windows build doesn't support --disable-test-modules feature, so there's no
1380 # 'TEST_MODULES' var in config
1381 TEST_MODULES_ENABLED = (sysconfig.get_config_var('TEST_MODULES') or 'yes') == 'yes'
1382
1383 def requires_specialization(test):
1384 return unittest.skipUnless(
1385 _opcode.ENABLE_SPECIALIZATION, "requires specialization")(test)
1386
1387
1388 def requires_specialization_ft(test):
1389 return unittest.skipUnless(
1390 _opcode.ENABLE_SPECIALIZATION_FT, "requires specialization")(test)
1391
1392
1393 def reset_code(f: types.FunctionType) -> types.FunctionType:
1394 """Clear all specializations, local instrumentation, and JIT code for the given function."""
1395 f.__code__ = f.__code__.replace()
1396 return f
1397
1398 on_github_actions = "GITHUB_ACTIONS" in os.environ
1399
1400 #=======================================================================
1401 # Check for the presence of docstrings.
1402
1403 # Rather than trying to enumerate all the cases where docstrings may be
1404 # disabled, we just check for that directly
1405
1406 def _check_docstrings():
1407 """Just used to check if docstrings are enabled"""
1408
1409 MISSING_C_DOCSTRINGS = (check_impl_detail() and
1410 sys.platform != 'win32' and
1411 not sysconfig.get_config_var('WITH_DOC_STRINGS'))
1412
1413 HAVE_PY_DOCSTRINGS = _check_docstrings.__doc__ is not None
1414 HAVE_DOCSTRINGS = (HAVE_PY_DOCSTRINGS and not MISSING_C_DOCSTRINGS)
1415
1416 requires_docstrings = unittest.skipUnless(HAVE_DOCSTRINGS,
1417 "test requires docstrings")
1418
1419
1420 #=======================================================================
1421 # Support for saving and restoring the imported modules.
1422
1423 def flush_std_streams():
1424 if sys.stdout is not None:
1425 sys.stdout.flush()
1426 if sys.stderr is not None:
1427 sys.stderr.flush()
1428
1429
1430 def print_warning(msg):
1431 # bpo-45410: Explicitly flush stdout to keep logs in order
1432 flush_std_streams()
1433 stream = print_warning.orig_stderr
1434 for line in msg.splitlines():
1435 print(f"Warning -- {line}", file=stream)
1436 stream.flush()
1437
1438 # bpo-39983: Store the original sys.stderr at Python startup to be able to
1439 # log warnings even if sys.stderr is captured temporarily by a test.
1440 print_warning.orig_stderr = sys.stderr
1441
1442
1443 # Flag used by saved_test_environment of test.libregrtest.save_env,
1444 # to check if a test modified the environment. The flag should be set to False
1445 # before running a new test.
1446 #
1447 # For example, threading_helper.threading_cleanup() sets the flag is the function fails
1448 # to cleanup threads.
1449 environment_altered = False
1450
1451 def reap_children():
1452 """Use this function at the end of test_main() whenever sub-processes
1453 are started. This will help ensure that no extra children (zombies)
1454 stick around to hog resources and create problems when looking
1455 for refleaks.
1456 """
1457 global environment_altered
1458
1459 # Need os.waitpid(-1, os.WNOHANG): Windows is not supported
1460 if not (hasattr(os, 'waitpid') and hasattr(os, 'WNOHANG')):
1461 return
1462 elif not has_subprocess_support:
1463 return
1464
1465 # Reap all our dead child processes so we don't leave zombies around.
1466 # These hog resources and might be causing some of the buildbots to die.
1467 while True:
1468 try:
1469 # Read the exit status of any child process which already completed
1470 pid, status = os.waitpid(-1, os.WNOHANG)
1471 except OSError:
1472 break
1473
1474 if pid == 0:
1475 break
1476
1477 print_warning(f"reap_children() reaped child process {pid}")
1478 environment_altered = True
1479
1480
1481 @contextlib.contextmanager
1482 def swap_attr(obj, attr, new_val):
1483 """Temporary swap out an attribute with a new object.
1484
1485 Usage:
1486 with swap_attr(obj, "attr", 5):
1487 ...
1488
1489 This will set obj.attr to 5 for the duration of the with: block,
1490 restoring the old value at the end of the block. If `attr` doesn't
1491 exist on `obj`, it will be created and then deleted at the end of the
1492 block.
1493
1494 The old value (or None if it doesn't exist) will be assigned to the
1495 target of the "as" clause, if there is one.
1496 """
1497 if hasattr(obj, attr):
1498 real_val = getattr(obj, attr)
1499 setattr(obj, attr, new_val)
1500 try:
1501 yield real_val
1502 finally:
1503 setattr(obj, attr, real_val)
1504 else:
1505 setattr(obj, attr, new_val)
1506 try:
1507 yield
1508 finally:
1509 if hasattr(obj, attr):
1510 delattr(obj, attr)
1511
1512 @contextlib.contextmanager
1513 def swap_item(obj, item, new_val):
1514 """Temporary swap out an item with a new object.
1515
1516 Usage:
1517 with swap_item(obj, "item", 5):
1518 ...
1519
1520 This will set obj["item"] to 5 for the duration of the with: block,
1521 restoring the old value at the end of the block. If `item` doesn't
1522 exist on `obj`, it will be created and then deleted at the end of the
1523 block.
1524
1525 The old value (or None if it doesn't exist) will be assigned to the
1526 target of the "as" clause, if there is one.
1527 """
1528 if item in obj:
1529 real_val = obj[item]
1530 obj[item] = new_val
1531 try:
1532 yield real_val
1533 finally:
1534 obj[item] = real_val
1535 else:
1536 obj[item] = new_val
1537 try:
1538 yield
1539 finally:
1540 if item in obj:
1541 del obj[item]
1542
1543 def args_from_interpreter_flags():
1544 """Return a list of command-line arguments reproducing the current
1545 settings in sys.flags and sys.warnoptions."""
1546 import subprocess
1547 return subprocess._args_from_interpreter_flags()
1548
1549 def optim_args_from_interpreter_flags():
1550 """Return a list of command-line arguments reproducing the current
1551 optimization settings in sys.flags."""
1552 import subprocess
1553 return subprocess._optim_args_from_interpreter_flags()
1554
1555
1556 class Matcher(object):
1557
1558 _partial_matches = ('msg', 'message')
1559
1560 def matches(self, d, **kwargs):
1561 """
1562 Try to match a single dict with the supplied arguments.
1563
1564 Keys whose values are strings and which are in self._partial_matches
1565 will be checked for partial (i.e. substring) matches. You can extend
1566 this scheme to (for example) do regular expression matching, etc.
1567 """
1568 result = True
1569 for k in kwargs:
1570 v = kwargs[k]
1571 dv = d.get(k)
1572 if not self.match_value(k, dv, v):
1573 result = False
1574 break
1575 return result
1576
1577 def match_value(self, k, dv, v):
1578 """
1579 Try to match a single stored value (dv) with a supplied value (v).
1580 """
1581 if type(v) != type(dv):
1582 result = False
1583 elif type(dv) is not str or k not in self._partial_matches:
1584 result = (v == dv)
1585 else:
1586 result = dv.find(v) >= 0
1587 return result
1588
1589
1590 _buggy_ucrt = None
1591 def skip_if_buggy_ucrt_strfptime(test):
1592 """
1593 Skip decorator for tests that use buggy strptime/strftime
1594
1595 If the UCRT bugs are present time.localtime().tm_zone will be
1596 an empty string, otherwise we assume the UCRT bugs are fixed
1597
1598 See bpo-37552 [Windows] strptime/strftime return invalid
1599 results with UCRT version 17763.615
1600 """
1601 import locale
1602 global _buggy_ucrt
1603 if _buggy_ucrt is None:
1604 if(sys.platform == 'win32' and
1605 locale.getencoding() == 'cp65001' and
1606 time.localtime().tm_zone == ''):
1607 _buggy_ucrt = True
1608 else:
1609 _buggy_ucrt = False
1610 return unittest.skip("buggy MSVC UCRT strptime/strftime")(test) if _buggy_ucrt else test
1611
1612 class PythonSymlink:
1613 """Creates a symlink for the current Python executable"""
1614 def __init__(self, link=None):
1615 from .os_helper import TESTFN
1616
1617 self.link = link or os.path.abspath(TESTFN)
1618 self._linked = []
1619 self.real = os.path.realpath(sys.executable)
1620 self._also_link = []
1621
1622 self._env = None
1623
1624 self._platform_specific()
1625
1626 if sys.platform == "win32":
1627 def _platform_specific(self):
1628 import glob
1629 import _winapi
1630
1631 if os.path.lexists(self.real) and not os.path.exists(self.real):
1632 # App symlink appears to not exist, but we want the
1633 # real executable here anyway
1634 self.real = _winapi.GetModuleFileName(0)
1635
1636 dll = _winapi.GetModuleFileName(sys.dllhandle)
1637 src_dir = os.path.dirname(dll)
1638 dest_dir = os.path.dirname(self.link)
1639 self._also_link.append((
1640 dll,
1641 os.path.join(dest_dir, os.path.basename(dll))
1642 ))
1643 for runtime in glob.glob(os.path.join(glob.escape(src_dir), "vcruntime*.dll")):
1644 self._also_link.append((
1645 runtime,
1646 os.path.join(dest_dir, os.path.basename(runtime))
1647 ))
1648
1649 self._env = {k.upper(): os.getenv(k) for k in os.environ}
1650 self._env["PYTHONHOME"] = os.path.dirname(self.real)
1651 if sysconfig.is_python_build():
1652 self._env["PYTHONPATH"] = STDLIB_DIR
1653 else:
1654 def _platform_specific(self):
1655 pass
1656
1657 def __enter__(self):
1658 os.symlink(self.real, self.link)
1659 self._linked.append(self.link)
1660 for real, link in self._also_link:
1661 os.symlink(real, link)
1662 self._linked.append(link)
1663 return self
1664
1665 def __exit__(self, exc_type, exc_value, exc_tb):
1666 for link in self._linked:
1667 try:
1668 os.remove(link)
1669 except IOError as ex:
1670 if verbose:
1671 print("failed to clean up {}: {}".format(link, ex))
1672
1673 def _call(self, python, args, env, returncode):
1674 import subprocess
1675 cmd = [python, *args]
1676 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
1677 stderr=subprocess.PIPE, env=env)
1678 r = p.communicate()
1679 if p.returncode != returncode:
1680 if verbose:
1681 print(repr(r[0]))
1682 print(repr(r[1]), file=sys.stderr)
1683 raise RuntimeError(
1684 'unexpected return code: {0} (0x{0:08X})'.format(p.returncode))
1685 return r
1686
1687 def call_real(self, *args, returncode=0):
1688 return self._call(self.real, args, None, returncode)
1689
1690 def call_link(self, *args, returncode=0):
1691 return self._call(self.link, args, self._env, returncode)
1692
1693
1694 def skip_if_pgo_task(test):
1695 """Skip decorator for tests not run in (non-extended) PGO task"""
1696 ok = not PGO or PGO_EXTENDED
1697 msg = "Not run for (non-extended) PGO task"
1698 return test if ok else unittest.skip(msg)(test)
1699
1700
1701 def skip_if_unlimited_stack_size(test):
1702 """Skip decorator for tests not run when an unlimited stack size is configured.
1703
1704 Tests using support.infinite_recursion([...]) may otherwise run into
1705 an infinite loop, running until the memory on the system is filled and
1706 crashing due to OOM.
1707
1708 See https://github.com/python/cpython/issues/143460.
1709 """
1710 if is_emscripten or is_wasi or os.name == "nt":
1711 return test
1712
1713 import resource
1714 curlim, maxlim = resource.getrlimit(resource.RLIMIT_STACK)
1715 unlimited_stack_size_cond = curlim == maxlim and curlim in (-1, 0xFFFF_FFFF_FFFF_FFFF)
1716 reason = "Not run due to unlimited stack size"
1717 return unittest.skipIf(unlimited_stack_size_cond, reason)(test)
1718
1719
1720 def detect_api_mismatch(ref_api, other_api, *, ignore=()):
1721 """Returns the set of items in ref_api not in other_api, except for a
1722 defined list of items to be ignored in this check.
1723
1724 By default this skips private attributes beginning with '_' but
1725 includes all magic methods, i.e. those starting and ending in '__'.
1726 """
1727 missing_items = set(dir(ref_api)) - set(dir(other_api))
1728 if ignore:
1729 missing_items -= set(ignore)
1730 missing_items = set(m for m in missing_items
1731 if not m.startswith('_') or m.endswith('__'))
1732 return missing_items
1733
1734
1735 def check__all__(test_case, module, name_of_module=None, extra=(),
1736 not_exported=()):
1737 """Assert that the __all__ variable of 'module' contains all public names.
1738
1739 The module's public names (its API) are detected automatically based on
1740 whether they match the public name convention and were defined in
1741 'module'.
1742
1743 The 'name_of_module' argument can specify (as a string or tuple thereof)
1744 what module(s) an API could be defined in order to be detected as a
1745 public API. One case for this is when 'module' imports part of its public
1746 API from other modules, possibly a C backend (like 'csv' and its '_csv').
1747
1748 The 'extra' argument can be a set of names that wouldn't otherwise be
1749 automatically detected as "public", like objects without a proper
1750 '__module__' attribute. If provided, it will be added to the
1751 automatically detected ones.
1752
1753 The 'not_exported' argument can be a set of names that must not be treated
1754 as part of the public API even though their names indicate otherwise.
1755
1756 Usage:
1757 import bar
1758 import foo
1759 import unittest
1760 from test import support
1761
1762 class MiscTestCase(unittest.TestCase):
1763 def test__all__(self):
1764 support.check__all__(self, foo)
1765
1766 class OtherTestCase(unittest.TestCase):
1767 def test__all__(self):
1768 extra = {'BAR_CONST', 'FOO_CONST'}
1769 not_exported = {'baz'} # Undocumented name.
1770 # bar imports part of its API from _bar.
1771 support.check__all__(self, bar, ('bar', '_bar'),
1772 extra=extra, not_exported=not_exported)
1773
1774 """
1775
1776 if name_of_module is None:
1777 name_of_module = (module.__name__, )
1778 elif isinstance(name_of_module, str):
1779 name_of_module = (name_of_module, )
1780
1781 expected = set(extra)
1782
1783 for name in dir(module):
1784 if name.startswith('_') or name in not_exported:
1785 continue
1786 obj = getattr(module, name)
1787 if (getattr(obj, '__module__', None) in name_of_module or
1788 (not hasattr(obj, '__module__') and
1789 not isinstance(obj, types.ModuleType))):
1790 expected.add(name)
1791 test_case.assertCountEqual(module.__all__, expected)
1792
1793
1794 def suppress_msvcrt_asserts(verbose=False):
1795 try:
1796 import msvcrt
1797 except ImportError:
1798 return
1799
1800 msvcrt.SetErrorMode(msvcrt.SEM_FAILCRITICALERRORS
1801 | msvcrt.SEM_NOALIGNMENTFAULTEXCEPT
1802 | msvcrt.SEM_NOGPFAULTERRORBOX
1803 | msvcrt.SEM_NOOPENFILEERRORBOX)
1804
1805 # CrtSetReportMode() is only available in debug build
1806 if hasattr(msvcrt, 'CrtSetReportMode'):
1807 for m in [msvcrt.CRT_WARN, msvcrt.CRT_ERROR, msvcrt.CRT_ASSERT]:
1808 if verbose:
1809 msvcrt.CrtSetReportMode(m, msvcrt.CRTDBG_MODE_FILE)
1810 msvcrt.CrtSetReportFile(m, msvcrt.CRTDBG_FILE_STDERR)
1811 else:
1812 msvcrt.CrtSetReportMode(m, 0)
1813
1814
1815 class SuppressCrashReport:
1816 """Try to prevent a crash report from popping up.
1817
1818 On Windows, don't display the Windows Error Reporting dialog. On UNIX,
1819 disable the creation of coredump file.
1820 """
1821 old_value = None
1822 old_modes = None
1823
1824 def __enter__(self):
1825 """On Windows, disable Windows Error Reporting dialogs using
1826 SetErrorMode() and CrtSetReportMode().
1827
1828 On UNIX, try to save the previous core file size limit, then set
1829 soft limit to 0.
1830 """
1831 if sys.platform.startswith('win'):
1832 # see http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx
1833 try:
1834 import msvcrt
1835 except ImportError:
1836 return
1837
1838 self.old_value = msvcrt.GetErrorMode()
1839
1840 msvcrt.SetErrorMode(self.old_value | msvcrt.SEM_NOGPFAULTERRORBOX)
1841
1842 # bpo-23314: Suppress assert dialogs in debug builds.
1843 # CrtSetReportMode() is only available in debug build.
1844 if hasattr(msvcrt, 'CrtSetReportMode'):
1845 self.old_modes = {}
1846 for report_type in [msvcrt.CRT_WARN,
1847 msvcrt.CRT_ERROR,
1848 msvcrt.CRT_ASSERT]:
1849 old_mode = msvcrt.CrtSetReportMode(report_type,
1850 msvcrt.CRTDBG_MODE_FILE)
1851 old_file = msvcrt.CrtSetReportFile(report_type,
1852 msvcrt.CRTDBG_FILE_STDERR)
1853 self.old_modes[report_type] = old_mode, old_file
1854
1855 else:
1856 try:
1857 import resource
1858 self.resource = resource
1859 except ImportError:
1860 self.resource = None
1861 if self.resource is not None:
1862 try:
1863 self.old_value = self.resource.getrlimit(self.resource.RLIMIT_CORE)
1864 self.resource.setrlimit(self.resource.RLIMIT_CORE,
1865 (0, self.old_value[1]))
1866 except (ValueError, OSError):
1867 pass
1868
1869 if sys.platform == 'darwin':
1870 import subprocess
1871 # Check if the 'Crash Reporter' on OSX was configured
1872 # in 'Developer' mode and warn that it will get triggered
1873 # when it is.
1874 #
1875 # This assumes that this context manager is used in tests
1876 # that might trigger the next manager.
1877 cmd = ['/usr/bin/defaults', 'read',
1878 'com.apple.CrashReporter', 'DialogType']
1879 proc = subprocess.Popen(cmd,
1880 stdout=subprocess.PIPE,
1881 stderr=subprocess.PIPE)
1882 with proc:
1883 stdout = proc.communicate()[0]
1884 if stdout.strip() == b'developer':
1885 print("this test triggers the Crash Reporter, "
1886 "that is intentional", end='', flush=True)
1887
1888 return self
1889
1890 def __exit__(self, *ignore_exc):
1891 """Restore Windows ErrorMode or core file behavior to initial value."""
1892 if self.old_value is None:
1893 return
1894
1895 if sys.platform.startswith('win'):
1896 import msvcrt
1897 msvcrt.SetErrorMode(self.old_value)
1898
1899 if self.old_modes:
1900 for report_type, (old_mode, old_file) in self.old_modes.items():
1901 msvcrt.CrtSetReportMode(report_type, old_mode)
1902 msvcrt.CrtSetReportFile(report_type, old_file)
1903 else:
1904 if self.resource is not None:
1905 try:
1906 self.resource.setrlimit(self.resource.RLIMIT_CORE, self.old_value)
1907 except (ValueError, OSError):
1908 pass
1909
1910
1911 def patch(test_instance, object_to_patch, attr_name, new_value):
1912 """Override 'object_to_patch'.'attr_name' with 'new_value'.
1913
1914 Also, add a cleanup procedure to 'test_instance' to restore
1915 'object_to_patch' value for 'attr_name'.
1916 The 'attr_name' should be a valid attribute for 'object_to_patch'.
1917
1918 """
1919 # check that 'attr_name' is a real attribute for 'object_to_patch'
1920 # will raise AttributeError if it does not exist
1921 getattr(object_to_patch, attr_name)
1922
1923 # keep a copy of the old value
1924 attr_is_local = False
1925 try:
1926 old_value = object_to_patch.__dict__[attr_name]
1927 except (AttributeError, KeyError):
1928 old_value = getattr(object_to_patch, attr_name, None)
1929 else:
1930 attr_is_local = True
1931
1932 # restore the value when the test is done
1933 def cleanup():
1934 if attr_is_local:
1935 setattr(object_to_patch, attr_name, old_value)
1936 else:
1937 delattr(object_to_patch, attr_name)
1938
1939 test_instance.addCleanup(cleanup)
1940
1941 # actually override the attribute
1942 setattr(object_to_patch, attr_name, new_value)
1943
1944
1945 @contextlib.contextmanager
1946 def patch_list(orig):
1947 """Like unittest.mock.patch.dict, but for lists."""
1948 try:
1949 saved = orig[:]
1950 yield
1951 finally:
1952 orig[:] = saved
1953
1954
1955 def run_in_subinterp(code):
1956 """
1957 Run code in a subinterpreter. Raise unittest.SkipTest if the tracemalloc
1958 module is enabled.
1959 """
1960 _check_tracemalloc()
1961 try:
1962 import _testcapi
1963 except ImportError:
1964 raise unittest.SkipTest("requires _testcapi")
1965 return _testcapi.run_in_subinterp(code)
1966
1967
1968 def run_in_subinterp_with_config(code, *, own_gil=None, **config):
1969 """
1970 Run code in a subinterpreter. Raise unittest.SkipTest if the tracemalloc
1971 module is enabled.
1972 """
1973 _check_tracemalloc()
1974 try:
1975 import _testinternalcapi
1976 except ImportError:
1977 raise unittest.SkipTest("requires _testinternalcapi")
1978 if own_gil is not None:
1979 assert 'gil' not in config, (own_gil, config)
1980 config['gil'] = 'own' if own_gil else 'shared'
1981 else:
1982 gil = config['gil']
1983 if gil == 0:
1984 config['gil'] = 'default'
1985 elif gil == 1:
1986 config['gil'] = 'shared'
1987 elif gil == 2:
1988 config['gil'] = 'own'
1989 elif not isinstance(gil, str):
1990 raise NotImplementedError(gil)
1991 config = types.SimpleNamespace(**config)
1992 return _testinternalcapi.run_in_subinterp_with_config(code, config)
1993
1994
1995 def _check_tracemalloc():
1996 # Issue #10915, #15751: PyGILState_*() functions don't work with
1997 # sub-interpreters, the tracemalloc module uses these functions internally
1998 try:
1999 import tracemalloc
2000 except ImportError:
2001 pass
2002 else:
2003 if tracemalloc.is_tracing():
2004 raise unittest.SkipTest("run_in_subinterp() cannot be used "
2005 "if tracemalloc module is tracing "
2006 "memory allocations")
2007
2008
2009 def check_free_after_iterating(test, iter, cls, args=()):
2010 done = False
2011 def wrapper():
2012 class A(cls):
2013 def __del__(self):
2014 nonlocal done
2015 done = True
2016 try:
2017 next(it)
2018 except StopIteration:
2019 pass
2020
2021 it = iter(A(*args))
2022 # Issue 26494: Shouldn't crash
2023 test.assertRaises(StopIteration, next, it)
2024
2025 wrapper()
2026 # The sequence should be deallocated just after the end of iterating
2027 gc_collect()
2028 test.assertTrue(done)
2029
2030
2031 def missing_compiler_executable(cmd_names=[]):
2032 """Check if the compiler components used to build the interpreter exist.
2033
2034 Check for the existence of the compiler executables whose names are listed
2035 in 'cmd_names' or all the compiler executables when 'cmd_names' is empty
2036 and return the first missing executable or None when none is found
2037 missing.
2038
2039 """
2040 from setuptools._distutils import ccompiler, sysconfig
2041 from setuptools import errors
2042 import shutil
2043
2044 compiler = ccompiler.new_compiler()
2045 sysconfig.customize_compiler(compiler)
2046 if compiler.compiler_type == "msvc":
2047 # MSVC has no executables, so check whether initialization succeeds
2048 try:
2049 compiler.initialize()
2050 except errors.PlatformError:
2051 return "msvc"
2052 for name in compiler.executables:
2053 if cmd_names and name not in cmd_names:
2054 continue
2055 cmd = getattr(compiler, name)
2056 if cmd_names:
2057 assert cmd is not None, \
2058 "the '%s' executable is not configured" % name
2059 elif not cmd:
2060 continue
2061 if shutil.which(cmd[0]) is None:
2062 return cmd[0]
2063
2064
2065 _old_android_emulator = None
2066 def setswitchinterval(interval):
2067 # Setting a very low gil interval on the Android emulator causes python
2068 # to hang (issue #26939).
2069 minimum_interval = 1e-4 # 100 us
2070 if is_android and interval < minimum_interval:
2071 global _old_android_emulator
2072 if _old_android_emulator is None:
2073 import platform
2074 av = platform.android_ver()
2075 _old_android_emulator = av.is_emulator and av.api_level < 24
2076 if _old_android_emulator:
2077 interval = minimum_interval
2078 return sys.setswitchinterval(interval)
2079
2080
2081 def get_pagesize():
2082 """Get size of a page in bytes."""
2083 try:
2084 page_size = os.sysconf('SC_PAGESIZE')
2085 except (ValueError, AttributeError):
2086 try:
2087 page_size = os.sysconf('SC_PAGE_SIZE')
2088 except (ValueError, AttributeError):
2089 page_size = 4096
2090 return page_size
2091
2092
2093 @contextlib.contextmanager
2094 def disable_faulthandler():
2095 import faulthandler
2096
2097 # use sys.__stderr__ instead of sys.stderr, since regrtest replaces
2098 # sys.stderr with a StringIO which has no file descriptor when a test
2099 # is run with -W/--verbose3.
2100 fd = sys.__stderr__.fileno()
2101
2102 is_enabled = faulthandler.is_enabled()
2103 try:
2104 faulthandler.disable()
2105 yield
2106 finally:
2107 if is_enabled:
2108 faulthandler.enable(file=fd, all_threads=True)
2109
2110
2111 class SaveSignals:
2112 """
2113 Save and restore signal handlers.
2114
2115 This class is only able to save/restore signal handlers registered
2116 by the Python signal module: see bpo-13285 for "external" signal
2117 handlers.
2118 """
2119
2120 def __init__(self):
2121 import signal
2122 self.signal = signal
2123 self.signals = signal.valid_signals()
2124 # SIGKILL and SIGSTOP signals cannot be ignored nor caught
2125 for signame in ('SIGKILL', 'SIGSTOP'):
2126 try:
2127 signum = getattr(signal, signame)
2128 except AttributeError:
2129 continue
2130 self.signals.remove(signum)
2131 self.handlers = {}
2132
2133 def save(self):
2134 for signum in self.signals:
2135 handler = self.signal.getsignal(signum)
2136 if handler is None:
2137 # getsignal() returns None if a signal handler was not
2138 # registered by the Python signal module,
2139 # and the handler is not SIG_DFL nor SIG_IGN.
2140 #
2141 # Ignore the signal: we cannot restore the handler.
2142 continue
2143 self.handlers[signum] = handler
2144
2145 def restore(self):
2146 for signum, handler in self.handlers.items():
2147 self.signal.signal(signum, handler)
2148
2149
2150 def with_pymalloc():
2151 try:
2152 import _testcapi
2153 except ImportError:
2154 raise unittest.SkipTest("requires _testcapi")
2155 return _testcapi.WITH_PYMALLOC and not Py_GIL_DISABLED
2156
2157
2158 def with_mimalloc():
2159 try:
2160 import _testcapi
2161 except ImportError:
2162 raise unittest.SkipTest("requires _testcapi")
2163 return _testcapi.WITH_MIMALLOC
2164
2165
2166 class _ALWAYS_EQ:
2167 """
2168 Object that is equal to anything.
2169 """
2170 def __eq__(self, other):
2171 return True
2172 def __ne__(self, other):
2173 return False
2174
2175 ALWAYS_EQ = _ALWAYS_EQ()
2176
2177 class _NEVER_EQ:
2178 """
2179 Object that is not equal to anything.
2180 """
2181 def __eq__(self, other):
2182 return False
2183 def __ne__(self, other):
2184 return True
2185 def __hash__(self):
2186 return 1
2187
2188 NEVER_EQ = _NEVER_EQ()
2189
2190 @functools.total_ordering
2191 class _LARGEST:
2192 """
2193 Object that is greater than anything (except itself).
2194 """
2195 def __eq__(self, other):
2196 return isinstance(other, _LARGEST)
2197 def __lt__(self, other):
2198 return False
2199
2200 LARGEST = _LARGEST()
2201
2202 @functools.total_ordering
2203 class _SMALLEST:
2204 """
2205 Object that is less than anything (except itself).
2206 """
2207 def __eq__(self, other):
2208 return isinstance(other, _SMALLEST)
2209 def __gt__(self, other):
2210 return False
2211
2212 SMALLEST = _SMALLEST()
2213
2214 def maybe_get_event_loop_policy():
2215 """Return the global event loop policy if one is set, else return None."""
2216 import asyncio.events
2217 return asyncio.events._event_loop_policy
2218
2219 # Helpers for testing hashing.
2220 NHASHBITS = sys.hash_info.width # number of bits in hash() result
2221 assert NHASHBITS in (32, 64)
2222
2223 # Return mean and sdev of number of collisions when tossing nballs balls
2224 # uniformly at random into nbins bins. By definition, the number of
2225 # collisions is the number of balls minus the number of occupied bins at
2226 # the end.
2227 def collision_stats(nbins, nballs):
2228 n, k = nbins, nballs
2229 # prob a bin empty after k trials = (1 - 1/n)**k
2230 # mean # empty is then n * (1 - 1/n)**k
2231 # so mean # occupied is n - n * (1 - 1/n)**k
2232 # so collisions = k - (n - n*(1 - 1/n)**k)
2233 #
2234 # For the variance:
2235 # n*(n-1)*(1-2/n)**k + meanempty - meanempty**2 =
2236 # n*(n-1)*(1-2/n)**k + meanempty * (1 - meanempty)
2237 #
2238 # Massive cancellation occurs, and, e.g., for a 64-bit hash code
2239 # 1-1/2**64 rounds uselessly to 1.0. Rather than make heroic (and
2240 # error-prone) efforts to rework the naive formulas to avoid those,
2241 # we use the `decimal` module to get plenty of extra precision.
2242 #
2243 # Note: the exact values are straightforward to compute with
2244 # rationals, but in context that's unbearably slow, requiring
2245 # multi-million bit arithmetic.
2246 import decimal
2247 with decimal.localcontext() as ctx:
2248 bits = n.bit_length() * 2 # bits in n**2
2249 # At least that many bits will likely cancel out.
2250 # Use that many decimal digits instead.
2251 ctx.prec = max(bits, 30)
2252 dn = decimal.Decimal(n)
2253 p1empty = ((dn - 1) / dn) ** k
2254 meanempty = n * p1empty
2255 occupied = n - meanempty
2256 collisions = k - occupied
2257 var = dn*(dn-1)*((dn-2)/dn)**k + meanempty * (1 - meanempty)
2258 return float(collisions), float(var.sqrt())
2259
2260
2261 class catch_unraisable_exception:
2262 """
2263 Context manager catching unraisable exception using sys.unraisablehook.
2264
2265 Storing the exception value (cm.unraisable.exc_value) creates a reference
2266 cycle. The reference cycle is broken explicitly when the context manager
2267 exits.
2268
2269 Storing the object (cm.unraisable.object) can resurrect it if it is set to
2270 an object which is being finalized. Exiting the context manager clears the
2271 stored object.
2272
2273 Usage:
2274
2275 with support.catch_unraisable_exception() as cm:
2276 # code creating an "unraisable exception"
2277 ...
2278
2279 # check the unraisable exception: use cm.unraisable
2280 ...
2281
2282 # cm.unraisable attribute no longer exists at this point
2283 # (to break a reference cycle)
2284 """
2285
2286 def __init__(self):
2287 self.unraisable = None
2288 self._old_hook = None
2289
2290 def _hook(self, unraisable):
2291 # Storing unraisable.object can resurrect an object which is being
2292 # finalized. Storing unraisable.exc_value creates a reference cycle.
2293 self.unraisable = unraisable
2294
2295 def __enter__(self):
2296 self._old_hook = sys.unraisablehook
2297 sys.unraisablehook = self._hook
2298 return self
2299
2300 def __exit__(self, *exc_info):
2301 sys.unraisablehook = self._old_hook
2302 del self.unraisable
2303
2304
2305 def wait_process(pid, *, exitcode, timeout=None):
2306 """
2307 Wait until process pid completes and check that the process exit code is
2308 exitcode.
2309
2310 Raise an AssertionError if the process exit code is not equal to exitcode.
2311
2312 If the process runs longer than timeout seconds (LONG_TIMEOUT by default),
2313 kill the process (if signal.SIGKILL is available) and raise an
2314 AssertionError. The timeout feature is not available on Windows.
2315 """
2316 if os.name != "nt":
2317 import signal
2318
2319 if timeout is None:
2320 timeout = LONG_TIMEOUT
2321
2322 start_time = time.monotonic()
2323 for _ in sleeping_retry(timeout, error=False):
2324 pid2, status = os.waitpid(pid, os.WNOHANG)
2325 if pid2 != 0:
2326 break
2327 # rety: the process is still running
2328 else:
2329 try:
2330 os.kill(pid, signal.SIGKILL)
2331 os.waitpid(pid, 0)
2332 except OSError:
2333 # Ignore errors like ChildProcessError or PermissionError
2334 pass
2335
2336 dt = time.monotonic() - start_time
2337 raise AssertionError(f"process {pid} is still running "
2338 f"after {dt:.1f} seconds")
2339 else:
2340 # Windows implementation: don't support timeout :-(
2341 pid2, status = os.waitpid(pid, 0)
2342
2343 exitcode2 = os.waitstatus_to_exitcode(status)
2344 if exitcode2 != exitcode:
2345 raise AssertionError(f"process {pid} exited with code {exitcode2}, "
2346 f"but exit code {exitcode} is expected")
2347
2348 # sanity check: it should not fail in practice
2349 if pid2 != pid:
2350 raise AssertionError(f"pid {pid2} != pid {pid}")
2351
2352 def skip_if_broken_multiprocessing_synchronize():
2353 """
2354 Skip tests if the multiprocessing.synchronize module is missing, if there
2355 is no available semaphore implementation, or if creating a lock raises an
2356 OSError (on Linux only).
2357 """
2358 from .import_helper import import_module
2359
2360 # Skip tests if the _multiprocessing extension is missing.
2361 import_module('_multiprocessing')
2362
2363 # Skip tests if there is no available semaphore implementation:
2364 # multiprocessing.synchronize requires _multiprocessing.SemLock.
2365 synchronize = import_module('multiprocessing.synchronize')
2366
2367 if sys.platform == "linux":
2368 try:
2369 # bpo-38377: On Linux, creating a semaphore fails with OSError
2370 # if the current user does not have the permission to create
2371 # a file in /dev/shm/ directory.
2372 import multiprocessing
2373 synchronize.Lock(ctx=multiprocessing.get_context('fork'))
2374 # The explicit fork mp context is required in order for
2375 # TestResourceTracker.test_resource_tracker_reused to work.
2376 # synchronize creates a new multiprocessing.resource_tracker
2377 # process at module import time via the above call in that
2378 # scenario. Awkward. This enables gh-84559. No code involved
2379 # should have threads at that point so fork() should be safe.
2380
2381 except OSError as exc:
2382 raise unittest.SkipTest(f"broken multiprocessing SemLock: {exc!r}")
2383
2384
2385 def check_disallow_instantiation(testcase, tp, *args, **kwds):
2386 """
2387 Check that given type cannot be instantiated using *args and **kwds.
2388
2389 See bpo-43916: Add Py_TPFLAGS_DISALLOW_INSTANTIATION type flag.
2390 """
2391 mod = tp.__module__
2392 name = tp.__name__
2393 if mod != 'builtins':
2394 qualname = f"{mod}.{name}"
2395 else:
2396 qualname = f"{name}"
2397 msg = f"cannot create '{re.escape(qualname)}' instances"
2398 testcase.assertRaisesRegex(TypeError, msg, tp, *args, **kwds)
2399 testcase.assertRaisesRegex(TypeError, msg, tp.__new__, tp, *args, **kwds)
2400
2401 def get_recursion_depth():
2402 """Get the recursion depth of the caller function.
2403
2404 In the __main__ module, at the module level, it should be 1.
2405 """
2406 try:
2407 import _testinternalcapi
2408 depth = _testinternalcapi.get_recursion_depth()
2409 except (ImportError, RecursionError) as exc:
2410 # sys._getframe() + frame.f_back implementation.
2411 try:
2412 depth = 0
2413 frame = sys._getframe()
2414 while frame is not None:
2415 depth += 1
2416 frame = frame.f_back
2417 finally:
2418 # Break any reference cycles.
2419 frame = None
2420
2421 # Ignore get_recursion_depth() frame.
2422 return max(depth - 1, 1)
2423
2424 def get_recursion_available():
2425 """Get the number of available frames before RecursionError.
2426
2427 It depends on the current recursion depth of the caller function and
2428 sys.getrecursionlimit().
2429 """
2430 limit = sys.getrecursionlimit()
2431 depth = get_recursion_depth()
2432 return limit - depth
2433
2434 @contextlib.contextmanager
2435 def set_recursion_limit(limit):
2436 """Temporarily change the recursion limit."""
2437 original_limit = sys.getrecursionlimit()
2438 try:
2439 sys.setrecursionlimit(limit)
2440 yield
2441 finally:
2442 sys.setrecursionlimit(original_limit)
2443
2444 def infinite_recursion(max_depth=None):
2445 if max_depth is None:
2446 # Pick a number large enough to cause problems
2447 # but not take too long for code that can handle
2448 # very deep recursion.
2449 max_depth = 20_000
2450 elif max_depth < 3:
2451 raise ValueError(f"max_depth must be at least 3, got {max_depth}")
2452 depth = get_recursion_depth()
2453 depth = max(depth - 1, 1) # Ignore infinite_recursion() frame.
2454 limit = depth + max_depth
2455 return set_recursion_limit(limit)
2456
2457 def ignore_deprecations_from(module: str, *, like: str) -> object:
2458 token = object()
2459 warnings.filterwarnings(
2460 "ignore",
2461 category=DeprecationWarning,
2462 module=module,
2463 message=like + fr"(?#support{id(token)})",
2464 )
2465 return token
2466
2467 def clear_ignored_deprecations(*tokens: object) -> None:
2468 if not tokens:
2469 raise ValueError("Provide token or tokens returned by ignore_deprecations_from")
2470
2471 new_filters = []
2472 old_filters = warnings._get_filters()
2473 endswith = tuple(rf"(?#support{id(token)})" for token in tokens)
2474 for action, message, category, module, lineno in old_filters:
2475 if action == "ignore" and category is DeprecationWarning:
2476 if isinstance(message, re.Pattern):
2477 msg = message.pattern
2478 else:
2479 msg = message or ""
2480 if msg.endswith(endswith):
2481 continue
2482 new_filters.append((action, message, category, module, lineno))
2483 if old_filters != new_filters:
2484 old_filters[:] = new_filters
2485 warnings._filters_mutated()
2486
2487
2488 # Skip a test if venv with pip is known to not work.
2489 def requires_venv_with_pip():
2490 # ensurepip requires zlib to open ZIP archives (.whl binary wheel packages)
2491 try:
2492 import zlib # noqa: F401
2493 except ImportError:
2494 return unittest.skipIf(True, "venv: ensurepip requires zlib")
2495
2496 # bpo-26610: pip/pep425tags.py requires ctypes.
2497 # gh-92820: setuptools/windows_support.py uses ctypes (setuptools 58.1).
2498 try:
2499 import ctypes
2500 except ImportError:
2501 ctypes = None
2502 return unittest.skipUnless(ctypes, 'venv: pip requires ctypes')
2503
2504
2505 @functools.cache
2506 def _findwheel(pkgname):
2507 """Try to find a wheel with the package specified as pkgname.
2508
2509 If set, the wheels are searched for in WHEEL_PKG_DIR (see ensurepip).
2510 Otherwise, they are searched for in the test directory.
2511 """
2512 wheel_dir = sysconfig.get_config_var('WHEEL_PKG_DIR') or os.path.join(
2513 TEST_HOME_DIR, 'wheeldata',
2514 )
2515 filenames = os.listdir(wheel_dir)
2516 filenames = sorted(filenames, reverse=True) # approximate "newest" first
2517 for filename in filenames:
2518 # filename is like 'setuptools-{version}-py3-none-any.whl'
2519 if not filename.endswith(".whl"):
2520 continue
2521 prefix = pkgname + '-'
2522 if filename.startswith(prefix):
2523 return os.path.join(wheel_dir, filename)
2524 raise FileNotFoundError(f"No wheel for {pkgname} found in {wheel_dir}")
2525
2526
2527 # Context manager that creates a virtual environment, install setuptools in it,
2528 # and returns the paths to the venv directory and the python executable
2529 @contextlib.contextmanager
2530 def setup_venv_with_pip_setuptools(venv_dir):
2531 import subprocess
2532 from .os_helper import temp_cwd
2533
2534 def run_command(cmd):
2535 if verbose:
2536 import shlex
2537 print()
2538 print('Run:', ' '.join(map(shlex.quote, cmd)))
2539 subprocess.run(cmd, check=True)
2540 else:
2541 subprocess.run(cmd,
2542 stdout=subprocess.PIPE,
2543 stderr=subprocess.STDOUT,
2544 check=True)
2545
2546 with temp_cwd() as temp_dir:
2547 # Create virtual environment to get setuptools
2548 cmd = [sys.executable, '-X', 'dev', '-m', 'venv', venv_dir]
2549 run_command(cmd)
2550
2551 venv = os.path.join(temp_dir, venv_dir)
2552
2553 # Get the Python executable of the venv
2554 python_exe = os.path.basename(sys.executable)
2555 if sys.platform == 'win32':
2556 python = os.path.join(venv, 'Scripts', python_exe)
2557 else:
2558 python = os.path.join(venv, 'bin', python_exe)
2559
2560 cmd = (python, '-X', 'dev',
2561 '-m', 'pip', 'install',
2562 _findwheel('setuptools'),
2563 )
2564 run_command(cmd)
2565
2566 yield python
2567
2568
2569 # True if Python is built with the Py_DEBUG macro defined: if
2570 # Python is built in debug mode (./configure --with-pydebug).
2571 Py_DEBUG = hasattr(sys, 'gettotalrefcount')
2572
2573
2574 def late_deletion(obj):
2575 """
2576 Keep a Python alive as long as possible.
2577
2578 Create a reference cycle and store the cycle in an object deleted late in
2579 Python finalization. Try to keep the object alive until the very last
2580 garbage collection.
2581
2582 The function keeps a strong reference by design. It should be called in a
2583 subprocess to not mark a test as "leaking a reference".
2584 """
2585
2586 # Late CPython finalization:
2587 # - finalize_interp_clear()
2588 # - _PyInterpreterState_Clear(): Clear PyInterpreterState members
2589 # (ex: codec_search_path, before_forkers)
2590 # - clear os.register_at_fork() callbacks
2591 # - clear codecs.register() callbacks
2592
2593 ref_cycle = [obj]
2594 ref_cycle.append(ref_cycle)
2595
2596 # Store a reference in PyInterpreterState.codec_search_path
2597 import codecs
2598 def search_func(encoding):
2599 return None
2600 search_func.reference = ref_cycle
2601 codecs.register(search_func)
2602
2603 if hasattr(os, 'register_at_fork'):
2604 # Store a reference in PyInterpreterState.before_forkers
2605 def atfork_func():
2606 pass
2607 atfork_func.reference = ref_cycle
2608 os.register_at_fork(before=atfork_func)
2609
2610
2611 def busy_retry(timeout, err_msg=None, /, *, error=True):
2612 """
2613 Run the loop body until "break" stops the loop.
2614
2615 After *timeout* seconds, raise an AssertionError if *error* is true,
2616 or just stop if *error is false.
2617
2618 Example:
2619
2620 for _ in support.busy_retry(support.SHORT_TIMEOUT):
2621 if check():
2622 break
2623
2624 Example of error=False usage:
2625
2626 for _ in support.busy_retry(support.SHORT_TIMEOUT, error=False):
2627 if check():
2628 break
2629 else:
2630 raise RuntimeError('my custom error')
2631
2632 """
2633 if timeout <= 0:
2634 raise ValueError("timeout must be greater than zero")
2635
2636 start_time = time.monotonic()
2637 deadline = start_time + timeout
2638
2639 while True:
2640 yield
2641
2642 if time.monotonic() >= deadline:
2643 break
2644
2645 if error:
2646 dt = time.monotonic() - start_time
2647 msg = f"timeout ({dt:.1f} seconds)"
2648 if err_msg:
2649 msg = f"{msg}: {err_msg}"
2650 raise AssertionError(msg)
2651
2652
2653 def sleeping_retry(timeout, err_msg=None, /,
2654 *, init_delay=0.010, max_delay=1.0, error=True):
2655 """
2656 Wait strategy that applies exponential backoff.
2657
2658 Run the loop body until "break" stops the loop. Sleep at each loop
2659 iteration, but not at the first iteration. The sleep delay is doubled at
2660 each iteration (up to *max_delay* seconds).
2661
2662 See busy_retry() documentation for the parameters usage.
2663
2664 Example raising an exception after SHORT_TIMEOUT seconds:
2665
2666 for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
2667 if check():
2668 break
2669
2670 Example of error=False usage:
2671
2672 for _ in support.sleeping_retry(support.SHORT_TIMEOUT, error=False):
2673 if check():
2674 break
2675 else:
2676 raise RuntimeError('my custom error')
2677 """
2678
2679 delay = init_delay
2680 for _ in busy_retry(timeout, err_msg, error=error):
2681 yield
2682
2683 time.sleep(delay)
2684 delay = min(delay * 2, max_delay)
2685
2686
2687 class Stopwatch:
2688 """Context manager to roughly time a CPU-bound operation.
2689
2690 Disables GC. Uses perf_counter, which is a clock with the highest
2691 available resolution. It is chosen even though it does include
2692 time elapsed during sleep and is system-wide, because the
2693 resolution of process_time is too coarse on Windows and
2694 process_time does not exist everywhere (for example, WASM).
2695
2696 Note:
2697 - This *includes* time spent in other threads/processes.
2698 - Some systems only have a coarse resolution; check
2699 stopwatch.clock_info.resolution when using the results.
2700
2701 Usage:
2702
2703 with Stopwatch() as stopwatch:
2704 ...
2705 elapsed = stopwatch.seconds
2706 resolution = stopwatch.clock_info.resolution
2707 """
2708 def __enter__(self):
2709 get_time = time.perf_counter
2710 clock_info = time.get_clock_info('perf_counter')
2711 self.context = disable_gc()
2712 self.context.__enter__()
2713 self.get_time = get_time
2714 self.clock_info = clock_info
2715 self.start_time = get_time()
2716 return self
2717
2718 def __exit__(self, *exc):
2719 try:
2720 end_time = self.get_time()
2721 finally:
2722 result = self.context.__exit__(*exc)
2723 self.seconds = end_time - self.start_time
2724 return result
2725
2726
2727 @contextlib.contextmanager
2728 def adjust_int_max_str_digits(max_digits):
2729 """Temporarily change the integer string conversion length limit."""
2730 current = sys.get_int_max_str_digits()
2731 try:
2732 sys.set_int_max_str_digits(max_digits)
2733 yield
2734 finally:
2735 sys.set_int_max_str_digits(current)
2736
2737
2738 def exceeds_recursion_limit():
2739 """For recursion tests, easily exceeds default recursion limit."""
2740 return 150_000
2741
2742
2743 def _has_huge_c_stack(depth):
2744 """Check that *depth* recursive calls cannot exhaust the C stack."""
2745 try:
2746 from _testinternalcapi import get_c_recursion_remaining
2747 except ImportError:
2748 # Fall back to checking for an unlimited stack size.
2749 if is_emscripten or is_wasi or os.name == "nt":
2750 return False
2751 import resource
2752 soft, hard = resource.getrlimit(resource.RLIMIT_STACK)
2753 return soft == hard and soft in (-1, 0xFFFF_FFFF_FFFF_FFFF)
2754 else:
2755 remaining = get_c_recursion_remaining()
2756 # A negative value means integer overflow in the estimate
2757 # (e.g. with an unlimited RLIMIT_STACK). The estimate is based on
2758 # the size of the interpreter loop frame, so it is only a lower
2759 # bound for recursion with smaller C frames.
2760 return remaining >= depth or remaining < 0
2761
2762
2763 def skip_if_huge_c_stack(depth=150_000):
2764 """Skip decorator for tests which cannot overflow the C stack.
2765
2766 Tests exhausting the C stack with *depth* recursive calls cannot
2767 trigger the recursion protection if the C stack is too large (e.g.
2768 with a large or unlimited RLIMIT_STACK), and either fail, or run
2769 for a very long time, or crash, or consume all memory.
2770
2771 Prefer run_with_limited_c_stack() for tests recursing to a fixed depth.
2772 """
2773 return unittest.skipIf(
2774 _has_huge_c_stack(depth),
2775 f"the C stack is large enough for {depth} recursive calls")
2776
2777
2778 # Small enough to be exhausted by tens of thousands of recursive calls,
2779 # but not smaller than Py_C_STACK_SIZE (4 MiB) which the interpreter
2780 # assumes if it cannot query the thread stack size.
2781 C_STACK_SIZE = 8 * 1024 * 1024
2782
2783
2784 def run_with_limited_c_stack(depth=150_000, size=C_STACK_SIZE):
2785 """Decorator for tests exhausting the C stack with *depth* recursive calls.
2786
2787 Run the test in a separate thread with the C stack of *size* bytes, so
2788 that the outcome does not depend on the C stack size of the main thread
2789 (which can be large or unlimited, see RLIMIT_STACK).
2790
2791 If a thread with the limited C stack cannot be created, run the test in
2792 the current thread, but skip it if the C stack is too large.
2793 """
2794 reason = f"the C stack is large enough for {depth} recursive calls"
2795 def decorator(test):
2796 @functools.wraps(test)
2797 def wrapper(*args, **kwargs):
2798 def run_test():
2799 # The C stack can still be too large if limiting it failed.
2800 if _has_huge_c_stack(depth):
2801 raise unittest.SkipTest(reason)
2802 test(*args, **kwargs)
2803
2804 try:
2805 import threading
2806 old_size = threading.stack_size(size)
2807 except (ImportError, ValueError, RuntimeError):
2808 # Setting the thread stack size is not supported.
2809 return run_test()
2810
2811 exceptions = []
2812 def run():
2813 try:
2814 run_test()
2815 except BaseException as exc:
2816 exceptions.append(exc)
2817
2818 thread = threading.Thread(target=run)
2819 try:
2820 thread.start()
2821 except RuntimeError:
2822 # Threads are not supported.
2823 return run_test()
2824 finally:
2825 threading.stack_size(old_size)
2826 thread.join()
2827 if exceptions:
2828 raise exceptions[0]
2829 return wrapper
2830 return decorator
2831
2832
2833 # Windows doesn't have os.uname() but it doesn't support s390x.
2834 is_s390x = hasattr(os, 'uname') and os.uname().machine == 's390x'
2835 skip_on_s390x = unittest.skipIf(is_s390x, 'skipped on s390x')
2836
2837 Py_TRACE_REFS = hasattr(sys, 'getobjects')
2838
2839 try:
2840 _JIT_ENABLED = sys._jit.is_enabled()
2841 except AttributeError:
2842 _JIT_ENABLED = False
2843 requires_jit_enabled = unittest.skipUnless(_JIT_ENABLED, "requires JIT enabled")
2844 requires_jit_disabled = unittest.skipIf(_JIT_ENABLED, "requires JIT disabled")
2845
2846
2847 _BASE_COPY_SRC_DIR_IGNORED_NAMES = frozenset({
2848 # SRC_DIR/.git
2849 '.git',
2850 # ignore all __pycache__/ sub-directories
2851 '__pycache__',
2852 })
2853
2854 # Ignore function for shutil.copytree() to copy the Python source code.
2855 def copy_python_src_ignore(path, names):
2856 ignored = _BASE_COPY_SRC_DIR_IGNORED_NAMES
2857 if os.path.basename(path) == 'Doc':
2858 ignored |= {
2859 # SRC_DIR/Doc/build/
2860 'build',
2861 # SRC_DIR/Doc/venv/
2862 'venv',
2863 }
2864
2865 # check if we are at the root of the source code
2866 elif 'Modules' in names:
2867 ignored |= {
2868 # SRC_DIR/build/
2869 'build',
2870 }
2871 return ignored
2872
2873
2874 # XXX Move this to the inspect module?
2875 def walk_class_hierarchy(top, *, topdown=True):
2876 # This is based on the logic in os.walk().
2877 assert isinstance(top, type), repr(top)
2878 stack = [top]
2879 while stack:
2880 top = stack.pop()
2881 if isinstance(top, tuple):
2882 yield top
2883 continue
2884
2885 subs = type(top).__subclasses__(top)
2886 if topdown:
2887 # Yield before subclass traversal if going top down.
2888 yield top, subs
2889 # Traverse into subclasses.
2890 for sub in reversed(subs):
2891 stack.append(sub)
2892 else:
2893 # Yield after subclass traversal if going bottom up.
2894 stack.append((top, subs))
2895 # Traverse into subclasses.
2896 for sub in reversed(subs):
2897 stack.append(sub)
2898
2899
2900 def iter_builtin_types():
2901 # First try the explicit route.
2902 try:
2903 import _testinternalcapi
2904 except ImportError:
2905 _testinternalcapi = None
2906 if _testinternalcapi is not None:
2907 yield from _testinternalcapi.get_static_builtin_types()
2908 return
2909
2910 # Fall back to making a best-effort guess.
2911 if hasattr(object, '__flags__'):
2912 # Look for any type object with the Py_TPFLAGS_STATIC_BUILTIN flag set.
2913 import datetime
2914 seen = set()
2915 for cls, subs in walk_class_hierarchy(object):
2916 if cls in seen:
2917 continue
2918 seen.add(cls)
2919 if not (cls.__flags__ & _TPFLAGS_STATIC_BUILTIN):
2920 # Do not walk its subclasses.
2921 subs[:] = []
2922 continue
2923 yield cls
2924 else:
2925 # Fall back to a naive approach.
2926 seen = set()
2927 for obj in __builtins__.values():
2928 if not isinstance(obj, type):
2929 continue
2930 cls = obj
2931 # XXX?
2932 if cls.__module__ != 'builtins':
2933 continue
2934 if cls == ExceptionGroup:
2935 # It's a heap type.
2936 continue
2937 if cls in seen:
2938 continue
2939 seen.add(cls)
2940 yield cls
2941
2942
2943 # XXX Move this to the inspect module?
2944 def iter_name_in_mro(cls, name):
2945 """Yield matching items found in base.__dict__ across the MRO.
2946
2947 The descriptor protocol is not invoked.
2948
2949 list(iter_name_in_mro(cls, name))[0] is roughly equivalent to
2950 find_name_in_mro() in Objects/typeobject.c (AKA PyType_Lookup()).
2951
2952 inspect.getattr_static() is similar.
2953 """
2954 # This can fail if "cls" is weird.
2955 for base in inspect._static_getmro(cls):
2956 # This can fail if "base" is weird.
2957 ns = inspect._get_dunder_dict_of_class(base)
2958 try:
2959 obj = ns[name]
2960 except KeyError:
2961 continue
2962 yield obj, base
2963
2964
2965 # XXX Move this to the inspect module?
2966 def find_name_in_mro(cls, name, default=inspect._sentinel):
2967 for res in iter_name_in_mro(cls, name):
2968 # Return the first one.
2969 return res
2970 if default is not inspect._sentinel:
2971 return default, None
2972 raise AttributeError(name)
2973
2974
2975 # XXX The return value should always be exactly the same...
2976 def identify_type_slot_wrappers():
2977 try:
2978 import _testinternalcapi
2979 except ImportError:
2980 _testinternalcapi = None
2981 if _testinternalcapi is not None:
2982 names = {n: None for n in _testinternalcapi.identify_type_slot_wrappers()}
2983 return list(names)
2984 else:
2985 raise NotImplementedError
2986
2987
2988 def iter_slot_wrappers(cls):
2989 def is_slot_wrapper(name, value):
2990 if not isinstance(value, types.WrapperDescriptorType):
2991 assert not repr(value).startswith('<slot wrapper '), (cls, name, value)
2992 return False
2993 assert repr(value).startswith('<slot wrapper '), (cls, name, value)
2994 assert callable(value), (cls, name, value)
2995 assert name.startswith('__') and name.endswith('__'), (cls, name, value)
2996 return True
2997
2998 try:
2999 attrs = identify_type_slot_wrappers()
3000 except NotImplementedError:
3001 attrs = None
3002 if attrs is not None:
3003 for attr in sorted(attrs):
3004 obj, base = find_name_in_mro(cls, attr, None)
3005 if obj is not None and is_slot_wrapper(attr, obj):
3006 yield attr, base is cls
3007 return
3008
3009 # Fall back to a naive best-effort approach.
3010
3011 ns = vars(cls)
3012 unused = set(ns)
3013 for name in dir(cls):
3014 if name in ns:
3015 unused.remove(name)
3016
3017 try:
3018 value = getattr(cls, name)
3019 except AttributeError:
3020 # It's as though it weren't in __dir__.
3021 assert name in ('__annotate__', '__annotations__', '__abstractmethods__'), (cls, name)
3022 if name in ns and is_slot_wrapper(name, ns[name]):
3023 unused.add(name)
3024 continue
3025
3026 if not name.startswith('__') or not name.endswith('__'):
3027 assert not is_slot_wrapper(name, value), (cls, name, value)
3028 if not is_slot_wrapper(name, value):
3029 if name in ns:
3030 assert not is_slot_wrapper(name, ns[name]), (cls, name, value, ns[name])
3031 else:
3032 if name in ns:
3033 assert ns[name] is value, (cls, name, value, ns[name])
3034 yield name, True
3035 else:
3036 yield name, False
3037
3038 for name in unused:
3039 value = ns[name]
3040 if is_slot_wrapper(cls, name, value):
3041 yield name, True
3042
3043
3044 @contextlib.contextmanager
3045 def force_color(color: bool):
3046 import _colorize
3047 from .os_helper import EnvironmentVarGuard
3048
3049 with (
3050 swap_attr(_colorize, "can_colorize", lambda *, file=None: color),
3051 EnvironmentVarGuard() as env,
3052 ):
3053 env.unset("FORCE_COLOR", "NO_COLOR", "PYTHON_COLORS")
3054 env.set("FORCE_COLOR" if color else "NO_COLOR", "1")
3055 yield
3056
3057
3058 def force_colorized(func):
3059 """Force the terminal to be colorized."""
3060 @functools.wraps(func)
3061 def wrapper(*args, **kwargs):
3062 with force_color(True):
3063 return func(*args, **kwargs)
3064 return wrapper
3065
3066
3067 def force_not_colorized(func):
3068 """Force the terminal NOT to be colorized."""
3069 @functools.wraps(func)
3070 def wrapper(*args, **kwargs):
3071 with force_color(False):
3072 return func(*args, **kwargs)
3073 return wrapper
3074
3075
3076 def force_colorized_test_class(cls):
3077 """Force the terminal to be colorized for the entire test class."""
3078 original_setUpClass = cls.setUpClass
3079
3080 @classmethod
3081 @functools.wraps(cls.setUpClass)
3082 def new_setUpClass(cls):
3083 cls.enterClassContext(force_color(True))
3084 original_setUpClass()
3085
3086 cls.setUpClass = new_setUpClass
3087 return cls
3088
3089
3090 def force_not_colorized_test_class(cls):
3091 """Force the terminal NOT to be colorized for the entire test class."""
3092 original_setUpClass = cls.setUpClass
3093
3094 @classmethod
3095 @functools.wraps(cls.setUpClass)
3096 def new_setUpClass(cls):
3097 cls.enterClassContext(force_color(False))
3098 original_setUpClass()
3099
3100 cls.setUpClass = new_setUpClass
3101 return cls
3102
3103
3104 def make_clean_env() -> dict[str, str]:
3105 clean_env = os.environ.copy()
3106 for k in clean_env.copy():
3107 if k.startswith("PYTHON"):
3108 clean_env.pop(k)
3109 clean_env.pop("FORCE_COLOR", None)
3110 clean_env.pop("NO_COLOR", None)
3111 return clean_env
3112
3113
3114 WINDOWS_STATUS = {
3115 0xC0000005: "STATUS_ACCESS_VIOLATION",
3116 0xC00000FD: "STATUS_STACK_OVERFLOW",
3117 0xC000013A: "STATUS_CONTROL_C_EXIT",
3118 }
3119
3120 def get_signal_name(exitcode):
3121 import signal
3122
3123 if exitcode < 0:
3124 signum = -exitcode
3125 try:
3126 return signal.Signals(signum).name
3127 except ValueError:
3128 pass
3129
3130 # Shell exit code (ex: WASI build)
3131 if 128 < exitcode < 256:
3132 signum = exitcode - 128
3133 try:
3134 return signal.Signals(signum).name
3135 except ValueError:
3136 pass
3137
3138 try:
3139 return WINDOWS_STATUS[exitcode]
3140 except KeyError:
3141 pass
3142
3143 # Format Windows exit status as hexadecimal
3144 if 0xC0000000 <= exitcode:
3145 return f"0x{exitcode:X}"
3146
3147 return None
3148
3149 class BrokenIter:
3150 def __init__(self, init_raises=False, next_raises=False, iter_raises=False):
3151 if init_raises:
3152 1/0
3153 self.next_raises = next_raises
3154 self.iter_raises = iter_raises
3155
3156 def __next__(self):
3157 if self.next_raises:
3158 1/0
3159
3160 def __iter__(self):
3161 if self.iter_raises:
3162 1/0
3163 return self
3164
3165
3166 def in_systemd_nspawn_sync_suppressed() -> bool:
3167 """
3168 Test whether the test suite is runing in systemd-nspawn
3169 with ``--suppress-sync=true``.
3170
3171 This can be used to skip tests that rely on ``fsync()`` calls
3172 and similar not being intercepted.
3173 """
3174
3175 if not hasattr(os, "O_SYNC"):
3176 return False
3177
3178 try:
3179 with open("/run/systemd/container", "rb") as fp:
3180 if fp.read().rstrip() != b"systemd-nspawn":
3181 return False
3182 except (FileNotFoundError, PermissionError):
3183 return False
3184
3185 # If systemd-nspawn is used, O_SYNC flag will immediately
3186 # trigger EINVAL. Otherwise, ENOENT will be given instead.
3187 import errno
3188 try:
3189 fd = os.open(__file__, os.O_RDONLY | os.O_SYNC)
3190 except OSError as err:
3191 if err.errno == errno.EINVAL:
3192 return True
3193 else:
3194 os.close(fd)
3195
3196 return False
3197
3198 def run_no_yield_async_fn(async_fn, /, *args, **kwargs):
3199 coro = async_fn(*args, **kwargs)
3200 try:
3201 coro.send(None)
3202 except StopIteration as e:
3203 return e.value
3204 else:
3205 raise AssertionError("coroutine did not complete")
3206 finally:
3207 coro.close()
3208
3209
3210 @types.coroutine
3211 def async_yield(v):
3212 return (yield v)
3213
3214
3215 def run_yielding_async_fn(async_fn, /, *args, **kwargs):
3216 coro = async_fn(*args, **kwargs)
3217 try:
3218 while True:
3219 try:
3220 coro.send(None)
3221 except StopIteration as e:
3222 return e.value
3223 finally:
3224 coro.close()
3225
3226
3227 def is_libssl_fips_mode():
3228 try:
3229 from _hashlib import get_fips_mode # ask _hashopenssl.c
3230 except ImportError:
3231 return False # more of a maybe, unless we add this to the _ssl module.
3232 return get_fips_mode() != 0
3233
3234 def _supports_remote_attaching():
3235 PROCESS_VM_READV_SUPPORTED = False
3236
3237 try:
3238 from _remote_debugging import PROCESS_VM_READV_SUPPORTED
3239 except ImportError:
3240 pass
3241
3242 return PROCESS_VM_READV_SUPPORTED
3243
3244 def _support_remote_exec_only_impl():
3245 if not sys.is_remote_debug_enabled():
3246 return unittest.skip("Remote debugging is not enabled")
3247 if sys.platform not in ("darwin", "linux", "win32"):
3248 return unittest.skip("Test only runs on Linux, Windows and macOS")
3249 if sys.platform == "linux" and not _supports_remote_attaching():
3250 return unittest.skip("Test only runs on Linux with process_vm_readv support")
3251 return _id
3252
3253 def support_remote_exec_only(test):
3254 return _support_remote_exec_only_impl()(test)
3255
3256 class EqualToForwardRef:
3257 """Helper to ease use of annotationlib.ForwardRef in tests.
3258
3259 This checks only attributes that can be set using the constructor.
3260
3261 """
3262
3263 def __init__(
3264 self,
3265 arg,
3266 *,
3267 module=None,
3268 owner=None,
3269 is_class=False,
3270 ):
3271 self.__forward_arg__ = arg
3272 self.__forward_is_class__ = is_class
3273 self.__forward_module__ = module
3274 self.__owner__ = owner
3275
3276 def __eq__(self, other):
3277 if not isinstance(other, (EqualToForwardRef, annotationlib.ForwardRef)):
3278 return NotImplemented
3279 return (
3280 self.__forward_arg__ == other.__forward_arg__
3281 and self.__forward_module__ == other.__forward_module__
3282 and self.__forward_is_class__ == other.__forward_is_class__
3283 and self.__owner__ == other.__owner__
3284 )
3285
3286 def __repr__(self):
3287 extra = []
3288 if self.__forward_module__ is not None:
3289 extra.append(f", module={self.__forward_module__!r}")
3290 if self.__forward_is_class__:
3291 extra.append(", is_class=True")
3292 if self.__owner__ is not None:
3293 extra.append(f", owner={self.__owner__!r}")
3294 return f"EqualToForwardRef({self.__forward_arg__!r}{''.join(extra)})"
3295
3296
3297 _linked_to_musl = None
3298 def linked_to_musl():
3299 """
3300 Report if the Python executable is linked to the musl C library.
3301
3302 Return False if we don't think it is, or a version triple otherwise.
3303 """
3304 # This is can be a relatively expensive check, so we use a cache.
3305 global _linked_to_musl
3306 if _linked_to_musl is not None:
3307 return _linked_to_musl
3308
3309 # emscripten (at least as far as we're concerned) and wasi use musl,
3310 # but platform doesn't know how to get the version, so set it to zero.
3311 if is_wasm32:
3312 _linked_to_musl = (0, 0, 0)
3313 return _linked_to_musl
3314
3315 # On all other non-linux platforms assume no musl.
3316 if sys.platform != 'linux':
3317 _linked_to_musl = False
3318 return _linked_to_musl
3319
3320 # On linux, we'll depend on the platform module to do the check, so new
3321 # musl platforms should add support in that module if possible.
3322 import platform
3323 lib, version = platform.libc_ver()
3324 if lib != 'musl':
3325 _linked_to_musl = False
3326 return _linked_to_musl
3327 _linked_to_musl = tuple(map(int, version.split('.')))
3328 return _linked_to_musl
3329
3330
3331 def control_characters_c0() -> list[str]:
3332 """Returns a list of C0 control characters as strings.
3333 C0 control characters defined as the byte range 0x00-0x1F, and 0x7F.
3334 """
3335 return [chr(c) for c in range(0x00, 0x20)] + ["\x7F"]
3336
3337
3338 STATUS_DLL_INIT_FAILED = 0xC0000142
3339 def skip_on_low_desktop_heap_memory_subprocess(returncode):
3340 if sys.platform not in ('win32', 'cygwin'):
3341 return
3342 # On Windows, STATUS_DLL_INIT_FAILED is a generic error code that could
3343 # come from any of the DLLs being loaded when a new Python process is
3344 # created. In practice, it's likely a memory allocation failure in the
3345 # desktop heap memory which caused the DLL init failure, especially on
3346 # process created with CREATE_NEW_CONSOLE creation flag. See the article:
3347 # https://learn.microsoft.com/en-us/troubleshoot/windows-server/performance/desktop-heap-limitation-out-of-memory
3348 if returncode == STATUS_DLL_INIT_FAILED:
3349 raise unittest.SkipTest('gh-150436: DLL init failed, likely because '
3350 'of low desktop heap memory')