Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/testing/test_faulthandler.py

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