blob: 5254e7fc6fe0c1766cadcc02ee94267808d70e88 [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 Stinner95f61c82019-06-13 01:09:04 +020013from test.libregrtest.utils import setup_unraisable_hook
14
Victor Stinner234cbef2015-09-30 01:13:53 +020015
Victor Stinnera2045022015-09-30 02:17:28 +020016def setup_tests(ns):
Victor Stinnerccef8232017-10-13 12:59:12 -070017 try:
18 stderr_fd = sys.__stderr__.fileno()
19 except (ValueError, AttributeError):
20 # Catch ValueError to catch io.UnsupportedOperation on TextIOBase
21 # and ValueError on a closed stream.
22 #
23 # Catch AttributeError for stderr being None.
24 stderr_fd = None
25 else:
26 # Display the Python traceback on fatal errors (e.g. segfault)
27 faulthandler.enable(all_threads=True, file=stderr_fd)
Victor Stinner234cbef2015-09-30 01:13:53 +020028
Victor Stinnerccef8232017-10-13 12:59:12 -070029 # Display the Python traceback on SIGALRM or SIGUSR1 signal
30 signals = []
31 if hasattr(signal, 'SIGALRM'):
32 signals.append(signal.SIGALRM)
33 if hasattr(signal, 'SIGUSR1'):
34 signals.append(signal.SIGUSR1)
35 for signum in signals:
36 faulthandler.register(signum, chain=True, file=stderr_fd)
Victor Stinner234cbef2015-09-30 01:13:53 +020037
38 replace_stdout()
39 support.record_original_stdout(sys.stdout)
40
Victor Stinner9759dd32016-03-30 02:32:52 +020041 if ns.testdir:
42 # Prepend test directory to sys.path, so runtest() will be able
43 # to locate tests
44 sys.path.insert(0, os.path.abspath(ns.testdir))
45
Victor Stinner234cbef2015-09-30 01:13:53 +020046 # Some times __path__ and __file__ are not absolute (e.g. while running from
47 # Lib/) and, if we change the CWD to run the tests in a temporary dir, some
48 # imports might fail. This affects only the modules imported before os.chdir().
49 # These modules are searched first in sys.path[0] (so '' -- the CWD) and if
50 # they are found in the CWD their __file__ and __path__ will be relative (this
51 # happens before the chdir). All the modules imported after the chdir, are
52 # not found in the CWD, and since the other paths in sys.path[1:] are absolute
53 # (site.py absolutize them), the __file__ and __path__ will be absolute too.
54 # Therefore it is necessary to absolutize manually the __file__ and __path__ of
55 # the packages to prevent later imports to fail when the CWD is different.
56 for module in sys.modules.values():
57 if hasattr(module, '__path__'):
Victor Stinner82f04e22016-03-15 23:08:44 +010058 for index, path in enumerate(module.__path__):
59 module.__path__[index] = os.path.abspath(path)
Ned Deilye52ac042018-03-28 01:57:13 -040060 if getattr(module, '__file__', None):
Victor Stinner234cbef2015-09-30 01:13:53 +020061 module.__file__ = os.path.abspath(module.__file__)
62
Victor Stinner234cbef2015-09-30 01:13:53 +020063 if ns.huntrleaks:
64 unittest.BaseTestSuite._cleanup = False
65
Victor Stinner234cbef2015-09-30 01:13:53 +020066 if ns.memlimit is not None:
67 support.set_memlimit(ns.memlimit)
68
69 if ns.threshold is not None:
70 gc.set_threshold(ns.threshold)
71
Steve Dower9ddc4162019-05-29 08:20:35 -070072 suppress_msvcrt_asserts(ns.verbose and ns.verbose >= 2)
Victor Stinner234cbef2015-09-30 01:13:53 +020073
Victor Stinnera2045022015-09-30 02:17:28 +020074 support.use_resources = ns.use_resources
75
Steve Dowerb82e17e2019-05-23 08:45:22 -070076 if hasattr(sys, 'addaudithook'):
77 # Add an auditing hook for all tests to ensure PySys_Audit is tested
78 def _test_audit_hook(name, args):
79 pass
80 sys.addaudithook(_test_audit_hook)
81
Victor Stinner95f61c82019-06-13 01:09:04 +020082 setup_unraisable_hook()
83
Victor Stinner234cbef2015-09-30 01:13:53 +020084
Steve Dower9ddc4162019-05-29 08:20:35 -070085def suppress_msvcrt_asserts(verbose):
86 try:
87 import msvcrt
88 except ImportError:
89 return
90
91 msvcrt.SetErrorMode(msvcrt.SEM_FAILCRITICALERRORS|
92 msvcrt.SEM_NOALIGNMENTFAULTEXCEPT|
93 msvcrt.SEM_NOGPFAULTERRORBOX|
94 msvcrt.SEM_NOOPENFILEERRORBOX)
95 try:
96 msvcrt.CrtSetReportMode
97 except AttributeError:
98 # release build
99 return
100
101 for m in [msvcrt.CRT_WARN, msvcrt.CRT_ERROR, msvcrt.CRT_ASSERT]:
102 if verbose:
103 msvcrt.CrtSetReportMode(m, msvcrt.CRTDBG_MODE_FILE)
104 msvcrt.CrtSetReportFile(m, msvcrt.CRTDBG_FILE_STDERR)
105 else:
106 msvcrt.CrtSetReportMode(m, 0)
107
108
109
Victor Stinner234cbef2015-09-30 01:13:53 +0200110def replace_stdout():
111 """Set stdout encoder error handler to backslashreplace (as stderr error
112 handler) to avoid UnicodeEncodeError when printing a traceback"""
113 stdout = sys.stdout
Victor Stinnerccef8232017-10-13 12:59:12 -0700114 try:
115 fd = stdout.fileno()
116 except ValueError:
117 # On IDLE, sys.stdout has no file descriptor and is not a TextIOWrapper
118 # object. Leaving sys.stdout unchanged.
119 #
120 # Catch ValueError to catch io.UnsupportedOperation on TextIOBase
121 # and ValueError on a closed stream.
122 return
123
124 sys.stdout = open(fd, 'w',
Victor Stinner234cbef2015-09-30 01:13:53 +0200125 encoding=stdout.encoding,
126 errors="backslashreplace",
127 closefd=False,
128 newline='\n')
129
130 def restore_stdout():
131 sys.stdout.close()
132 sys.stdout = stdout
133 atexit.register(restore_stdout)