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", "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 bigaddrspacetest(f):
1219 """Decorator for tests that fill the address space."""
1220 def wrapper(self):
1221 if max_memuse < MAX_Py_ssize_t:
1222 if MAX_Py_ssize_t >= 2**63 - 1 and max_memuse >= 2**31:
1223 raise unittest.SkipTest(
1224 "not enough memory: try a 32-bit build instead")
1225 else:
1226 raise unittest.SkipTest(
1227 "not enough memory: %.1fG minimum needed"
1228 % (MAX_Py_ssize_t / (1024 ** 3)))
1229 else:
1230 return f(self)
1231 return wrapper
1232
1233 #=======================================================================
1234 # unittest integration.
1235
1236 def _id(obj):
1237 return obj
1238
1239 def requires_resource(resource):
1240 if resource == 'gui' and not _is_gui_available():
1241 return unittest.skip(_is_gui_available.reason)
1242 if is_resource_enabled(resource):
1243 return _id
1244 else:
1245 return unittest.skip("resource {0!r} is not enabled".format(resource))
1246
1247 def cpython_only(test):
1248 """
1249 Decorator for tests only applicable on CPython.
1250 """
1251 return impl_detail(cpython=True)(test)
1252
1253 def impl_detail(msg=None, **guards):
1254 if check_impl_detail(**guards):
1255 return _id
1256 if msg is None:
1257 guardnames, default = _parse_guards(guards)
1258 if default:
1259 msg = "implementation detail not available on {0}"
1260 else:
1261 msg = "implementation detail specific to {0}"
1262 guardnames = sorted(guardnames.keys())
1263 msg = msg.format(' or '.join(guardnames))
1264 return unittest.skip(msg)
1265
1266 def _parse_guards(guards):
1267 # Returns a tuple ({platform_name: run_me}, default_value)
1268 if not guards:
1269 return ({'cpython': True}, False)
1270 is_true = list(guards.values())[0]
1271 assert list(guards.values()) == [is_true] * len(guards) # all True or all False
1272 return (guards, not is_true)
1273
1274 # Use the following check to guard CPython's implementation-specific tests --
1275 # or to run them only on the implementation(s) guarded by the arguments.
1276 def check_impl_detail(**guards):
1277 """This function returns True or False depending on the host platform.
1278 Examples:
1279 if check_impl_detail(): # only on CPython (default)
1280 if check_impl_detail(jython=True): # only on Jython
1281 if check_impl_detail(cpython=False): # everywhere except on CPython
1282 """
1283 guards, default = _parse_guards(guards)
1284 return guards.get(sys.implementation.name, default)
1285
1286
1287 def no_tracing(func):
1288 """Decorator to temporarily turn off tracing for the duration of a test."""
1289 trace_wrapper = func
1290 if hasattr(sys, 'gettrace'):
1291 @functools.wraps(func)
1292 def trace_wrapper(*args, **kwargs):
1293 original_trace = sys.gettrace()
1294 try:
1295 sys.settrace(None)
1296 return func(*args, **kwargs)
1297 finally:
1298 sys.settrace(original_trace)
1299
1300 coverage_wrapper = trace_wrapper
1301 if 'test.cov' in sys.modules: # -Xpresite=test.cov used
1302 cov = sys.monitoring.COVERAGE_ID
1303 @functools.wraps(func)
1304 def coverage_wrapper(*args, **kwargs):
1305 original_events = sys.monitoring.get_events(cov)
1306 try:
1307 sys.monitoring.set_events(cov, 0)
1308 return trace_wrapper(*args, **kwargs)
1309 finally:
1310 sys.monitoring.set_events(cov, original_events)
1311
1312 return coverage_wrapper
1313
1314
1315 def refcount_test(test):
1316 """Decorator for tests which involve reference counting.
1317
1318 To start, the decorator does not run the test if is not run by CPython.
1319 After that, any trace function is unset during the test to prevent
1320 unexpected refcounts caused by the trace function.
1321
1322 """
1323 return no_tracing(cpython_only(test))
1324
1325
1326 def requires_limited_api(test):
1327 try:
1328 import _testcapi
1329 import _testlimitedcapi
1330 except ImportError:
1331 return unittest.skip('needs _testcapi and _testlimitedcapi modules')(test)
1332 return test
1333
1334
1335 # Windows build doesn't support --disable-test-modules feature, so there's no
1336 # 'TEST_MODULES' var in config
1337 TEST_MODULES_ENABLED = (sysconfig.get_config_var('TEST_MODULES') or 'yes') == 'yes'
1338
1339 def requires_specialization(test):
1340 return unittest.skipUnless(
1341 _opcode.ENABLE_SPECIALIZATION, "requires specialization")(test)
1342
1343
1344 #=======================================================================
1345 # Check for the presence of docstrings.
1346
1347 # Rather than trying to enumerate all the cases where docstrings may be
1348 # disabled, we just check for that directly
1349
1350 def _check_docstrings():
1351 """Just used to check if docstrings are enabled"""
1352
1353 MISSING_C_DOCSTRINGS = (check_impl_detail() and
1354 sys.platform != 'win32' and
1355 not sysconfig.get_config_var('WITH_DOC_STRINGS'))
1356
1357 HAVE_PY_DOCSTRINGS = _check_docstrings.__doc__ is not None
1358 HAVE_DOCSTRINGS = (HAVE_PY_DOCSTRINGS and not MISSING_C_DOCSTRINGS)
1359
1360 requires_docstrings = unittest.skipUnless(HAVE_DOCSTRINGS,
1361 "test requires docstrings")
1362
1363
1364 #=======================================================================
1365 # Support for saving and restoring the imported modules.
1366
1367 def flush_std_streams():
1368 if sys.stdout is not None:
1369 sys.stdout.flush()
1370 if sys.stderr is not None:
1371 sys.stderr.flush()
1372
1373
1374 def print_warning(msg):
1375 # bpo-45410: Explicitly flush stdout to keep logs in order
1376 flush_std_streams()
1377 stream = print_warning.orig_stderr
1378 for line in msg.splitlines():
1379 print(f"Warning -- {line}", file=stream)
1380 stream.flush()
1381
1382 # bpo-39983: Store the original sys.stderr at Python startup to be able to
1383 # log warnings even if sys.stderr is captured temporarily by a test.
1384 print_warning.orig_stderr = sys.stderr
1385
1386
1387 # Flag used by saved_test_environment of test.libregrtest.save_env,
1388 # to check if a test modified the environment. The flag should be set to False
1389 # before running a new test.
1390 #
1391 # For example, threading_helper.threading_cleanup() sets the flag is the function fails
1392 # to cleanup threads.
1393 environment_altered = False
1394
1395 def reap_children():
1396 """Use this function at the end of test_main() whenever sub-processes
1397 are started. This will help ensure that no extra children (zombies)
1398 stick around to hog resources and create problems when looking
1399 for refleaks.
1400 """
1401 global environment_altered
1402
1403 # Need os.waitpid(-1, os.WNOHANG): Windows is not supported
1404 if not (hasattr(os, 'waitpid') and hasattr(os, 'WNOHANG')):
1405 return
1406 elif not has_subprocess_support:
1407 return
1408
1409 # Reap all our dead child processes so we don't leave zombies around.
1410 # These hog resources and might be causing some of the buildbots to die.
1411 while True:
1412 try:
1413 # Read the exit status of any child process which already completed
1414 pid, status = os.waitpid(-1, os.WNOHANG)
1415 except OSError:
1416 break
1417
1418 if pid == 0:
1419 break
1420
1421 print_warning(f"reap_children() reaped child process {pid}")
1422 environment_altered = True
1423
1424
1425 @contextlib.contextmanager
1426 def swap_attr(obj, attr, new_val):
1427 """Temporary swap out an attribute with a new object.
1428
1429 Usage:
1430 with swap_attr(obj, "attr", 5):
1431 ...
1432
1433 This will set obj.attr to 5 for the duration of the with: block,
1434 restoring the old value at the end of the block. If `attr` doesn't
1435 exist on `obj`, it will be created and then deleted at the end of the
1436 block.
1437
1438 The old value (or None if it doesn't exist) will be assigned to the
1439 target of the "as" clause, if there is one.
1440 """
1441 if hasattr(obj, attr):
1442 real_val = getattr(obj, attr)
1443 setattr(obj, attr, new_val)
1444 try:
1445 yield real_val
1446 finally:
1447 setattr(obj, attr, real_val)
1448 else:
1449 setattr(obj, attr, new_val)
1450 try:
1451 yield
1452 finally:
1453 if hasattr(obj, attr):
1454 delattr(obj, attr)
1455
1456 @contextlib.contextmanager
1457 def swap_item(obj, item, new_val):
1458 """Temporary swap out an item with a new object.
1459
1460 Usage:
1461 with swap_item(obj, "item", 5):
1462 ...
1463
1464 This will set obj["item"] to 5 for the duration of the with: block,
1465 restoring the old value at the end of the block. If `item` doesn't
1466 exist on `obj`, it will be created and then deleted at the end of the
1467 block.
1468
1469 The old value (or None if it doesn't exist) will be assigned to the
1470 target of the "as" clause, if there is one.
1471 """
1472 if item in obj:
1473 real_val = obj[item]
1474 obj[item] = new_val
1475 try:
1476 yield real_val
1477 finally:
1478 obj[item] = real_val
1479 else:
1480 obj[item] = new_val
1481 try:
1482 yield
1483 finally:
1484 if item in obj:
1485 del obj[item]
1486
1487 def args_from_interpreter_flags():
1488 """Return a list of command-line arguments reproducing the current
1489 settings in sys.flags and sys.warnoptions."""
1490 import subprocess
1491 return subprocess._args_from_interpreter_flags()
1492
1493 def optim_args_from_interpreter_flags():
1494 """Return a list of command-line arguments reproducing the current
1495 optimization settings in sys.flags."""
1496 import subprocess
1497 return subprocess._optim_args_from_interpreter_flags()
1498
1499
1500 class Matcher(object):
1501
1502 _partial_matches = ('msg', 'message')
1503
1504 def matches(self, d, **kwargs):
1505 """
1506 Try to match a single dict with the supplied arguments.
1507
1508 Keys whose values are strings and which are in self._partial_matches
1509 will be checked for partial (i.e. substring) matches. You can extend
1510 this scheme to (for example) do regular expression matching, etc.
1511 """
1512 result = True
1513 for k in kwargs:
1514 v = kwargs[k]
1515 dv = d.get(k)
1516 if not self.match_value(k, dv, v):
1517 result = False
1518 break
1519 return result
1520
1521 def match_value(self, k, dv, v):
1522 """
1523 Try to match a single stored value (dv) with a supplied value (v).
1524 """
1525 if type(v) != type(dv):
1526 result = False
1527 elif type(dv) is not str or k not in self._partial_matches:
1528 result = (v == dv)
1529 else:
1530 result = dv.find(v) >= 0
1531 return result
1532
1533
1534 _buggy_ucrt = None
1535 def skip_if_buggy_ucrt_strfptime(test):
1536 """
1537 Skip decorator for tests that use buggy strptime/strftime
1538
1539 If the UCRT bugs are present time.localtime().tm_zone will be
1540 an empty string, otherwise we assume the UCRT bugs are fixed
1541
1542 See bpo-37552 [Windows] strptime/strftime return invalid
1543 results with UCRT version 17763.615
1544 """
1545 import locale
1546 global _buggy_ucrt
1547 if _buggy_ucrt is None:
1548 if(sys.platform == 'win32' and
1549 locale.getencoding() == 'cp65001' and
1550 time.localtime().tm_zone == ''):
1551 _buggy_ucrt = True
1552 else:
1553 _buggy_ucrt = False
1554 return unittest.skip("buggy MSVC UCRT strptime/strftime")(test) if _buggy_ucrt else test
1555
1556 class PythonSymlink:
1557 """Creates a symlink for the current Python executable"""
1558 def __init__(self, link=None):
1559 from .os_helper import TESTFN
1560
1561 self.link = link or os.path.abspath(TESTFN)
1562 self._linked = []
1563 self.real = os.path.realpath(sys.executable)
1564 self._also_link = []
1565
1566 self._env = None
1567
1568 self._platform_specific()
1569
1570 if sys.platform == "win32":
1571 def _platform_specific(self):
1572 import glob
1573 import _winapi
1574
1575 if os.path.lexists(self.real) and not os.path.exists(self.real):
1576 # App symlink appears to not exist, but we want the
1577 # real executable here anyway
1578 self.real = _winapi.GetModuleFileName(0)
1579
1580 dll = _winapi.GetModuleFileName(sys.dllhandle)
1581 src_dir = os.path.dirname(dll)
1582 dest_dir = os.path.dirname(self.link)
1583 self._also_link.append((
1584 dll,
1585 os.path.join(dest_dir, os.path.basename(dll))
1586 ))
1587 for runtime in glob.glob(os.path.join(glob.escape(src_dir), "vcruntime*.dll")):
1588 self._also_link.append((
1589 runtime,
1590 os.path.join(dest_dir, os.path.basename(runtime))
1591 ))
1592
1593 self._env = {k.upper(): os.getenv(k) for k in os.environ}
1594 self._env["PYTHONHOME"] = os.path.dirname(self.real)
1595 if sysconfig.is_python_build():
1596 self._env["PYTHONPATH"] = STDLIB_DIR
1597 else:
1598 def _platform_specific(self):
1599 pass
1600
1601 def __enter__(self):
1602 os.symlink(self.real, self.link)
1603 self._linked.append(self.link)
1604 for real, link in self._also_link:
1605 os.symlink(real, link)
1606 self._linked.append(link)
1607 return self
1608
1609 def __exit__(self, exc_type, exc_value, exc_tb):
1610 for link in self._linked:
1611 try:
1612 os.remove(link)
1613 except IOError as ex:
1614 if verbose:
1615 print("failed to clean up {}: {}".format(link, ex))
1616
1617 def _call(self, python, args, env, returncode):
1618 import subprocess
1619 cmd = [python, *args]
1620 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
1621 stderr=subprocess.PIPE, env=env)
1622 r = p.communicate()
1623 if p.returncode != returncode:
1624 if verbose:
1625 print(repr(r[0]))
1626 print(repr(r[1]), file=sys.stderr)
1627 raise RuntimeError(
1628 'unexpected return code: {0} (0x{0:08X})'.format(p.returncode))
1629 return r
1630
1631 def call_real(self, *args, returncode=0):
1632 return self._call(self.real, args, None, returncode)
1633
1634 def call_link(self, *args, returncode=0):
1635 return self._call(self.link, args, self._env, returncode)
1636
1637
1638 def skip_if_pgo_task(test):
1639 """Skip decorator for tests not run in (non-extended) PGO task"""
1640 ok = not PGO or PGO_EXTENDED
1641 msg = "Not run for (non-extended) PGO task"
1642 return test if ok else unittest.skip(msg)(test)
1643
1644
1645 def detect_api_mismatch(ref_api, other_api, *, ignore=()):
1646 """Returns the set of items in ref_api not in other_api, except for a
1647 defined list of items to be ignored in this check.
1648
1649 By default this skips private attributes beginning with '_' but
1650 includes all magic methods, i.e. those starting and ending in '__'.
1651 """
1652 missing_items = set(dir(ref_api)) - set(dir(other_api))
1653 if ignore:
1654 missing_items -= set(ignore)
1655 missing_items = set(m for m in missing_items
1656 if not m.startswith('_') or m.endswith('__'))
1657 return missing_items
1658
1659
1660 def check__all__(test_case, module, name_of_module=None, extra=(),
1661 not_exported=()):
1662 """Assert that the __all__ variable of 'module' contains all public names.
1663
1664 The module's public names (its API) are detected automatically based on
1665 whether they match the public name convention and were defined in
1666 'module'.
1667
1668 The 'name_of_module' argument can specify (as a string or tuple thereof)
1669 what module(s) an API could be defined in order to be detected as a
1670 public API. One case for this is when 'module' imports part of its public
1671 API from other modules, possibly a C backend (like 'csv' and its '_csv').
1672
1673 The 'extra' argument can be a set of names that wouldn't otherwise be
1674 automatically detected as "public", like objects without a proper
1675 '__module__' attribute. If provided, it will be added to the
1676 automatically detected ones.
1677
1678 The 'not_exported' argument can be a set of names that must not be treated
1679 as part of the public API even though their names indicate otherwise.
1680
1681 Usage:
1682 import bar
1683 import foo
1684 import unittest
1685 from test import support
1686
1687 class MiscTestCase(unittest.TestCase):
1688 def test__all__(self):
1689 support.check__all__(self, foo)
1690
1691 class OtherTestCase(unittest.TestCase):
1692 def test__all__(self):
1693 extra = {'BAR_CONST', 'FOO_CONST'}
1694 not_exported = {'baz'} # Undocumented name.
1695 # bar imports part of its API from _bar.
1696 support.check__all__(self, bar, ('bar', '_bar'),
1697 extra=extra, not_exported=not_exported)
1698
1699 """
1700
1701 if name_of_module is None:
1702 name_of_module = (module.__name__, )
1703 elif isinstance(name_of_module, str):
1704 name_of_module = (name_of_module, )
1705
1706 expected = set(extra)
1707
1708 for name in dir(module):
1709 if name.startswith('_') or name in not_exported:
1710 continue
1711 obj = getattr(module, name)
1712 if (getattr(obj, '__module__', None) in name_of_module or
1713 (not hasattr(obj, '__module__') and
1714 not isinstance(obj, types.ModuleType))):
1715 expected.add(name)
1716 test_case.assertCountEqual(module.__all__, expected)
1717
1718
1719 def suppress_msvcrt_asserts(verbose=False):
1720 try:
1721 import msvcrt
1722 except ImportError:
1723 return
1724
1725 msvcrt.SetErrorMode(msvcrt.SEM_FAILCRITICALERRORS
1726 | msvcrt.SEM_NOALIGNMENTFAULTEXCEPT
1727 | msvcrt.SEM_NOGPFAULTERRORBOX
1728 | msvcrt.SEM_NOOPENFILEERRORBOX)
1729
1730 # CrtSetReportMode() is only available in debug build
1731 if hasattr(msvcrt, 'CrtSetReportMode'):
1732 for m in [msvcrt.CRT_WARN, msvcrt.CRT_ERROR, msvcrt.CRT_ASSERT]:
1733 if verbose:
1734 msvcrt.CrtSetReportMode(m, msvcrt.CRTDBG_MODE_FILE)
1735 msvcrt.CrtSetReportFile(m, msvcrt.CRTDBG_FILE_STDERR)
1736 else:
1737 msvcrt.CrtSetReportMode(m, 0)
1738
1739
1740 class SuppressCrashReport:
1741 """Try to prevent a crash report from popping up.
1742
1743 On Windows, don't display the Windows Error Reporting dialog. On UNIX,
1744 disable the creation of coredump file.
1745 """
1746 old_value = None
1747 old_modes = None
1748
1749 def __enter__(self):
1750 """On Windows, disable Windows Error Reporting dialogs using
1751 SetErrorMode() and CrtSetReportMode().
1752
1753 On UNIX, try to save the previous core file size limit, then set
1754 soft limit to 0.
1755 """
1756 if sys.platform.startswith('win'):
1757 # see http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx
1758 try:
1759 import msvcrt
1760 except ImportError:
1761 return
1762
1763 self.old_value = msvcrt.GetErrorMode()
1764
1765 msvcrt.SetErrorMode(self.old_value | msvcrt.SEM_NOGPFAULTERRORBOX)
1766
1767 # bpo-23314: Suppress assert dialogs in debug builds.
1768 # CrtSetReportMode() is only available in debug build.
1769 if hasattr(msvcrt, 'CrtSetReportMode'):
1770 self.old_modes = {}
1771 for report_type in [msvcrt.CRT_WARN,
1772 msvcrt.CRT_ERROR,
1773 msvcrt.CRT_ASSERT]:
1774 old_mode = msvcrt.CrtSetReportMode(report_type,
1775 msvcrt.CRTDBG_MODE_FILE)
1776 old_file = msvcrt.CrtSetReportFile(report_type,
1777 msvcrt.CRTDBG_FILE_STDERR)
1778 self.old_modes[report_type] = old_mode, old_file
1779
1780 else:
1781 try:
1782 import resource
1783 self.resource = resource
1784 except ImportError:
1785 self.resource = None
1786 if self.resource is not None:
1787 try:
1788 self.old_value = self.resource.getrlimit(self.resource.RLIMIT_CORE)
1789 self.resource.setrlimit(self.resource.RLIMIT_CORE,
1790 (0, self.old_value[1]))
1791 except (ValueError, OSError):
1792 pass
1793
1794 if sys.platform == 'darwin':
1795 import subprocess
1796 # Check if the 'Crash Reporter' on OSX was configured
1797 # in 'Developer' mode and warn that it will get triggered
1798 # when it is.
1799 #
1800 # This assumes that this context manager is used in tests
1801 # that might trigger the next manager.
1802 cmd = ['/usr/bin/defaults', 'read',
1803 'com.apple.CrashReporter', 'DialogType']
1804 proc = subprocess.Popen(cmd,
1805 stdout=subprocess.PIPE,
1806 stderr=subprocess.PIPE)
1807 with proc:
1808 stdout = proc.communicate()[0]
1809 if stdout.strip() == b'developer':
1810 print("this test triggers the Crash Reporter, "
1811 "that is intentional", end='', flush=True)
1812
1813 return self
1814
1815 def __exit__(self, *ignore_exc):
1816 """Restore Windows ErrorMode or core file behavior to initial value."""
1817 if self.old_value is None:
1818 return
1819
1820 if sys.platform.startswith('win'):
1821 import msvcrt
1822 msvcrt.SetErrorMode(self.old_value)
1823
1824 if self.old_modes:
1825 for report_type, (old_mode, old_file) in self.old_modes.items():
1826 msvcrt.CrtSetReportMode(report_type, old_mode)
1827 msvcrt.CrtSetReportFile(report_type, old_file)
1828 else:
1829 if self.resource is not None:
1830 try:
1831 self.resource.setrlimit(self.resource.RLIMIT_CORE, self.old_value)
1832 except (ValueError, OSError):
1833 pass
1834
1835
1836 def patch(test_instance, object_to_patch, attr_name, new_value):
1837 """Override 'object_to_patch'.'attr_name' with 'new_value'.
1838
1839 Also, add a cleanup procedure to 'test_instance' to restore
1840 'object_to_patch' value for 'attr_name'.
1841 The 'attr_name' should be a valid attribute for 'object_to_patch'.
1842
1843 """
1844 # check that 'attr_name' is a real attribute for 'object_to_patch'
1845 # will raise AttributeError if it does not exist
1846 getattr(object_to_patch, attr_name)
1847
1848 # keep a copy of the old value
1849 attr_is_local = False
1850 try:
1851 old_value = object_to_patch.__dict__[attr_name]
1852 except (AttributeError, KeyError):
1853 old_value = getattr(object_to_patch, attr_name, None)
1854 else:
1855 attr_is_local = True
1856
1857 # restore the value when the test is done
1858 def cleanup():
1859 if attr_is_local:
1860 setattr(object_to_patch, attr_name, old_value)
1861 else:
1862 delattr(object_to_patch, attr_name)
1863
1864 test_instance.addCleanup(cleanup)
1865
1866 # actually override the attribute
1867 setattr(object_to_patch, attr_name, new_value)
1868
1869
1870 @contextlib.contextmanager
1871 def patch_list(orig):
1872 """Like unittest.mock.patch.dict, but for lists."""
1873 try:
1874 saved = orig[:]
1875 yield
1876 finally:
1877 orig[:] = saved
1878
1879
1880 def run_in_subinterp(code):
1881 """
1882 Run code in a subinterpreter. Raise unittest.SkipTest if the tracemalloc
1883 module is enabled.
1884 """
1885 _check_tracemalloc()
1886 try:
1887 import _testcapi
1888 except ImportError:
1889 raise unittest.SkipTest("requires _testcapi")
1890 return _testcapi.run_in_subinterp(code)
1891
1892
1893 def run_in_subinterp_with_config(code, *, own_gil=None, **config):
1894 """
1895 Run code in a subinterpreter. Raise unittest.SkipTest if the tracemalloc
1896 module is enabled.
1897 """
1898 _check_tracemalloc()
1899 try:
1900 import _testinternalcapi
1901 except ImportError:
1902 raise unittest.SkipTest("requires _testinternalcapi")
1903 if own_gil is not None:
1904 assert 'gil' not in config, (own_gil, config)
1905 config['gil'] = 'own' if own_gil else 'shared'
1906 else:
1907 gil = config['gil']
1908 if gil == 0:
1909 config['gil'] = 'default'
1910 elif gil == 1:
1911 config['gil'] = 'shared'
1912 elif gil == 2:
1913 config['gil'] = 'own'
1914 elif not isinstance(gil, str):
1915 raise NotImplementedError(gil)
1916 config = types.SimpleNamespace(**config)
1917 return _testinternalcapi.run_in_subinterp_with_config(code, config)
1918
1919
1920 def _check_tracemalloc():
1921 # Issue #10915, #15751: PyGILState_*() functions don't work with
1922 # sub-interpreters, the tracemalloc module uses these functions internally
1923 try:
1924 import tracemalloc
1925 except ImportError:
1926 pass
1927 else:
1928 if tracemalloc.is_tracing():
1929 raise unittest.SkipTest("run_in_subinterp() cannot be used "
1930 "if tracemalloc module is tracing "
1931 "memory allocations")
1932
1933
1934 def check_free_after_iterating(test, iter, cls, args=()):
1935 done = False
1936 def wrapper():
1937 class A(cls):
1938 def __del__(self):
1939 nonlocal done
1940 done = True
1941 try:
1942 next(it)
1943 except StopIteration:
1944 pass
1945
1946 it = iter(A(*args))
1947 # Issue 26494: Shouldn't crash
1948 test.assertRaises(StopIteration, next, it)
1949
1950 wrapper()
1951 # The sequence should be deallocated just after the end of iterating
1952 gc_collect()
1953 test.assertTrue(done)
1954
1955
1956 def missing_compiler_executable(cmd_names=[]):
1957 """Check if the compiler components used to build the interpreter exist.
1958
1959 Check for the existence of the compiler executables whose names are listed
1960 in 'cmd_names' or all the compiler executables when 'cmd_names' is empty
1961 and return the first missing executable or None when none is found
1962 missing.
1963
1964 """
1965 from setuptools._distutils import ccompiler, sysconfig
1966 from setuptools import errors
1967 import shutil
1968
1969 compiler = ccompiler.new_compiler()
1970 sysconfig.customize_compiler(compiler)
1971 if compiler.compiler_type == "msvc":
1972 # MSVC has no executables, so check whether initialization succeeds
1973 try:
1974 compiler.initialize()
1975 except errors.PlatformError:
1976 return "msvc"
1977 for name in compiler.executables:
1978 if cmd_names and name not in cmd_names:
1979 continue
1980 cmd = getattr(compiler, name)
1981 if cmd_names:
1982 assert cmd is not None, \
1983 "the '%s' executable is not configured" % name
1984 elif not cmd:
1985 continue
1986 if shutil.which(cmd[0]) is None:
1987 return cmd[0]
1988
1989
1990 _old_android_emulator = None
1991 def setswitchinterval(interval):
1992 # Setting a very low gil interval on the Android emulator causes python
1993 # to hang (issue #26939).
1994 minimum_interval = 1e-4 # 100 us
1995 if is_android and interval < minimum_interval:
1996 global _old_android_emulator
1997 if _old_android_emulator is None:
1998 import platform
1999 av = platform.android_ver()
2000 _old_android_emulator = av.is_emulator and av.api_level < 24
2001 if _old_android_emulator:
2002 interval = minimum_interval
2003 return sys.setswitchinterval(interval)
2004
2005
2006 def get_pagesize():
2007 """Get size of a page in bytes."""
2008 try:
2009 page_size = os.sysconf('SC_PAGESIZE')
2010 except (ValueError, AttributeError):
2011 try:
2012 page_size = os.sysconf('SC_PAGE_SIZE')
2013 except (ValueError, AttributeError):
2014 page_size = 4096
2015 return page_size
2016
2017
2018 @contextlib.contextmanager
2019 def disable_faulthandler():
2020 import faulthandler
2021
2022 # use sys.__stderr__ instead of sys.stderr, since regrtest replaces
2023 # sys.stderr with a StringIO which has no file descriptor when a test
2024 # is run with -W/--verbose3.
2025 fd = sys.__stderr__.fileno()
2026
2027 is_enabled = faulthandler.is_enabled()
2028 try:
2029 faulthandler.disable()
2030 yield
2031 finally:
2032 if is_enabled:
2033 faulthandler.enable(file=fd, all_threads=True)
2034
2035
2036 class SaveSignals:
2037 """
2038 Save and restore signal handlers.
2039
2040 This class is only able to save/restore signal handlers registered
2041 by the Python signal module: see bpo-13285 for "external" signal
2042 handlers.
2043 """
2044
2045 def __init__(self):
2046 import signal
2047 self.signal = signal
2048 self.signals = signal.valid_signals()
2049 # SIGKILL and SIGSTOP signals cannot be ignored nor caught
2050 for signame in ('SIGKILL', 'SIGSTOP'):
2051 try:
2052 signum = getattr(signal, signame)
2053 except AttributeError:
2054 continue
2055 self.signals.remove(signum)
2056 self.handlers = {}
2057
2058 def save(self):
2059 for signum in self.signals:
2060 handler = self.signal.getsignal(signum)
2061 if handler is None:
2062 # getsignal() returns None if a signal handler was not
2063 # registered by the Python signal module,
2064 # and the handler is not SIG_DFL nor SIG_IGN.
2065 #
2066 # Ignore the signal: we cannot restore the handler.
2067 continue
2068 self.handlers[signum] = handler
2069
2070 def restore(self):
2071 for signum, handler in self.handlers.items():
2072 self.signal.signal(signum, handler)
2073
2074
2075 def with_pymalloc():
2076 try:
2077 import _testcapi
2078 except ImportError:
2079 raise unittest.SkipTest("requires _testcapi")
2080 return _testcapi.WITH_PYMALLOC and not Py_GIL_DISABLED
2081
2082
2083 def with_mimalloc():
2084 try:
2085 import _testcapi
2086 except ImportError:
2087 raise unittest.SkipTest("requires _testcapi")
2088 return _testcapi.WITH_MIMALLOC
2089
2090
2091 class _ALWAYS_EQ:
2092 """
2093 Object that is equal to anything.
2094 """
2095 def __eq__(self, other):
2096 return True
2097 def __ne__(self, other):
2098 return False
2099
2100 ALWAYS_EQ = _ALWAYS_EQ()
2101
2102 class _NEVER_EQ:
2103 """
2104 Object that is not equal to anything.
2105 """
2106 def __eq__(self, other):
2107 return False
2108 def __ne__(self, other):
2109 return True
2110 def __hash__(self):
2111 return 1
2112
2113 NEVER_EQ = _NEVER_EQ()
2114
2115 @functools.total_ordering
2116 class _LARGEST:
2117 """
2118 Object that is greater than anything (except itself).
2119 """
2120 def __eq__(self, other):
2121 return isinstance(other, _LARGEST)
2122 def __lt__(self, other):
2123 return False
2124
2125 LARGEST = _LARGEST()
2126
2127 @functools.total_ordering
2128 class _SMALLEST:
2129 """
2130 Object that is less than anything (except itself).
2131 """
2132 def __eq__(self, other):
2133 return isinstance(other, _SMALLEST)
2134 def __gt__(self, other):
2135 return False
2136
2137 SMALLEST = _SMALLEST()
2138
2139 def maybe_get_event_loop_policy():
2140 """Return the global event loop policy if one is set, else return None."""
2141 import asyncio.events
2142 return asyncio.events._event_loop_policy
2143
2144 # Helpers for testing hashing.
2145 NHASHBITS = sys.hash_info.width # number of bits in hash() result
2146 assert NHASHBITS in (32, 64)
2147
2148 # Return mean and sdev of number of collisions when tossing nballs balls
2149 # uniformly at random into nbins bins. By definition, the number of
2150 # collisions is the number of balls minus the number of occupied bins at
2151 # the end.
2152 def collision_stats(nbins, nballs):
2153 n, k = nbins, nballs
2154 # prob a bin empty after k trials = (1 - 1/n)**k
2155 # mean # empty is then n * (1 - 1/n)**k
2156 # so mean # occupied is n - n * (1 - 1/n)**k
2157 # so collisions = k - (n - n*(1 - 1/n)**k)
2158 #
2159 # For the variance:
2160 # n*(n-1)*(1-2/n)**k + meanempty - meanempty**2 =
2161 # n*(n-1)*(1-2/n)**k + meanempty * (1 - meanempty)
2162 #
2163 # Massive cancellation occurs, and, e.g., for a 64-bit hash code
2164 # 1-1/2**64 rounds uselessly to 1.0. Rather than make heroic (and
2165 # error-prone) efforts to rework the naive formulas to avoid those,
2166 # we use the `decimal` module to get plenty of extra precision.
2167 #
2168 # Note: the exact values are straightforward to compute with
2169 # rationals, but in context that's unbearably slow, requiring
2170 # multi-million bit arithmetic.
2171 import decimal
2172 with decimal.localcontext() as ctx:
2173 bits = n.bit_length() * 2 # bits in n**2
2174 # At least that many bits will likely cancel out.
2175 # Use that many decimal digits instead.
2176 ctx.prec = max(bits, 30)
2177 dn = decimal.Decimal(n)
2178 p1empty = ((dn - 1) / dn) ** k
2179 meanempty = n * p1empty
2180 occupied = n - meanempty
2181 collisions = k - occupied
2182 var = dn*(dn-1)*((dn-2)/dn)**k + meanempty * (1 - meanempty)
2183 return float(collisions), float(var.sqrt())
2184
2185
2186 class catch_unraisable_exception:
2187 """
2188 Context manager catching unraisable exception using sys.unraisablehook.
2189
2190 Storing the exception value (cm.unraisable.exc_value) creates a reference
2191 cycle. The reference cycle is broken explicitly when the context manager
2192 exits.
2193
2194 Storing the object (cm.unraisable.object) can resurrect it if it is set to
2195 an object which is being finalized. Exiting the context manager clears the
2196 stored object.
2197
2198 Usage:
2199
2200 with support.catch_unraisable_exception() as cm:
2201 # code creating an "unraisable exception"
2202 ...
2203
2204 # check the unraisable exception: use cm.unraisable
2205 ...
2206
2207 # cm.unraisable attribute no longer exists at this point
2208 # (to break a reference cycle)
2209 """
2210
2211 def __init__(self):
2212 self.unraisable = None
2213 self._old_hook = None
2214
2215 def _hook(self, unraisable):
2216 # Storing unraisable.object can resurrect an object which is being
2217 # finalized. Storing unraisable.exc_value creates a reference cycle.
2218 self.unraisable = unraisable
2219
2220 def __enter__(self):
2221 self._old_hook = sys.unraisablehook
2222 sys.unraisablehook = self._hook
2223 return self
2224
2225 def __exit__(self, *exc_info):
2226 sys.unraisablehook = self._old_hook
2227 del self.unraisable
2228
2229
2230 def wait_process(pid, *, exitcode, timeout=None):
2231 """
2232 Wait until process pid completes and check that the process exit code is
2233 exitcode.
2234
2235 Raise an AssertionError if the process exit code is not equal to exitcode.
2236
2237 If the process runs longer than timeout seconds (LONG_TIMEOUT by default),
2238 kill the process (if signal.SIGKILL is available) and raise an
2239 AssertionError. The timeout feature is not available on Windows.
2240 """
2241 if os.name != "nt":
2242 import signal
2243
2244 if timeout is None:
2245 timeout = LONG_TIMEOUT
2246
2247 start_time = time.monotonic()
2248 for _ in sleeping_retry(timeout, error=False):
2249 pid2, status = os.waitpid(pid, os.WNOHANG)
2250 if pid2 != 0:
2251 break
2252 # rety: the process is still running
2253 else:
2254 try:
2255 os.kill(pid, signal.SIGKILL)
2256 os.waitpid(pid, 0)
2257 except OSError:
2258 # Ignore errors like ChildProcessError or PermissionError
2259 pass
2260
2261 dt = time.monotonic() - start_time
2262 raise AssertionError(f"process {pid} is still running "
2263 f"after {dt:.1f} seconds")
2264 else:
2265 # Windows implementation: don't support timeout :-(
2266 pid2, status = os.waitpid(pid, 0)
2267
2268 exitcode2 = os.waitstatus_to_exitcode(status)
2269 if exitcode2 != exitcode:
2270 raise AssertionError(f"process {pid} exited with code {exitcode2}, "
2271 f"but exit code {exitcode} is expected")
2272
2273 # sanity check: it should not fail in practice
2274 if pid2 != pid:
2275 raise AssertionError(f"pid {pid2} != pid {pid}")
2276
2277 def skip_if_broken_multiprocessing_synchronize():
2278 """
2279 Skip tests if the multiprocessing.synchronize module is missing, if there
2280 is no available semaphore implementation, or if creating a lock raises an
2281 OSError (on Linux only).
2282 """
2283 from .import_helper import import_module
2284
2285 # Skip tests if the _multiprocessing extension is missing.
2286 import_module('_multiprocessing')
2287
2288 # Skip tests if there is no available semaphore implementation:
2289 # multiprocessing.synchronize requires _multiprocessing.SemLock.
2290 synchronize = import_module('multiprocessing.synchronize')
2291
2292 if sys.platform == "linux":
2293 try:
2294 # bpo-38377: On Linux, creating a semaphore fails with OSError
2295 # if the current user does not have the permission to create
2296 # a file in /dev/shm/ directory.
2297 synchronize.Lock(ctx=None)
2298 except OSError as exc:
2299 raise unittest.SkipTest(f"broken multiprocessing SemLock: {exc!r}")
2300
2301
2302 def check_disallow_instantiation(testcase, tp, *args, **kwds):
2303 """
2304 Check that given type cannot be instantiated using *args and **kwds.
2305
2306 See bpo-43916: Add Py_TPFLAGS_DISALLOW_INSTANTIATION type flag.
2307 """
2308 mod = tp.__module__
2309 name = tp.__name__
2310 if mod != 'builtins':
2311 qualname = f"{mod}.{name}"
2312 else:
2313 qualname = f"{name}"
2314 msg = f"cannot create '{re.escape(qualname)}' instances"
2315 testcase.assertRaisesRegex(TypeError, msg, tp, *args, **kwds)
2316 testcase.assertRaisesRegex(TypeError, msg, tp.__new__, tp, *args, **kwds)
2317
2318 def get_recursion_depth():
2319 """Get the recursion depth of the caller function.
2320
2321 In the __main__ module, at the module level, it should be 1.
2322 """
2323 try:
2324 import _testinternalcapi
2325 depth = _testinternalcapi.get_recursion_depth()
2326 except (ImportError, RecursionError) as exc:
2327 # sys._getframe() + frame.f_back implementation.
2328 try:
2329 depth = 0
2330 frame = sys._getframe()
2331 while frame is not None:
2332 depth += 1
2333 frame = frame.f_back
2334 finally:
2335 # Break any reference cycles.
2336 frame = None
2337
2338 # Ignore get_recursion_depth() frame.
2339 return max(depth - 1, 1)
2340
2341 def get_recursion_available():
2342 """Get the number of available frames before RecursionError.
2343
2344 It depends on the current recursion depth of the caller function and
2345 sys.getrecursionlimit().
2346 """
2347 limit = sys.getrecursionlimit()
2348 depth = get_recursion_depth()
2349 return limit - depth
2350
2351 @contextlib.contextmanager
2352 def set_recursion_limit(limit):
2353 """Temporarily change the recursion limit."""
2354 original_limit = sys.getrecursionlimit()
2355 try:
2356 sys.setrecursionlimit(limit)
2357 yield
2358 finally:
2359 sys.setrecursionlimit(original_limit)
2360
2361 def infinite_recursion(max_depth=None):
2362 if max_depth is None:
2363 # Pick a number large enough to cause problems
2364 # but not take too long for code that can handle
2365 # very deep recursion.
2366 max_depth = 20_000
2367 elif max_depth < 3:
2368 raise ValueError(f"max_depth must be at least 3, got {max_depth}")
2369 depth = get_recursion_depth()
2370 depth = max(depth - 1, 1) # Ignore infinite_recursion() frame.
2371 limit = depth + max_depth
2372 return set_recursion_limit(limit)
2373
2374 def ignore_deprecations_from(module: str, *, like: str) -> object:
2375 token = object()
2376 warnings.filterwarnings(
2377 "ignore",
2378 category=DeprecationWarning,
2379 module=module,
2380 message=like + fr"(?#support{id(token)})",
2381 )
2382 return token
2383
2384 def clear_ignored_deprecations(*tokens: object) -> None:
2385 if not tokens:
2386 raise ValueError("Provide token or tokens returned by ignore_deprecations_from")
2387
2388 new_filters = []
2389 endswith = tuple(rf"(?#support{id(token)})" for token in tokens)
2390 for action, message, category, module, lineno in warnings.filters:
2391 if action == "ignore" and category is DeprecationWarning:
2392 if isinstance(message, re.Pattern):
2393 msg = message.pattern
2394 else:
2395 msg = message or ""
2396 if msg.endswith(endswith):
2397 continue
2398 new_filters.append((action, message, category, module, lineno))
2399 if warnings.filters != new_filters:
2400 warnings.filters[:] = new_filters
2401 warnings._filters_mutated()
2402
2403
2404 # Skip a test if venv with pip is known to not work.
2405 def requires_venv_with_pip():
2406 # ensurepip requires zlib to open ZIP archives (.whl binary wheel packages)
2407 try:
2408 import zlib
2409 except ImportError:
2410 return unittest.skipIf(True, "venv: ensurepip requires zlib")
2411
2412 # bpo-26610: pip/pep425tags.py requires ctypes.
2413 # gh-92820: setuptools/windows_support.py uses ctypes (setuptools 58.1).
2414 try:
2415 import ctypes
2416 except ImportError:
2417 ctypes = None
2418 return unittest.skipUnless(ctypes, 'venv: pip requires ctypes')
2419
2420
2421 @functools.cache
2422 def _findwheel(pkgname):
2423 """Try to find a wheel with the package specified as pkgname.
2424
2425 If set, the wheels are searched for in WHEEL_PKG_DIR (see ensurepip).
2426 Otherwise, they are searched for in the test directory.
2427 """
2428 wheel_dir = sysconfig.get_config_var('WHEEL_PKG_DIR') or os.path.join(
2429 TEST_HOME_DIR, 'wheeldata',
2430 )
2431 filenames = os.listdir(wheel_dir)
2432 filenames = sorted(filenames, reverse=True) # approximate "newest" first
2433 for filename in filenames:
2434 # filename is like 'setuptools-{version}-py3-none-any.whl'
2435 if not filename.endswith(".whl"):
2436 continue
2437 prefix = pkgname + '-'
2438 if filename.startswith(prefix):
2439 return os.path.join(wheel_dir, filename)
2440 raise FileNotFoundError(f"No wheel for {pkgname} found in {wheel_dir}")
2441
2442
2443 # Context manager that creates a virtual environment, install setuptools in it,
2444 # and returns the paths to the venv directory and the python executable
2445 @contextlib.contextmanager
2446 def setup_venv_with_pip_setuptools(venv_dir):
2447 import subprocess
2448 from .os_helper import temp_cwd
2449
2450 def run_command(cmd):
2451 if verbose:
2452 import shlex
2453 print()
2454 print('Run:', ' '.join(map(shlex.quote, cmd)))
2455 subprocess.run(cmd, check=True)
2456 else:
2457 subprocess.run(cmd,
2458 stdout=subprocess.PIPE,
2459 stderr=subprocess.STDOUT,
2460 check=True)
2461
2462 with temp_cwd() as temp_dir:
2463 # Create virtual environment to get setuptools
2464 cmd = [sys.executable, '-X', 'dev', '-m', 'venv', venv_dir]
2465 run_command(cmd)
2466
2467 venv = os.path.join(temp_dir, venv_dir)
2468
2469 # Get the Python executable of the venv
2470 python_exe = os.path.basename(sys.executable)
2471 if sys.platform == 'win32':
2472 python = os.path.join(venv, 'Scripts', python_exe)
2473 else:
2474 python = os.path.join(venv, 'bin', python_exe)
2475
2476 cmd = (python, '-X', 'dev',
2477 '-m', 'pip', 'install',
2478 _findwheel('setuptools'),
2479 )
2480 run_command(cmd)
2481
2482 yield python
2483
2484
2485 # True if Python is built with the Py_DEBUG macro defined: if
2486 # Python is built in debug mode (./configure --with-pydebug).
2487 Py_DEBUG = hasattr(sys, 'gettotalrefcount')
2488
2489
2490 def late_deletion(obj):
2491 """
2492 Keep a Python alive as long as possible.
2493
2494 Create a reference cycle and store the cycle in an object deleted late in
2495 Python finalization. Try to keep the object alive until the very last
2496 garbage collection.
2497
2498 The function keeps a strong reference by design. It should be called in a
2499 subprocess to not mark a test as "leaking a reference".
2500 """
2501
2502 # Late CPython finalization:
2503 # - finalize_interp_clear()
2504 # - _PyInterpreterState_Clear(): Clear PyInterpreterState members
2505 # (ex: codec_search_path, before_forkers)
2506 # - clear os.register_at_fork() callbacks
2507 # - clear codecs.register() callbacks
2508
2509 ref_cycle = [obj]
2510 ref_cycle.append(ref_cycle)
2511
2512 # Store a reference in PyInterpreterState.codec_search_path
2513 import codecs
2514 def search_func(encoding):
2515 return None
2516 search_func.reference = ref_cycle
2517 codecs.register(search_func)
2518
2519 if hasattr(os, 'register_at_fork'):
2520 # Store a reference in PyInterpreterState.before_forkers
2521 def atfork_func():
2522 pass
2523 atfork_func.reference = ref_cycle
2524 os.register_at_fork(before=atfork_func)
2525
2526
2527 def busy_retry(timeout, err_msg=None, /, *, error=True):
2528 """
2529 Run the loop body until "break" stops the loop.
2530
2531 After *timeout* seconds, raise an AssertionError if *error* is true,
2532 or just stop if *error is false.
2533
2534 Example:
2535
2536 for _ in support.busy_retry(support.SHORT_TIMEOUT):
2537 if check():
2538 break
2539
2540 Example of error=False usage:
2541
2542 for _ in support.busy_retry(support.SHORT_TIMEOUT, error=False):
2543 if check():
2544 break
2545 else:
2546 raise RuntimeError('my custom error')
2547
2548 """
2549 if timeout <= 0:
2550 raise ValueError("timeout must be greater than zero")
2551
2552 start_time = time.monotonic()
2553 deadline = start_time + timeout
2554
2555 while True:
2556 yield
2557
2558 if time.monotonic() >= deadline:
2559 break
2560
2561 if error:
2562 dt = time.monotonic() - start_time
2563 msg = f"timeout ({dt:.1f} seconds)"
2564 if err_msg:
2565 msg = f"{msg}: {err_msg}"
2566 raise AssertionError(msg)
2567
2568
2569 def sleeping_retry(timeout, err_msg=None, /,
2570 *, init_delay=0.010, max_delay=1.0, error=True):
2571 """
2572 Wait strategy that applies exponential backoff.
2573
2574 Run the loop body until "break" stops the loop. Sleep at each loop
2575 iteration, but not at the first iteration. The sleep delay is doubled at
2576 each iteration (up to *max_delay* seconds).
2577
2578 See busy_retry() documentation for the parameters usage.
2579
2580 Example raising an exception after SHORT_TIMEOUT seconds:
2581
2582 for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
2583 if check():
2584 break
2585
2586 Example of error=False usage:
2587
2588 for _ in support.sleeping_retry(support.SHORT_TIMEOUT, error=False):
2589 if check():
2590 break
2591 else:
2592 raise RuntimeError('my custom error')
2593 """
2594
2595 delay = init_delay
2596 for _ in busy_retry(timeout, err_msg, error=error):
2597 yield
2598
2599 time.sleep(delay)
2600 delay = min(delay * 2, max_delay)
2601
2602
2603 class CPUStopwatch:
2604 """Context manager to roughly time a CPU-bound operation.
2605
2606 Disables GC. Uses CPU time if it can (i.e. excludes sleeps & time of
2607 other processes).
2608
2609 N.B.:
2610 - This *includes* time spent in other threads.
2611 - Some systems only have a coarse resolution; check
2612 stopwatch.clock_info.rseolution if.
2613
2614 Usage:
2615
2616 with ProcessStopwatch() as stopwatch:
2617 ...
2618 elapsed = stopwatch.seconds
2619 resolution = stopwatch.clock_info.resolution
2620 """
2621 def __enter__(self):
2622 get_time = time.process_time
2623 clock_info = time.get_clock_info('process_time')
2624 if get_time() <= 0: # some platforms like WASM lack process_time()
2625 get_time = time.monotonic
2626 clock_info = time.get_clock_info('monotonic')
2627 self.context = disable_gc()
2628 self.context.__enter__()
2629 self.get_time = get_time
2630 self.clock_info = clock_info
2631 self.start_time = get_time()
2632 return self
2633
2634 def __exit__(self, *exc):
2635 try:
2636 end_time = self.get_time()
2637 finally:
2638 result = self.context.__exit__(*exc)
2639 self.seconds = end_time - self.start_time
2640 return result
2641
2642
2643 @contextlib.contextmanager
2644 def adjust_int_max_str_digits(max_digits):
2645 """Temporarily change the integer string conversion length limit."""
2646 current = sys.get_int_max_str_digits()
2647 try:
2648 sys.set_int_max_str_digits(max_digits)
2649 yield
2650 finally:
2651 sys.set_int_max_str_digits(current)
2652
2653
2654 def get_c_recursion_limit():
2655 try:
2656 import _testcapi
2657 return _testcapi.Py_C_RECURSION_LIMIT
2658 except ImportError:
2659 raise unittest.SkipTest('requires _testcapi')
2660
2661
2662 def exceeds_recursion_limit():
2663 """For recursion tests, easily exceeds default recursion limit."""
2664 return get_c_recursion_limit() * 3
2665
2666
2667 # Windows doesn't have os.uname() but it doesn't support s390x.
2668 is_s390x = hasattr(os, 'uname') and os.uname().machine == 's390x'
2669 skip_on_s390x = unittest.skipIf(is_s390x, 'skipped on s390x')
2670
2671 Py_TRACE_REFS = hasattr(sys, 'getobjects')
2672
2673 # Decorator to disable optimizer while a function run
2674 def without_optimizer(func):
2675 try:
2676 from _testinternalcapi import get_optimizer, set_optimizer
2677 except ImportError:
2678 return func
2679 @functools.wraps(func)
2680 def wrapper(*args, **kwargs):
2681 save_opt = get_optimizer()
2682 try:
2683 set_optimizer(None)
2684 return func(*args, **kwargs)
2685 finally:
2686 set_optimizer(save_opt)
2687 return wrapper
2688
2689
2690 _BASE_COPY_SRC_DIR_IGNORED_NAMES = frozenset({
2691 # SRC_DIR/.git
2692 '.git',
2693 # ignore all __pycache__/ sub-directories
2694 '__pycache__',
2695 })
2696
2697 # Ignore function for shutil.copytree() to copy the Python source code.
2698 def copy_python_src_ignore(path, names):
2699 ignored = _BASE_COPY_SRC_DIR_IGNORED_NAMES
2700 if os.path.basename(path) == 'Doc':
2701 ignored |= {
2702 # SRC_DIR/Doc/build/
2703 'build',
2704 # SRC_DIR/Doc/venv/
2705 'venv',
2706 }
2707
2708 # check if we are at the root of the source code
2709 elif 'Modules' in names:
2710 ignored |= {
2711 # SRC_DIR/build/
2712 'build',
2713 }
2714 return ignored
2715
2716
2717 def iter_builtin_types():
2718 for obj in __builtins__.values():
2719 if not isinstance(obj, type):
2720 continue
2721 cls = obj
2722 if cls.__module__ != 'builtins':
2723 continue
2724 yield cls
2725
2726
2727 def iter_slot_wrappers(cls):
2728 assert cls.__module__ == 'builtins', cls
2729
2730 def is_slot_wrapper(name, value):
2731 if not isinstance(value, types.WrapperDescriptorType):
2732 assert not repr(value).startswith('<slot wrapper '), (cls, name, value)
2733 return False
2734 assert repr(value).startswith('<slot wrapper '), (cls, name, value)
2735 assert callable(value), (cls, name, value)
2736 assert name.startswith('__') and name.endswith('__'), (cls, name, value)
2737 return True
2738
2739 ns = vars(cls)
2740 unused = set(ns)
2741 for name in dir(cls):
2742 if name in ns:
2743 unused.remove(name)
2744
2745 try:
2746 value = getattr(cls, name)
2747 except AttributeError:
2748 # It's as though it weren't in __dir__.
2749 assert name in ('__annotate__', '__annotations__', '__abstractmethods__'), (cls, name)
2750 if name in ns and is_slot_wrapper(name, ns[name]):
2751 unused.add(name)
2752 continue
2753
2754 if not name.startswith('__') or not name.endswith('__'):
2755 assert not is_slot_wrapper(name, value), (cls, name, value)
2756 if not is_slot_wrapper(name, value):
2757 if name in ns:
2758 assert not is_slot_wrapper(name, ns[name]), (cls, name, value, ns[name])
2759 else:
2760 if name in ns:
2761 assert ns[name] is value, (cls, name, value, ns[name])
2762 yield name, True
2763 else:
2764 yield name, False
2765
2766 for name in unused:
2767 value = ns[name]
2768 if is_slot_wrapper(cls, name, value):
2769 yield name, True
2770
2771
2772 @contextlib.contextmanager
2773 def no_color():
2774 import _colorize
2775 from .os_helper import EnvironmentVarGuard
2776
2777 with (
2778 swap_attr(_colorize, "can_colorize", lambda *, file=None: False),
2779 EnvironmentVarGuard() as env,
2780 ):
2781 env.unset("FORCE_COLOR", "NO_COLOR", "PYTHON_COLORS")
2782 env.set("NO_COLOR", "1")
2783 yield
2784
2785
2786 def force_not_colorized(func):
2787 """Force the terminal not to be colorized."""
2788 @functools.wraps(func)
2789 def wrapper(*args, **kwargs):
2790 with no_color():
2791 return func(*args, **kwargs)
2792 return wrapper
2793
2794
2795 def force_not_colorized_test_class(cls):
2796 """Force the terminal not to be colorized for the entire test class."""
2797 original_setUpClass = cls.setUpClass
2798
2799 @classmethod
2800 @functools.wraps(cls.setUpClass)
2801 def new_setUpClass(cls):
2802 cls.enterClassContext(no_color())
2803 original_setUpClass()
2804
2805 cls.setUpClass = new_setUpClass
2806 return cls
2807
2808
2809 def make_clean_env() -> dict[str, str]:
2810 clean_env = os.environ.copy()
2811 for k in clean_env.copy():
2812 if k.startswith("PYTHON"):
2813 clean_env.pop(k)
2814 clean_env.pop("FORCE_COLOR", None)
2815 clean_env.pop("NO_COLOR", None)
2816 return clean_env
2817
2818
2819 def initialized_with_pyrepl():
2820 """Detect whether PyREPL was used during Python initialization."""
2821 # If the main module has a __file__ attribute it's a Python module, which means PyREPL.
2822 return hasattr(sys.modules["__main__"], "__file__")
2823
2824
2825 class BrokenIter:
2826 def __init__(self, init_raises=False, next_raises=False, iter_raises=False):
2827 if init_raises:
2828 1/0
2829 self.next_raises = next_raises
2830 self.iter_raises = iter_raises
2831
2832 def __next__(self):
2833 if self.next_raises:
2834 1/0
2835
2836 def __iter__(self):
2837 if self.iter_raises:
2838 1/0
2839 return self
2840
2841
2842 def linked_to_musl():
2843 """
2844 Test if the Python executable is linked to the musl C library.
2845 """
2846 if sys.platform != 'linux':
2847 return False
2848
2849 import subprocess
2850 exe = getattr(sys, '_base_executable', sys.executable)
2851 cmd = ['ldd', exe]
2852 try:
2853 stdout = subprocess.check_output(cmd,
2854 text=True,
2855 stderr=subprocess.STDOUT)
2856 except (OSError, subprocess.CalledProcessError):
2857 return False
2858 return ('musl' in stdout)
2859
2860
2861 def control_characters_c0() -> list[str]:
2862 """Returns a list of C0 control characters as strings.
2863 C0 control characters defined as the byte range 0x00-0x1F, and 0x7F.
2864 """
2865 return [chr(c) for c in range(0x00, 0x20)] + ["\x7F"]