pytest-dev/pytest-asyncio

Allow the asyncio_event_loop mark to be applied to test coroutines

seifertm opened this issue · 2 comments

#620 introduced the asyncio_event_loop mark, which provides a class-scoped or module-scoped event loop when a class or module is marked, respectively. The mark optionally allows specifying one or more event loop policies used to create the scoped event loop. This functionality is intended to supersede the practice of overriding the event_loop fixture.

#631 deprecated event_loop fixture overrides, but there's no replacement for custom loop policies with function-scoped loops, for example:

@pytest.fixture(
    params=[
        DefaultEventLoopPolicy(),
        CustomEventLoopPolicy(),
    ]
)
def event_loop(request):
    policy = request.param
    loop = policy.new_event_loop()
    yield loop
    
async def test_should_run_twice():
    pass

Therefore, the asyncio_event_loop mark should be adjusted to allow its application to test functions, for example:

@pytest.mark.asyncio_event_loop(
    policy=[
        DefaultEventLoopPolicy(),
        CustomEventLoopPolicy(),
    ]
)
async def test_should_run_twice():
    pass

My first try at implementing this didn't succeed.

The setup of asyncio_event_loop needs to happen before pytest_generate_tests. For classes and modules this is done in pytest_collectstart. Unfortunately, this hook doesn't seem to be called for pytest.Function items.

The asyncio_event_loop mark has been abandoned in favour of the scope kwarg to the asyncio mark.
see #657