Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
include MANIFEST.in
include LICENSE
include test_pytest_timeout.py
include test_pytest_timeout_asyncio.py
include failure_demo.py
include tox.ini
12 changes: 12 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@ time. This is useful when running tests under a continuous
integration server or simply if you don't know why the test suite
hangs.

When asyncio is in use, timeout output also includes pending tasks and
their suspended coroutine await chains, including tasks in event loops
running in background threads. This works with both timeout methods
without additional configuration. Task inspection runs without asking
the event loops to execute callbacks, so it can also diagnose a blocked
event loop. Inspection is best effort because tasks may advance while
their stacks are collected. Frame locals are not included. Task types
that do not derive from ``asyncio.Task`` and other async runtimes are
not supported.

.. note::

While by default on POSIX systems pytest will continue to execute
Expand Down Expand Up @@ -395,6 +405,8 @@ Changelog
X.Y.Z
-----

- Include pending asyncio tasks and suspended coroutine await chains in
timeout output for both the signal and thread methods.
- Preserve capture-fixture output and disable fixture capturing when reporting
thread timeouts. Thanks Arham Begani.
- Add support Python3.15. Thanks Vladimir Roshchin.
Expand Down
62 changes: 61 additions & 1 deletion pytest_timeout.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
the test, otherwise os._exit(1) is used.
"""

import gc
import inspect
import os
import signal
Expand Down Expand Up @@ -545,7 +546,7 @@ def timeout_timer(item, settings):


def dump_stacks(terminal):
"""Dump the stacks of all threads except the current thread."""
"""Dump other threads' stacks and pending asyncio coroutine chains."""
current_ident = threading.current_thread().ident
for thread_ident, frame in sys._current_frames().items():
if thread_ident == current_ident:
Expand All @@ -558,3 +559,62 @@ def dump_stacks(terminal):
thread_name = "<unknown>"
terminal.sep("~", title=f"Stack of {thread_name} ({thread_ident})")
terminal.write("".join(traceback.format_stack(frame)))
_dump_asyncio_stacks(terminal)


def _dump_asyncio_stacks(terminal):
"""Inspect tasks across event loops without needing those loops to respond."""
# Avoid importing asyncio in test runs that do not use it.
asyncio = sys.modules.get("asyncio")
if asyncio is None or not hasattr(asyncio, "Task"):
return
try:
# Discover tasks in all threads without a private task registry. Check
# the real type to avoid invoking arbitrary __class__ properties.
tasks = [obj for obj in gc.get_objects() if issubclass(type(obj), asyncio.Task)]
tasks = [task for task in tasks if not task.done()]
if not tasks:
return
terminal.sep("~", title="Asyncio task stacks")
for task in tasks:
try:
terminal.write(
f"\nTask: {task.get_name()} (loop {id(task.get_loop()):#x})\n"
)
_dump_await_chain(task.get_coro(), terminal)
except Exception: # noqa: PERF203
# Preserve other tasks' stacks if one task changes or cannot
# be inspected while the test is still running.
terminal.write(traceback.format_exc())
except Exception:
# Task discovery is best effort; diagnostic errors must not replace
# the original timeout failure.
terminal.write("Unable to collect asyncio task stacks:\n")
terminal.write(traceback.format_exc())


def _dump_await_chain(current, terminal):
seen = set()
for _ in range(50):
if current is None:
return
if id(current) in seen:
terminal.write(" <cycle in coroutine chain>\n")
return
seen.add(id(current))
frame = (
getattr(current, "cr_frame", None)
or getattr(current, "gi_frame", None)
or getattr(current, "ag_frame", None)
)
if frame is not None:
terminal.write("".join(traceback.format_stack(frame, limit=1)))
else:
terminal.write(f" <{type(current).__name__}>\n")
current = (
getattr(current, "cr_await", None)
or getattr(current, "gi_yieldfrom", None)
or getattr(current, "ag_await", None)
)
if current is not None:
terminal.write(" <coroutine chain truncated after 50 frames>\n")
220 changes: 220 additions & 0 deletions test_pytest_timeout_asyncio.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
import asyncio
import gc
import io
import signal
import sys
from types import SimpleNamespace

import pytest
from _pytest._io import TerminalWriter

import pytest_timeout

pytest_plugins = "pytester"

timeout_methods = [
"thread",
pytest.param(
"signal",
marks=pytest.mark.skipif(
not hasattr(signal, "SIGALRM"), reason="OS does not have SIGALRM"
),
),
]


