Debian Codegraph @

src/_pytest/unraisableexception.py

raw
1 from __future__ import annotations
2
3 import collections
4 from collections.abc import Callable
5 import functools
6 import gc
7 import sys
8 import traceback
9 from typing import NamedTuple
10 from typing import TYPE_CHECKING
11 import warnings
12
13 from _pytest.config import Config
14 from _pytest.nodes import Item
15 from _pytest.stash import StashKey
16 from _pytest.tracemalloc import tracemalloc_message
17 import pytest
18
19
20 if TYPE_CHECKING:
21 pass
22
23 if sys.version_info < (3, 11):
24 from exceptiongroup import ExceptionGroup
25
26
27 # This is a stash item and not a simple constant to allow pytester to override it.
28 gc_collect_iterations_key = StashKey[int]()
29
30
31 def gc_collect_harder(iterations: int) -> None:
32 for _ in range(iterations):
33 gc.collect()
34
35
36 class UnraisableMeta(NamedTuple):
37 msg: str
38 cause_msg: str
39 exc_value: BaseException | None
40
41
42 unraisable_exceptions: StashKey[collections.deque[UnraisableMeta | BaseException]] = (
43 StashKey()
44 )
45
46
47 def collect_unraisable(config: Config) -> None:
48 pop_unraisable = config.stash[unraisable_exceptions].pop
49 errors: list[pytest.PytestUnraisableExceptionWarning | RuntimeError] = []
50 meta = None
51 hook_error = None
52 try:
53 while True:
54 try:
55 meta = pop_unraisable()
56 except IndexError:
57 break
58
59 if isinstance(meta, BaseException):
60 hook_error = RuntimeError("Failed to process unraisable exception")
61 hook_error.__cause__ = meta
62 errors.append(hook_error)
63 continue
64
65 msg = meta.msg
66 try:
67 warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))
68 except pytest.PytestUnraisableExceptionWarning as e:
69 # This except happens when the warning is treated as an error (e.g. `-Werror`).
70 if meta.exc_value is not None:
71 # Exceptions have a better way to show the traceback, but
72 # warnings do not, so hide the traceback from the msg and
73 # set the cause so the traceback shows up in the right place.
74 e.args = (meta.cause_msg,)
75 e.__cause__ = meta.exc_value
76 errors.append(e)
77
78 if len(errors) == 1:
79 raise errors[0]
80 if errors:
81 raise ExceptionGroup("multiple unraisable exception warnings", errors)
82 finally:
83 del errors, meta, hook_error
84
85
86 def cleanup(
87 *, config: Config, prev_hook: Callable[[sys.UnraisableHookArgs], object]
88 ) -> None:
89 # On PyPy, objects (e.g. coroutines) can survive GC rounds because executing
90 # their __del__ can resurrect them. The Trio project determined experimentally
91 # that 5 passes are needed on PyPy to flush everything. On CPython, reference
92 # counting handles most cleanup immediately, so 1 pass is sufficient.
93 _default_gc_collect_iterations = 5 if sys.implementation.name == "pypy" else 1
94 gc_collect_iterations = config.stash.get(
95 gc_collect_iterations_key, _default_gc_collect_iterations
96 )
97 try:
98 try:
99 gc_collect_harder(gc_collect_iterations)
100 collect_unraisable(config)
101 finally:
102 sys.unraisablehook = prev_hook
103 finally:
104 del config.stash[unraisable_exceptions]
105
106
107 def unraisable_hook(
108 unraisable: sys.UnraisableHookArgs,
109 /,
110 *,
111 append: Callable[[UnraisableMeta | BaseException], object],
112 ) -> None:
113 try:
114 # we need to compute these strings here as they might change after
115 # the unraisablehook finishes and before the metadata object is
116 # collected by a pytest hook
117 err_msg = (
118 "Exception ignored in" if unraisable.err_msg is None else unraisable.err_msg
119 )
120 summary = f"{err_msg}: {unraisable.object!r}"
121 traceback_message = "\n\n" + "".join(
122 traceback.format_exception(
123 unraisable.exc_type,
124 unraisable.exc_value,
125 unraisable.exc_traceback,
126 )
127 )
128 tracemalloc_tb = "\n" + tracemalloc_message(unraisable.object)
129 msg = summary + traceback_message + tracemalloc_tb
130 cause_msg = summary + tracemalloc_tb
131
132 append(
133 UnraisableMeta(
134 msg=msg,
135 cause_msg=cause_msg,
136 exc_value=unraisable.exc_value,
137 )
138 )
139 except BaseException as e:
140 append(e)
141 # Raising this will cause the exception to be logged twice, once in our
142 # collect_unraisable and once by the unraisablehook calling machinery
143 # which is fine - this should never happen anyway and if it does
144 # it should probably be reported as a pytest bug.
145 raise
146
147
148 def pytest_configure(config: Config) -> None:
149 prev_hook = sys.unraisablehook
150 deque: collections.deque[UnraisableMeta | BaseException] = collections.deque()
151 config.stash[unraisable_exceptions] = deque
152 config.add_cleanup(functools.partial(cleanup, config=config, prev_hook=prev_hook))
153 sys.unraisablehook = functools.partial(unraisable_hook, append=deque.append)
154
155
156 def pytest_unconfigure(config: Config) -> None:
157 # Runs before ``_cleanup_stack.close()``, so warning filters from
158 # cleanup-stack-managed contexts (notably the ``warnings`` plugin's
159 # ``catch_warnings``) are still installed when garbage-collected
160 # finalizers fire. A ``config.add_cleanup`` callback would instead
161 # couple correctness to LIFO pop order across plugins' cleanups.
162 if unraisable_exceptions not in config.stash:
163 # ``pytest_configure`` did not complete (e.g. a usage error raised
164 # in another plugin's configure), so the queue stash was never set.
165 return
166 # PyPy can resurrect objects in __del__, so it needs several GC passes
167 # (5, per the Trio project); CPython frees cycles in one pass. See #14441.
168 _default_gc_collect_iterations = 5 if sys.implementation.name == "pypy" else 1
169 gc_collect_iterations = config.stash.get(
170 gc_collect_iterations_key, _default_gc_collect_iterations
171 )
172 gc_collect_harder(gc_collect_iterations)
173 collect_unraisable(config)
174
175
176 @pytest.hookimpl(trylast=True)
177 def pytest_runtest_setup(item: Item) -> None:
178 collect_unraisable(item.config)
179
180
181 @pytest.hookimpl(trylast=True)
182 def pytest_runtest_call(item: Item) -> None:
183 collect_unraisable(item.config)
184
185
186 @pytest.hookimpl(trylast=True)
187 def pytest_runtest_teardown(item: Item) -> None:
188 collect_unraisable(item.config)