Debian Codegraph @

Lib/test/libregrtest/setup.py

raw
1 import faulthandler
2 import gc
3 import io
4 import os
5 import random
6 import signal
7 import sys
8 import unittest
9 from test import support
10 from test.support.os_helper import TESTFN_UNDECODABLE, FS_NONASCII
11 from _colorize import can_colorize # type: ignore[import-not-found]
12
13 from .filter import set_match_tests
14 from .runtests import RunTests
15 from .utils import (
16 setup_unraisable_hook, setup_threading_excepthook, fix_umask,
17 adjust_rlimit_nofile)
18
19
20 UNICODE_GUARD_ENV = "PYTHONREGRTEST_UNICODE_GUARD"
21
22
23 def setup_test_dir(testdir: str | None) -> None:
24 if testdir:
25 # Prepend test directory to sys.path, so runtest() will be able
26 # to locate tests
27 sys.path.insert(0, os.path.abspath(testdir))
28
29
30 def setup_process() -> None:
31 fix_umask()
32
33 assert sys.__stderr__ is not None, "sys.__stderr__ is None"
34 try:
35 stderr_fd = sys.__stderr__.fileno()
36 except (ValueError, AttributeError):
37 # Catch ValueError to catch io.UnsupportedOperation on TextIOBase
38 # and ValueError on a closed stream.
39 #
40 # Catch AttributeError for stderr being None.
41 pass
42 else:
43 # Display the Python traceback on fatal errors (e.g. segfault)
44 faulthandler.enable(all_threads=True, file=stderr_fd)
45
46 # Display the Python traceback on SIGALRM or SIGUSR1 signal
47 signals: list[signal.Signals] = []
48 if hasattr(signal, 'SIGALRM'):
49 signals.append(signal.SIGALRM)
50 if hasattr(signal, 'SIGUSR1'):
51 signals.append(signal.SIGUSR1)
52 for signum in signals:
53 faulthandler.register(signum, chain=True, file=stderr_fd)
54
55 # Restore the default SIGINT handler if there is no Python-level
56 # handler. Python inherits the SIG_IGN disposition when the test
57 # suite runs as a shell background job; then asyncio.Runner does not
58 # install its own handler and _thread.interrupt_main() is a no-op,
59 # which makes some tests in test_asyncio and test_threading hang.
60 if signal.getsignal(signal.SIGINT) in (signal.SIG_IGN, signal.SIG_DFL):
61 signal.signal(signal.SIGINT, signal.default_int_handler)
62
63 adjust_rlimit_nofile()
64
65 support.record_original_stdout(sys.stdout)
66
67 # Set sys.stdout encoder error handler to backslashreplace,
68 # similar to sys.stderr error handler, to avoid UnicodeEncodeError
69 # when printing a traceback or any other non-encodable character.
70 #
71 # Use an assertion to fix mypy error.
72 assert isinstance(sys.stdout, io.TextIOWrapper)
73 sys.stdout.reconfigure(errors="backslashreplace")
74
75 # Some times __path__ and __file__ are not absolute (e.g. while running from
76 # Lib/) and, if we change the CWD to run the tests in a temporary dir, some
77 # imports might fail. This affects only the modules imported before os.chdir().
78 # These modules are searched first in sys.path[0] (so '' -- the CWD) and if
79 # they are found in the CWD their __file__ and __path__ will be relative (this
80 # happens before the chdir). All the modules imported after the chdir, are
81 # not found in the CWD, and since the other paths in sys.path[1:] are absolute
82 # (site.py absolutize them), the __file__ and __path__ will be absolute too.
83 # Therefore it is necessary to absolutize manually the __file__ and __path__ of
84 # the packages to prevent later imports to fail when the CWD is different.
85 for module in sys.modules.values():
86 if hasattr(module, '__path__'):
87 for index, path in enumerate(module.__path__):
88 module.__path__[index] = os.path.abspath(path)
89 if getattr(module, '__file__', None):
90 module.__file__ = os.path.abspath(module.__file__) # type: ignore[type-var]
91
92 if hasattr(sys, 'addaudithook'):
93 # Add an auditing hook for all tests to ensure PySys_Audit is tested
94 def _test_audit_hook(name, args):
95 pass
96 sys.addaudithook(_test_audit_hook)
97
98 setup_unraisable_hook()
99 setup_threading_excepthook()
100
101 # Ensure there's a non-ASCII character in env vars at all times to force
102 # tests consider this case. See BPO-44647 for details.
103 if TESTFN_UNDECODABLE and os.supports_bytes_environ:
104 os.environb.setdefault(UNICODE_GUARD_ENV.encode(), TESTFN_UNDECODABLE)
105 elif FS_NONASCII:
106 os.environ.setdefault(UNICODE_GUARD_ENV, FS_NONASCII)
107
108
109 def setup_tests(runtests: RunTests) -> None:
110 support.verbose = runtests.verbose
111 support.failfast = runtests.fail_fast
112 support.PGO = runtests.pgo
113 support.PGO_EXTENDED = runtests.pgo_extended
114
115 set_match_tests(runtests.match_tests)
116
117 if runtests.use_junit:
118 support.junit_xml_list = []
119 from .testresult import RegressionTestResult
120 RegressionTestResult.USE_XML = True
121 else:
122 support.junit_xml_list = None
123
124 if runtests.memory_limit is not None:
125 support.set_memlimit(runtests.memory_limit)
126
127 support.suppress_msvcrt_asserts(runtests.verbose >= 2)
128
129 support.use_resources = runtests.use_resources
130
131 timeout = runtests.timeout
132 if timeout is not None:
133 # For a slow buildbot worker, increase SHORT_TIMEOUT and LONG_TIMEOUT
134 support.LOOPBACK_TIMEOUT = max(support.LOOPBACK_TIMEOUT, timeout / 120)
135 # don't increase INTERNET_TIMEOUT
136 support.SHORT_TIMEOUT = max(support.SHORT_TIMEOUT, timeout / 40)
137 support.LONG_TIMEOUT = max(support.LONG_TIMEOUT, timeout / 4)
138
139 # If --timeout is short: reduce timeouts
140 support.LOOPBACK_TIMEOUT = min(support.LOOPBACK_TIMEOUT, timeout)
141 support.INTERNET_TIMEOUT = min(support.INTERNET_TIMEOUT, timeout)
142 support.SHORT_TIMEOUT = min(support.SHORT_TIMEOUT, timeout)
143 support.LONG_TIMEOUT = min(support.LONG_TIMEOUT, timeout)
144
145 if runtests.hunt_refleak:
146 # private attribute that mypy doesn't know about:
147 unittest.BaseTestSuite._cleanup = False # type: ignore[attr-defined]
148
149 if runtests.gc_threshold is not None:
150 gc.set_threshold(runtests.gc_threshold)
151
152 random.seed(runtests.random_seed)
153
154 # sys.stdout is redirected to a StringIO in single process mode on which
155 # color auto-detect fails as StringIO is not a TTY. If the original
156 # sys.stdout supports color pass that through with FORCE_COLOR so that when
157 # results are printed, such as with -W, they get color.
158 if can_colorize(file=sys.stdout):
159 os.environ['FORCE_COLOR'] = "1"