| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import collections |
| 4 |
from collections.abc import Callable |
| 5 |
import functools |
| 6 |
import sys |
| 7 |
import threading |
| 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 |
class ThreadExceptionMeta(NamedTuple): |
| 28 |
msg: str |
| 29 |
cause_msg: str |
| 30 |
exc_value: BaseException | None |
| 31 |
|
| 32 |
|
| 33 |
thread_exceptions: StashKey[collections.deque[ThreadExceptionMeta | BaseException]] = ( |
| 34 |
StashKey() |
| 35 |
) |
| 36 |
|
| 37 |
|
| 38 |
def collect_thread_exception(config: Config) -> None: |
| 39 |
pop_thread_exception = config.stash[thread_exceptions].pop |
| 40 |
errors: list[pytest.PytestUnhandledThreadExceptionWarning | RuntimeError] = [] |
| 41 |
meta = None |
| 42 |
hook_error = None |
| 43 |
try: |
| 44 |
while True: |
| 45 |
try: |
| 46 |
meta = pop_thread_exception() |
| 47 |
except IndexError: |
| 48 |
break |
| 49 |
|
| 50 |
if isinstance(meta, BaseException): |
| 51 |
hook_error = RuntimeError("Failed to process thread exception") |
| 52 |
hook_error.__cause__ = meta |
| 53 |
errors.append(hook_error) |
| 54 |
continue |
| 55 |
|
| 56 |
msg = meta.msg |
| 57 |
try: |
| 58 |
warnings.warn(pytest.PytestUnhandledThreadExceptionWarning(msg)) |
| 59 |
except pytest.PytestUnhandledThreadExceptionWarning as e: |
| 60 |
# This except happens when the warning is treated as an error (e.g. `-Werror`). |
| 61 |
if meta.exc_value is not None: |
| 62 |
# Exceptions have a better way to show the traceback, but |
| 63 |
# warnings do not, so hide the traceback from the msg and |
| 64 |
# set the cause so the traceback shows up in the right place. |
| 65 |
e.args = (meta.cause_msg,) |
| 66 |
e.__cause__ = meta.exc_value |
| 67 |
errors.append(e) |
| 68 |
|
| 69 |
if len(errors) == 1: |
| 70 |
raise errors[0] |
| 71 |
if errors: |
| 72 |
raise ExceptionGroup("multiple thread exception warnings", errors) |
| 73 |
finally: |
| 74 |
del errors, meta, hook_error |
| 75 |
|
| 76 |
|
| 77 |
def cleanup( |
| 78 |
*, config: Config, prev_hook: Callable[[threading.ExceptHookArgs], object] |
| 79 |
) -> None: |
| 80 |
try: |
| 81 |
try: |
| 82 |
# We don't join threads here, so exceptions raised from any |
| 83 |
# threads still running by the time _threading_atexits joins them |
| 84 |
# do not get captured (see #13027). |
| 85 |
collect_thread_exception(config) |
| 86 |
finally: |
| 87 |
threading.excepthook = prev_hook |
| 88 |
finally: |
| 89 |
del config.stash[thread_exceptions] |
| 90 |
|
| 91 |
|
| 92 |
def thread_exception_hook( |
| 93 |
args: threading.ExceptHookArgs, |
| 94 |
/, |
| 95 |
*, |
| 96 |
append: Callable[[ThreadExceptionMeta | BaseException], object], |
| 97 |
) -> None: |
| 98 |
try: |
| 99 |
# we need to compute these strings here as they might change after |
| 100 |
# the excepthook finishes and before the metadata object is |
| 101 |
# collected by a pytest hook |
| 102 |
thread_name = "<unknown>" if args.thread is None else args.thread.name |
| 103 |
summary = f"Exception in thread {thread_name}" |
| 104 |
traceback_message = "\n\n" + "".join( |
| 105 |
traceback.format_exception( |
| 106 |
args.exc_type, |
| 107 |
args.exc_value, |
| 108 |
args.exc_traceback, |
| 109 |
) |
| 110 |
) |
| 111 |
tracemalloc_tb = "\n" + tracemalloc_message(args.thread) |
| 112 |
msg = summary + traceback_message + tracemalloc_tb |
| 113 |
cause_msg = summary + tracemalloc_tb |
| 114 |
|
| 115 |
append( |
| 116 |
ThreadExceptionMeta( |
| 117 |
# Compute these strings here as they might change later |
| 118 |
msg=msg, |
| 119 |
cause_msg=cause_msg, |
| 120 |
exc_value=args.exc_value, |
| 121 |
) |
| 122 |
) |
| 123 |
except BaseException as e: |
| 124 |
append(e) |
| 125 |
# Raising this will cause the exception to be logged twice, once in our |
| 126 |
# collect_thread_exception and once by sys.excepthook |
| 127 |
# which is fine - this should never happen anyway and if it does |
| 128 |
# it should probably be reported as a pytest bug. |
| 129 |
raise |
| 130 |
|
| 131 |
|
| 132 |
def pytest_configure(config: Config) -> None: |
| 133 |
prev_hook = threading.excepthook |
| 134 |
deque: collections.deque[ThreadExceptionMeta | BaseException] = collections.deque() |
| 135 |
config.stash[thread_exceptions] = deque |
| 136 |
config.add_cleanup(functools.partial(cleanup, config=config, prev_hook=prev_hook)) |
| 137 |
threading.excepthook = functools.partial(thread_exception_hook, append=deque.append) |
| 138 |
|
| 139 |
|
| 140 |
@pytest.hookimpl(trylast=True) |
| 141 |
def pytest_runtest_setup(item: Item) -> None: |
| 142 |
collect_thread_exception(item.config) |
| 143 |
|
| 144 |
|
| 145 |
@pytest.hookimpl(trylast=True) |
| 146 |
def pytest_runtest_call(item: Item) -> None: |
| 147 |
collect_thread_exception(item.config) |
| 148 |
|
| 149 |
|
| 150 |
@pytest.hookimpl(trylast=True) |
| 151 |
def pytest_runtest_teardown(item: Item) -> None: |
| 152 |
collect_thread_exception(item.config) |