blob: 83ce2f73f4e5a62529b1ffd640576ceb61a3d8b5 [file] [log] [blame]
Victor Stinner234cbef2015-09-30 01:13:53 +02001import atexit
2import faulthandler
3import os
4import signal
5import sys
6import unittest
7from test import support
8try:
9 import gc
10except ImportError:
11 gc = None
12
Victor Stinnerb136b1a2021-04-16 14:33:10 +020013from test.libregrtest.utils import (setup_unraisable_hook,
14 setup_threading_excepthook)
Victor Stinner95f61c82019-06-13 01:09:04 +020015
Victor Stinner234cbef2015-09-30 01:13:53 +020016
Victor Stinnera2045022015-09-30 02:17:28 +020017def setup_tests(ns):
Victor Stinnerccef8232017-10-13 12:59:12 -070018 try:
19 stderr_fd = sys.__stderr__.fileno()
20 except (ValueError, AttributeError):
21 # Catch ValueError to catch io.UnsupportedOperation on TextIOBase
22 # and ValueError on a closed stream.
23 #
24 # Catch AttributeError for stderr being None.
25 stderr_fd = None
26 else:
27 # Display the Python traceback on fatal errors (e.g. segfault)
28 faulthandler.enable(all_threads=True, file=stderr_fd)
Victor Stinner234cbef2015-09-30 01:13:53 +020029
Victor Stinnerccef8232017-10-13 12:59:12 -070030 # Display the Python traceback on SIGALRM or SIGUSR1 signal
31 signals = []
32 if hasattr(signal, 'SIGALRM'):
33 signals.append(signal.SIGALRM)
34 if hasattr(signal, 'SIGUSR1'):
35 signals.append(signal.SIGUSR1)
36 for signum in signals:
37 faulthandler.register(signum, chain=True, file=stderr_fd)
Victor Stinner234cbef2015-09-30 01:13:53 +020038
39 replace_stdout()
40 support.record_original_stdout(sys.stdout)
41
Victor Stinner9759dd32016-03-30 02:32:52 +020042 if ns.testdir:
43 # Prepend test directory to sys.path, so runtest() will be able
44 # to locate tests
45 sys.path.insert(0, os.path.abspath(ns.testdir))
46
Victor Stinner234cbef2015-09-30 01:13:53 +020047 # Some times __path__ and __file__ are not absolute (e.g. while running from
48 # Lib/) and, if we change the CWD to run the tests in a temporary dir, some
49 # imports might fail. This affects only the modules imported before os.chdir().
50 # These modules are searched first in sys.path[0] (so '' -- the CWD) and if
51 # they are found in the CWD their __file__ and __path__ will be relative (this
52 # happens before the chdir). All the modules imported after the chdir, are
53 # not found in the CWD, and since the other paths in sys.path[1:] are absolute
54 # (site.py absolutize them), the __file__ and __path__ will be absolute too.
55 # Therefore it is necessary to absolutize manually the __file__ and __path__ of
56 # the packages to prevent later imports to fail when the CWD is different.
57 for module in sys.modules.values():
58 if hasattr(module, '__path__'):
Victor Stinner82f04e22016-03-15 23:08:44 +010059 for index, path in enumerate(module.__path__):
60 module.__path__[index] = os.path.abspath(path)
Ned Deilye52ac042018-03-28 01:57:13 -040061 if getattr(module, '__file__', None):
Victor Stinner234cbef2015-09-30 01:13:53 +020062 module.__file__ = os.path.abspath(module.__file__)
63
Victor Stinner234cbef2015-09-30 01:13:53 +020064 if ns.huntrleaks:
65 unittest.BaseTestSuite._cleanup = False
Pablo Galindoaf5fa132021-02-28 22:41:09 +000066 sys._deactivate_opcache()
Victor Stinner234cbef2015-09-30 01:13:53 +020067
Victor Stinner234cbef2015-09-30 01:13:53 +020068 if ns.memlimit is not None:
69 support.set_memlimit(ns.memlimit)
70
71 if ns.threshold is not None:
72 gc.set_threshold(ns.threshold)
73
Victor Stinnerf6e58ae2020-06-10 18:49:23 +020074 support.suppress_msvcrt_asserts(ns.verbose and ns.verbose >= 2)
Victor Stinner234cbef2015-09-30 01:13:53 +020075
Victor Stinnera2045022015-09-30 02:17:28 +020076 support.use_resources = ns.use_resources
77
Steve Dowerb82e17e2019-05-23 08:45:22 -070078 if hasattr(sys, 'addaudithook'):
79 # Add an auditing hook for all tests to ensure PySys_Audit is tested
80 def _test_audit_hook(name, args):
81 pass
82 sys.addaudithook(_test_audit_hook)
83
Victor Stinner95f61c82019-06-13 01:09:04 +020084 setup_unraisable_hook()
Victor Stinnerb136b1a2021-04-16 14:33:10 +020085 setup_threading_excepthook()
Victor Stinner95f61c82019-06-13 01:09:04 +020086
Victor Stinner24c62582019-10-30 12:41:43 +010087 if ns.timeout is not None:
88 # For a slow buildbot worker, increase SHORT_TIMEOUT and LONG_TIMEOUT
89 support.SHORT_TIMEOUT = max(support.SHORT_TIMEOUT, ns.timeout / 40)
90 support.LONG_TIMEOUT = max(support.LONG_TIMEOUT, ns.timeout / 4)
91
92 # If --timeout is short: reduce timeouts
93 support.LOOPBACK_TIMEOUT = min(support.LOOPBACK_TIMEOUT, ns.timeout)
94 support.INTERNET_TIMEOUT = min(support.INTERNET_TIMEOUT, ns.timeout)
95 support.SHORT_TIMEOUT = min(support.SHORT_TIMEOUT, ns.timeout)
96 support.LONG_TIMEOUT = min(support.LONG_TIMEOUT, ns.timeout)
97
Victor Stinner30793e82021-03-23 01:11:31 +010098 if ns.xmlpath:
99 from test.support.testresult import RegressionTestResult
100 RegressionTestResult.USE_XML = True
101
Victor Stinner234cbef2015-09-30 01:13:53 +0200102
103def replace_stdout():
104 """Set stdout encoder error handler to backslashreplace (as stderr error
105 handler) to avoid UnicodeEncodeError when printing a traceback"""
106 stdout = sys.stdout
Victor Stinnerccef8232017-10-13 12:59:12 -0700107 try:
108 fd = stdout.fileno()
109 except ValueError:
110 # On IDLE, sys.stdout has no file descriptor and is not a TextIOWrapper
111 # object. Leaving sys.stdout unchanged.
112 #
113 # Catch ValueError to catch io.UnsupportedOperation on TextIOBase
114 # and ValueError on a closed stream.
115 return
116
117 sys.stdout = open(fd, 'w',
Victor Stinner234cbef2015-09-30 01:13:53 +0200118 encoding=stdout.encoding,
119 errors="backslashreplace",
120 closefd=False,
121 newline='\n')
122
123 def restore_stdout():
124 sys.stdout.close()
125 sys.stdout = stdout
126 atexit.register(restore_stdout)