Debian Codegraph @

tests/test/support/__init__.py

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