@pytest.mark.parametrize("method", timeout_methods)
@pytest.mark.parametrize("blocked_loop", [False, True])
def test_timeout_suspended_asyncio_chains_across_threads(
pytester, method, blocked_loop
):
pytester.makepyfile(
f"""
import asyncio
import gc
import threading
import time
import types

ready = threading.Event()
stop = threading.Event()

async def background_leaf():
ready.set()
while not stop.is_set():
await asyncio.sleep(0.01)

async def background_root():
asyncio.current_task().set_name("background-worker")
await background_leaf()

@types.coroutine
def legacy_wait():
yield from asyncio.Event().wait().__await__()

async def foreground_leaf():
await legacy_wait()

async def foreground_root():
await foreground_leaf()

async def main():
# Keep the task alive while collecting suspended reference cycles.
foreground_task = asyncio.create_task(
foreground_root(), name="foreground-worker"
)
await asyncio.sleep(0)
gc.collect()
if {blocked_loop}:
time.sleep(10)
await foreground_task

def test_hang():
thread = threading.Thread(
target=lambda: asyncio.run(background_root()),
name="background-loop", daemon=True,
)
thread.start()
try:
assert ready.wait(5)
asyncio.run(main())
finally:
stop.set()
thread.join(5)
"""
)

result = pytester.runpytest_subprocess(
"--timeout=1", f"--timeout-method={method}", timeout=20
)

assert result.ret == 1
if method == "signal":
result.assert_outcomes(failed=1)
result.stdout.fnmatch_lines(["*Failed: Timeout (>1.0s) from pytest-timeout.*"])
else:
result.stdout.fnmatch_lines(["*Stack of MainThread*", "*Asyncio task stacks*"])
assert "++ Timeout ++" in result.stdout.lines[-1]
async_stacks = result.stdout.str().split("Asyncio task stacks", 1)[1]
for name in (
"foreground-worker",
"background-worker",
"in foreground_root",
"in foreground_leaf",
"in legacy_wait",
"in background_root",
"in background_leaf",
):
assert name in async_stacks


@pytest.mark.parametrize("method", timeout_methods)
def test_asyncio_inspection_error_preserves_timeout(pytester, method):
pytester.makepyfile(
"""
import asyncio
import gc
import time

def fail_inspection():
raise RuntimeError("task inspection failed")

def test_hang(monkeypatch):
monkeypatch.setattr(gc, "get_objects", fail_inspection)
time.sleep(10)
"""
)

result = pytester.runpytest_subprocess(
"--timeout=1", f"--timeout-method={method}", timeout=20
)

assert result.ret == 1
result.stdout.fnmatch_lines(
[
"*Unable to collect asyncio task stacks:*",
"*RuntimeError: task inspection failed*",
]
)
if method == "signal":
result.assert_outcomes(failed=1)
result.stdout.fnmatch_lines(["*Failed: Timeout (>1.0s) from pytest-timeout.*"])
else:
assert "++ Timeout ++" in result.stdout.lines[-1]


@pytest.mark.parametrize("imported", [False, True])
def test_no_asyncio_tasks_leave_output_unchanged(monkeypatch, imported):
if imported:
monkeypatch.setattr(gc, "get_objects", lambda: [])
else:
monkeypatch.delitem(sys.modules, "asyncio")
stream = io.StringIO()

pytest_timeout._dump_asyncio_stacks(TerminalWriter(file=stream))

assert stream.getvalue() == ""


def test_completed_asyncio_tasks_are_omitted(monkeypatch):
loop = asyncio.new_event_loop()
stream = io.StringIO()

async def finished():
pass

task = loop.create_task(finished(), name="completed-task")
try:
loop.run_until_complete(task)
monkeypatch.setattr(gc, "get_objects", lambda: [task])

pytest_timeout._dump_asyncio_stacks(TerminalWriter(file=stream))

assert stream.getvalue() == ""
finally:
loop.close()


def test_uninspectable_task_preserves_other_tasks(monkeypatch):
class UninspectableTask(asyncio.Task):
def get_coro(self):
raise RuntimeError("cannot inspect coroutine")

async def pending():
await asyncio.Event().wait()

loop = asyncio.new_event_loop()
broken = UninspectableTask(pending(), loop=loop, name="broken-task")
healthy = loop.create_task(pending(), name="healthy-task")
stream = io.StringIO()
try:
monkeypatch.setattr(gc, "get_objects", lambda: [broken, healthy])

pytest_timeout._dump_asyncio_stacks(TerminalWriter(file=stream))

output = stream.getvalue()
assert "RuntimeError: cannot inspect coroutine" in output
assert "healthy-task" in output
assert "in pending" in output
finally:
broken.cancel()
healthy.cancel()
loop.run_until_complete(asyncio.gather(broken, healthy, return_exceptions=True))
loop.close()


@pytest.mark.parametrize("cyclic", [False, True])
def test_await_chain_is_bounded(cyclic):
current = SimpleNamespace()
root = current
for _ in range(60):
current.cr_await = SimpleNamespace()
current = current.cr_await
if cyclic:
root.cr_await = root
stream = io.StringIO()

pytest_timeout._dump_await_chain(root, stream)

expected = "cycle" if cyclic else "truncated after 50 frames"
assert expected in stream.getvalue()
Loading