Skip to content

Abort async test if event loop catched unhandled exception #223

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
HMaker opened this issue Aug 4, 2021 · 1 comment
Closed

Abort async test if event loop catched unhandled exception #223

HMaker opened this issue Aug 4, 2021 · 1 comment

Comments

@HMaker
Copy link

HMaker commented Aug 4, 2021

Hi. Sometimes async tests hangs when background tasks raises some exception but it's not propagated to test function, it's not a bug in pytest-asyncio but a problem in application code. Can the following patch be used to abort current test if some exception is raised in background?

import inspect as _inspect
import asyncio as _asyncio
from functools import wraps as _wraps
from pytest_asyncio import plugin as _pytestasyncio_plugin

def _wrap_in_sync(func, _loop):
    """Return a sync wrapper around an async function executing it in the
    current event loop."""
    @_wraps(func)
    def inner(**kwargs):
        coro = func(**kwargs)
        if coro is not None:
            def forward_exception(loop, context):
                if _inspect.getcoroutinestate(coro) != _inspect.CORO_CLOSED:
                    coro.throw(context['exception'] if 'exception' in context else Exception(context['message']))
                else:
                    loop.default_exception_handler(context)
            _loop.set_exception_handler(forward_exception)
            task = _asyncio.ensure_future(coro, loop=_loop)
            try:
                _loop.run_until_complete(task)
            except BaseException:
                # run_until_complete doesn't get the result from exceptions
                # that are not subclasses of `Exception`. Consume all
                # exceptions to prevent asyncio's warning from logging.
                if task.done() and not task.cancelled():
                    task.exception()
                raise
    return inner
_pytestasyncio_plugin.wrap_in_sync = _wrap_in_sync
@seifertm
Copy link
Contributor

My understanding is that you want exceptions in (background) tasks to raise an error rather than letting the test succeed silently.

In this case, I'll close this issue as a duplicate of #205.

Feel free to comment or reopen, if I misunderstood your intention.

@seifertm seifertm closed this as not planned Won't fix, can't repro, duplicate, stale Nov 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants