Debian Codegraph @

testing/test_faulthandler.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 import io
5 import os
6 import sys
7
8 from _pytest.pytester import Pytester
9 import pytest
10
11
12 def test_enabled(pytester: Pytester) -> None:
13 """Test single crashing test displays a traceback."""
14 pytester.makepyfile(
15 """
16 import faulthandler
17 def test_crash():
18 faulthandler._sigabrt()
19 """
20 )
21 result = pytester.runpytest_subprocess()
22 result.stderr.fnmatch_lines(["*Fatal Python error*"])
23 assert result.ret != 0
24
25
26 def setup_crashing_test(pytester: Pytester) -> None:
27 pytester.makepyfile(
28 """
29 import faulthandler
30 import atexit
31 def test_ok():
32 atexit.register(faulthandler._sigabrt)
33 """
34 )
35
36
37 def test_crash_during_shutdown_captured(pytester: Pytester) -> None:
38 """
39 Re-enable faulthandler if pytest encountered it enabled during configure.
40 We should be able to then see crashes during interpreter shutdown.
41 """
42 setup_crashing_test(pytester)
43 args = (sys.executable, "-Xfaulthandler", "-mpytest")
44 result = pytester.run(*args)
45 result.stderr.fnmatch_lines(["*Fatal Python error*"])
46 assert result.ret != 0
47
48
49 def test_crash_during_shutdown_not_captured(pytester: Pytester) -> None:
50 """
51 Check that pytest leaves faulthandler disabled if it was not enabled during configure.
52 This prevents us from seeing crashes during interpreter shutdown (see #8260).
53 """
54 setup_crashing_test(pytester)
55 args = (sys.executable, "-mpytest")
56 result = pytester.run(*args)
57 result.stderr.no_fnmatch_line("*Fatal Python error*")
58 assert result.ret != 0
59
60
61 def test_disabled(pytester: Pytester) -> None:
62 """Test option to disable fault handler in the command line."""
63 pytester.makepyfile(
64 """
65 import faulthandler
66 def test_disabled():
67 assert not faulthandler.is_enabled()
68 """
69 )
70 result = pytester.runpytest_subprocess("-p", "no:faulthandler")
71 result.stdout.fnmatch_lines(["*1 passed*"])
72 assert result.ret == 0
73
74
75 @pytest.mark.keep_ci_var
76 @pytest.mark.parametrize(
77 "enabled",
78 [
79 pytest.param(
80 True,
81 marks=pytest.mark.skipif(
82 bool(os.environ.get("CI"))
83 and sys.platform == "linux"
84 and sys.version_info >= (3, 14),
85 reason="sometimes crashes on CI because of truncated outputs (#7022)",
86 ),
87 ),
88 False,
89 ],
90 )
91 def test_timeout(pytester: Pytester, enabled: bool) -> None:
92 """Test option to dump tracebacks after a certain timeout.
93
94 If faulthandler is disabled, no traceback will be dumped.
95 """
96 pytester.makepyfile(
97 """
98 import os, time
99 def test_timeout():
100 time.sleep(1 if "CI" in os.environ else 0.1)
101 """
102 )
103 pytester.makeini(
104 """
105 [pytest]
106 faulthandler_timeout = 0.01
107 """
108 )
109 args = ["-p", "no:faulthandler"] if not enabled else []
110
111 result = pytester.runpytest_subprocess(*args)
112 tb_output = "most recent call first"
113 if enabled:
114 result.stderr.fnmatch_lines([f"*{tb_output}*"])
115 else:
116 assert tb_output not in result.stderr.str()
117 result.stdout.fnmatch_lines(["*1 passed*"])
118 assert result.ret == 0
119
120
121 @pytest.mark.keep_ci_var
122 @pytest.mark.skipif(
123 "CI" in os.environ and sys.platform == "linux" and sys.version_info >= (3, 14),
124 reason="sometimes crashes on CI because of truncated outputs (#7022)",
125 )
126 @pytest.mark.parametrize("exit_on_timeout", [True, False])
127 def test_timeout_and_exit(pytester: Pytester, exit_on_timeout: bool) -> None:
128 """Test option to force exit pytest process after a certain timeout."""
129 pytester.makepyfile(
130 """
131 import os, time
132 def test_long_sleep_and_raise():
133 time.sleep(1 if "CI" in os.environ else 0.1)
134 raise AssertionError(
135 "This test should have been interrupted before reaching this point."
136 )
137 """
138 )
139 pytester.makeini(
140 f"""
141 [pytest]
142 faulthandler_timeout = 0.01
143 faulthandler_exit_on_timeout = {"true" if exit_on_timeout else "false"}
144 """
145 )
146 result = pytester.runpytest_subprocess()
147 tb_output = "most recent call first"
148 result.stderr.fnmatch_lines([f"*{tb_output}*"])
149 if exit_on_timeout:
150 result.stdout.no_fnmatch_line("*1 failed*")
151 result.stdout.no_fnmatch_line("*AssertionError*")
152 else:
153 result.stdout.fnmatch_lines(["*1 failed*"])
154 result.stdout.fnmatch_lines(["*AssertionError*"])
155 assert result.ret == 1
156
157
158 @pytest.mark.parametrize("hook_name", ["pytest_enter_pdb", "pytest_exception_interact"])
159 def test_cancel_timeout_on_hook(monkeypatch, hook_name) -> None:
160 """Make sure that we are cancelling any scheduled traceback dumping due
161 to timeout before entering pdb (pytest-dev/pytest-faulthandler#12) or any
162 other interactive exception (pytest-dev/pytest-faulthandler#14)."""
163 import faulthandler
164
165 from _pytest import faulthandler as faulthandler_plugin
166
167 called = []
168
169 monkeypatch.setattr(
170 faulthandler, "cancel_dump_traceback_later", lambda: called.append(1)
171 )
172
173 # call our hook explicitly, we can trust that pytest will call the hook
174 # for us at the appropriate moment
175 hook_func = getattr(faulthandler_plugin, hook_name)
176 hook_func()
177 assert called == [1]
178
179
180 def test_already_initialized_crash(pytester: Pytester) -> None:
181 """Even if faulthandler is already initialized, we still dump tracebacks on crashes (#8258)."""
182 pytester.makepyfile(
183 """
184 def test():
185 import faulthandler
186 faulthandler._sigabrt()
187 """
188 )
189 result = pytester.run(
190 sys.executable,
191 "-X",
192 "faulthandler",
193 "-mpytest",
194 pytester.path,
195 )
196 result.stderr.fnmatch_lines(["*Fatal Python error*"])
197 assert result.ret != 0
198
199
200 def test_get_stderr_fileno_invalid_fd() -> None:
201 """Test for faulthandler being able to handle invalid file descriptors for stderr (#8249)."""
202 from _pytest.faulthandler import get_stderr_fileno
203
204 class StdErrWrapper(io.StringIO):
205 """
206 Mimic ``twisted.logger.LoggingFile`` to simulate returning an invalid file descriptor.
207
208 https://github.com/twisted/twisted/blob/twisted-20.3.0/src/twisted/logger/_io.py#L132-L139
209 """
210
211 def fileno(self):
212 return -1
213
214 wrapper = StdErrWrapper()
215
216 with pytest.MonkeyPatch.context() as mp:
217 mp.setattr("sys.stderr", wrapper)
218
219 # Even when the stderr wrapper signals an invalid file descriptor,
220 # ``_get_stderr_fileno()`` should return the real one.
221 assert get_stderr_fileno() == 2