File size: 1,948 Bytes
a9e27c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""Slow-test stack snapshots without the native faulthandler watchdog."""

import os
import sys
import threading
import traceback
from collections.abc import Generator
from contextlib import contextmanager
from typing import TextIO

import pytest

_output = pytest.StashKey[TextIO]()


@contextmanager
def dump_threads_after(
    timeout: float, output: TextIO, test_name: str
) -> Generator[None]:
    def dump() -> None:
        print(f"Test still running after {timeout:g}s: {test_name}", file=output)
        for thread_id, frame in sys._current_frames().items():
            print(f"\nThread {thread_id}:", file=output)
            traceback.print_stack(frame, file=output)
        output.flush()

    timer = threading.Timer(timeout, dump)
    timer.name = "fcc-test-diagnostics"
    timer.daemon = True
    timer.start()
    try:
        yield
    finally:
        timer.cancel()
        timer.join()


def pytest_addoption(parser) -> None:
    parser.addini("thread_dump_timeout", "Print slow-test thread stacks", default="0")


def pytest_configure(config: pytest.Config) -> None:
    if float(config.getini("thread_dump_timeout")) > 0:
        # Windows xdist workers preserve stderr here and redirect descriptor 2 to NUL.
        # Keep a stable output descriptor across pytest's per-test capture changes.
        config.stash[_output] = os.fdopen(
            os.dup(sys.stderr.fileno()),
            "w",
            encoding="utf-8",
            errors="backslashreplace",
        )


def pytest_unconfigure(config: pytest.Config) -> None:
    if _output in config.stash:
        config.stash[_output].close()
        del config.stash[_output]


@pytest.hookimpl(wrapper=True)
def pytest_runtest_protocol(item: pytest.Item):
    timeout = float(item.config.getini("thread_dump_timeout"))
    if timeout <= 0:
        return (yield)
    with dump_threads_after(timeout, item.config.stash[_output], item.nodeid):
        return (yield)