pytest-asyncio icon indicating copy to clipboard operation
pytest-asyncio copied to clipboard

request.instance is None in async tests

Open JonathanMeans opened this issue 4 years ago • 4 comments

This test passes with version 0.10.0:

Pipfile:

[packages]
pytest-asyncio = "==0.10.0"
pytest = "==5.4.3"

test_request.py:

import pytest


class TestFixture:
    @pytest.mark.asyncio
    async def test_fixture(self, request):
        assert request.instance is not None

Under 0.11.0 (and higher), it fails:

Pipfile:

[packages]
pytest-asyncio = "==0.14.0"
pytest = "==5.4.3"

I don't fully understand everything that's going on with event loops behind the scenes, but I guess I'd expect the behavior to remain the same

JonathanMeans avatar Feb 16 '21 17:02 JonathanMeans

Thanks for the bug report and for narrowing down the issue to different pytest-asyncio versions!

We're currently trying to get an understand what issues are still relevant and which of them are obsolete. I just re-tested your example and the issue persists with pytest-asyncio-0.16. The following code gives an error:

import pytest

@pytest.mark.asyncio
async def test_fixture(request):
    assert request.instance is not None

>       assert request.instance is not None
E       assert None is not None
E        +  where None = <FixtureRequest for <Function test_fixture>>.instance

whereas the same code without the asyncio mark is successful:

def test_fixture(request):
    assert request.instance is not None

This seems to be a bug and it's still relevant.

seifertm avatar Jan 07 '22 16:01 seifertm

The issue is reproducible in v0.19.0.

seifertm avatar Sep 18 '22 17:09 seifertm

The culprit seems to be the implementation of pytest_pycollect_makeitem. The function injects the event_loop and request dependencies into async fixture definitions.

The pytest_pycollect_makeitem hook calls _preprocess_async_fixtures which essentially reimplements part of pytest's FixtureManager to inject the request and event_loop argnames into async fixtures. Apparently it fails to do so correctly in some cases like the one mentioned in this issue.

seifertm avatar Sep 25 '22 08:09 seifertm