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 adjust_rlimit_nofile()
56
57 support.record_original_stdout(sys.stdout)
58
59 # Set sys.stdout encoder error handler to backslashreplace,
60 # similar to sys.stderr error handler, to avoid UnicodeEncodeError
61 # when printing a traceback or any other non-encodable character.
62 #
63 # Use an assertion to fix mypy error.
64 assert isinstance(sys.stdout, io.TextIOWrapper)
65 sys.stdout.reconfigure(errors="backslashreplace")
66
67 # Some times __path__ and __file__ are not absolute (e.g. while running from
68 # Lib/) and, if we change the CWD to run the tests in a temporary dir, some
69 # imports might fail. This affects only the modules imported before os.chdir().
70 # These modules are searched first in sys.path[0] (so '' -- the CWD) and if
71 # they are found in the CWD their __file__ and __path__ will be relative (this
72 # happens before the chdir). All the modules imported after the chdir, are
73 # not found in the CWD, and since the other paths in sys.path[1:] are absolute
74 # (site.py absolutize them), the __file__ and __path__ will be absolute too.
75 # Therefore it is necessary to absolutize manually the __file__ and __path__ of
76 # the packages to prevent later imports to fail when the CWD is different.
77 for module in sys.modules.values():
78 if hasattr(module, '__path__'):
79 for index, path in enumerate(module.__path__):
80 module.__path__[index] = os.path.abspath(path)
81 if getattr(module, '__file__', None):
82 module.__file__ = os.path.abspath(module.__file__) # type: ignore[type-var]
83
84 if hasattr(sys, 'addaudithook'):
85 # Add an auditing hook for all tests to ensure PySys_Audit is tested
86 def _test_audit_hook(name, args):
87 pass
88 sys.addaudithook(_test_audit_hook)
89
90 setup_unraisable_hook()
91 setup_threading_excepthook()
92
93 # Ensure there's a non-ASCII character in env vars at all times to force
94 # tests consider this case. See BPO-44647 for details.
95 if TESTFN_UNDECODABLE and os.supports_bytes_environ:
96 os.environb.setdefault(UNICODE_GUARD_ENV.encode(), TESTFN_UNDECODABLE)
97 elif FS_NONASCII:
98 os.environ.setdefault(UNICODE_GUARD_ENV, FS_NONASCII)
99
100
101 def setup_tests(runtests: RunTests) -> None:
102 support.verbose = runtests.verbose
103 support.failfast = runtests.fail_fast
104 support.PGO = runtests.pgo
105 support.PGO_EXTENDED = runtests.pgo_extended
106
107 set_match_tests(runtests.match_tests)
108
109 if runtests.use_junit:
110 support.junit_xml_list = []
111 from .testresult import RegressionTestResult
112 RegressionTestResult.USE_XML = True
113 else:
114 support.junit_xml_list = None
115
116 if runtests.memory_limit is not None:
117 support.set_memlimit(runtests.memory_limit)
118
119 support.suppress_msvcrt_asserts(runtests.verbose >= 2)
120
121 support.use_resources = runtests.use_resources
122
123 timeout = runtests.timeout
124 if timeout is not None:
125 # For a slow buildbot worker, increase SHORT_TIMEOUT and LONG_TIMEOUT
126 support.LOOPBACK_TIMEOUT = max(support.LOOPBACK_TIMEOUT, timeout / 120)
127 # don't increase INTERNET_TIMEOUT
128 support.SHORT_TIMEOUT = max(support.SHORT_TIMEOUT, timeout / 40)
129 support.LONG_TIMEOUT = max(support.LONG_TIMEOUT, timeout / 4)
130
131 # If --timeout is short: reduce timeouts
132 support.LOOPBACK_TIMEOUT = min(support.LOOPBACK_TIMEOUT, timeout)
133 support.INTERNET_TIMEOUT = min(support.INTERNET_TIMEOUT, timeout)
134 support.SHORT_TIMEOUT = min(support.SHORT_TIMEOUT, timeout)
135 support.LONG_TIMEOUT = min(support.LONG_TIMEOUT, timeout)
136
137 if runtests.hunt_refleak:
138 # private attribute that mypy doesn't know about:
139 unittest.BaseTestSuite._cleanup = False # type: ignore[attr-defined]
140
141 if runtests.gc_threshold is not None:
142 gc.set_threshold(runtests.gc_threshold)
143
144 random.seed(runtests.random_seed)
145
146 # sys.stdout is redirected to a StringIO in single process mode on which
147 # color auto-detect fails as StringIO is not a TTY. If the original
148 # sys.stdout supports color pass that through with FORCE_COLOR so that when
149 # results are printed, such as with -W, they get color.
150 if can_colorize(file=sys.stdout):
151 os.environ['FORCE_COLOR'] = "1"