blob: bf899a9e4d4ac1a042f64968f9e34a1e0bcfc457 [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
13from test.libregrtest.refleak import warm_caches
14
15
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)
Victor Stinner234cbef2015-09-30 01:13:53 +020060 if hasattr(module, '__file__'):
61 module.__file__ = os.path.abspath(module.__file__)
62
63 # MacOSX (a.k.a. Darwin) has a default stack size that is too small
64 # for deeply recursive regular expressions. We see this as crashes in
65 # the Python test suite when running test_re.py and test_sre.py. The
66 # fix is to set the stack limit to 2048.
67 # This approach may also be useful for other Unixy platforms that
68 # suffer from small default stack limits.
69 if sys.platform == 'darwin':
70 try:
71 import resource
72 except ImportError:
73 pass
74 else:
75 soft, hard = resource.getrlimit(resource.RLIMIT_STACK)
76 newsoft = min(hard, max(soft, 1024*2048))
77 resource.setrlimit(resource.RLIMIT_STACK, (newsoft, hard))
78
79 if ns.huntrleaks:
80 unittest.BaseTestSuite._cleanup = False
81
82 # Avoid false positives due to various caches
83 # filling slowly with random data:
84 warm_caches()
85
86 if ns.memlimit is not None:
87 support.set_memlimit(ns.memlimit)
88
89 if ns.threshold is not None:
90 gc.set_threshold(ns.threshold)
91
Steve Dower12c29452015-10-08 09:05:36 -070092 try:
Victor Stinner234cbef2015-09-30 01:13:53 +020093 import msvcrt
Steve Dower12c29452015-10-08 09:05:36 -070094 except ImportError:
95 pass
96 else:
Victor Stinner234cbef2015-09-30 01:13:53 +020097 msvcrt.SetErrorMode(msvcrt.SEM_FAILCRITICALERRORS|
98 msvcrt.SEM_NOALIGNMENTFAULTEXCEPT|
99 msvcrt.SEM_NOGPFAULTERRORBOX|
100 msvcrt.SEM_NOOPENFILEERRORBOX)
101 try:
102 msvcrt.CrtSetReportMode
103 except AttributeError:
104 # release build
105 pass
106 else:
107 for m in [msvcrt.CRT_WARN, msvcrt.CRT_ERROR, msvcrt.CRT_ASSERT]:
Steve Dower12c29452015-10-08 09:05:36 -0700108 if ns.verbose and ns.verbose >= 2:
109 msvcrt.CrtSetReportMode(m, msvcrt.CRTDBG_MODE_FILE)
110 msvcrt.CrtSetReportFile(m, msvcrt.CRTDBG_FILE_STDERR)
111 else:
112 msvcrt.CrtSetReportMode(m, 0)
Victor Stinner234cbef2015-09-30 01:13:53 +0200113
Victor Stinnera2045022015-09-30 02:17:28 +0200114 support.use_resources = ns.use_resources
115
Victor Stinner234cbef2015-09-30 01:13:53 +0200116
117def replace_stdout():
118 """Set stdout encoder error handler to backslashreplace (as stderr error
119 handler) to avoid UnicodeEncodeError when printing a traceback"""
120 stdout = sys.stdout
Victor Stinnerccef8232017-10-13 12:59:12 -0700121 try:
122 fd = stdout.fileno()
123 except ValueError:
124 # On IDLE, sys.stdout has no file descriptor and is not a TextIOWrapper
125 # object. Leaving sys.stdout unchanged.
126 #
127 # Catch ValueError to catch io.UnsupportedOperation on TextIOBase
128 # and ValueError on a closed stream.
129 return
130
131 sys.stdout = open(fd, 'w',
Victor Stinner234cbef2015-09-30 01:13:53 +0200132 encoding=stdout.encoding,
133 errors="backslashreplace",
134 closefd=False,
135 newline='\n')
136
137 def restore_stdout():
138 sys.stdout.close()
139 sys.stdout = stdout
140 atexit.register(restore_stdout)