Debian Codegraph @

src/_pytest/faulthandler.py

raw
1 from __future__ import annotations
2
3 from collections.abc import Generator
4 import os
5 import sys
6
7 from _pytest.config import Config
8 from _pytest.config.argparsing import Parser
9 from _pytest.nodes import Item
10 from _pytest.stash import StashKey
11 import pytest
12
13
14 fault_handler_original_stderr_fd_key = StashKey[int]()
15 fault_handler_stderr_fd_key = StashKey[int]()
16
17
18 def pytest_addoption(parser: Parser) -> None:
19 help_timeout = (
20 "Dump the traceback of all threads if a test takes "
21 "more than TIMEOUT seconds to finish"
22 )
23 help_exit_on_timeout = (
24 "Exit the test process if a test takes more than "
25 "faulthandler_timeout seconds to finish"
26 )
27 parser.addini("faulthandler_timeout", help_timeout, default=0.0)
28 parser.addini(
29 "faulthandler_exit_on_timeout", help_exit_on_timeout, type="bool", default=False
30 )
31
32
33 def pytest_configure(config: Config) -> None:
34 import faulthandler
35
36 # at teardown we want to restore the original faulthandler fileno
37 # but faulthandler has no api to return the original fileno
38 # so here we stash the stderr fileno to be used at teardown
39 # sys.stderr and sys.__stderr__ may be closed or patched during the session
40 # so we can't rely on their values being good at that point (#11572).
41 stderr_fileno = get_stderr_fileno()
42 if faulthandler.is_enabled():
43 config.stash[fault_handler_original_stderr_fd_key] = stderr_fileno
44 config.stash[fault_handler_stderr_fd_key] = os.dup(stderr_fileno)
45 faulthandler.enable(file=config.stash[fault_handler_stderr_fd_key])
46
47
48 def pytest_unconfigure(config: Config) -> None:
49 import faulthandler
50
51 faulthandler.disable()
52 # Close the dup file installed during pytest_configure.
53 if fault_handler_stderr_fd_key in config.stash:
54 os.close(config.stash[fault_handler_stderr_fd_key])
55 del config.stash[fault_handler_stderr_fd_key]
56 # Re-enable the faulthandler if it was originally enabled.
57 if fault_handler_original_stderr_fd_key in config.stash:
58 faulthandler.enable(config.stash[fault_handler_original_stderr_fd_key])
59 del config.stash[fault_handler_original_stderr_fd_key]
60
61
62 def get_stderr_fileno() -> int:
63 try:
64 fileno = sys.stderr.fileno()
65 # The Twisted Logger will return an invalid file descriptor since it is not backed
66 # by an FD. So, let's also forward this to the same code path as with pytest-xdist.
67 if fileno == -1:
68 raise AttributeError()
69 return fileno
70 except (AttributeError, ValueError):
71 # pytest-xdist monkeypatches sys.stderr with an object that is not an actual file.
72 # https://docs.python.org/3/library/faulthandler.html#issue-with-file-descriptors
73 # This is potentially dangerous, but the best we can do.
74 assert sys.__stderr__ is not None
75 return sys.__stderr__.fileno()
76
77
78 def get_timeout_config_value(config: Config) -> float:
79 return float(config.getini("faulthandler_timeout") or 0.0)
80
81
82 def get_exit_on_timeout_config_value(config: Config) -> bool:
83 exit_on_timeout = config.getini("faulthandler_exit_on_timeout")
84 assert isinstance(exit_on_timeout, bool)
85 return exit_on_timeout
86
87
88 @pytest.hookimpl(wrapper=True, trylast=True)
89 def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]:
90 timeout = get_timeout_config_value(item.config)
91 exit_on_timeout = get_exit_on_timeout_config_value(item.config)
92 if timeout > 0:
93 import faulthandler
94
95 stderr = item.config.stash[fault_handler_stderr_fd_key]
96 faulthandler.dump_traceback_later(timeout, file=stderr, exit=exit_on_timeout)
97 try:
98 return (yield)
99 finally:
100 faulthandler.cancel_dump_traceback_later()
101 else:
102 return (yield)
103
104
105 @pytest.hookimpl(tryfirst=True)
106 def pytest_enter_pdb() -> None:
107 """Cancel any traceback dumping due to timeout before entering pdb."""
108 import faulthandler
109
110 faulthandler.cancel_dump_traceback_later()
111
112
113 @pytest.hookimpl(tryfirst=True)
114 def pytest_exception_interact() -> None:
115 """Cancel any traceback dumping due to an interactive exception being
116 raised."""
117 import faulthandler
118
119 faulthandler.cancel_dump_traceback_later()