Debian Codegraph @

lib-python/3/test/support/__init__.py

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