Debian Codegraph @

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