Kumar Gaurav
Kumar Gaurav

Reputation: 21

Testing async context manager fixture in pytest yields unexpected async generator object

This is somewhat related to my actuall code, Async context manager class used in pytest fixture returns async generator object instead of the expected context manager instance. Need help resolving this issue.

This is my code

 import asyncio

 class MyAsyncContextManager:
    async def __aenter__(self):
        print("Entering async context")
        return self

    async def __aexit__(self, exc_type, exc, tb):
        print("Exiting async context")

    def add_numbers(self, a, b):
        return a + b
    
 @pytest.fixture
 async def async_context_manager():
    async with MyAsyncContextManager() as manager:
        yield manager

 @pytest.mark.asyncio
 async def test_async_context_manager(async_context_manager):
    async_context_manager.add_numbers(1, 2)

This is the error i am getting

> async_context_manager.add_numbers(1, 2)
AttributeError: 'async_generator' object has no attribute 'add_numbers'

so basically fixure is giving me async_generator not the instance of MyAsyncContextManager

Upvotes: 2

Views: 347

Answers (1)

Andrew Certain
Andrew Certain

Reputation: 63

Async fixtures in pytest need to be marked with @pytest_asyncio.fixture so that they get awaited before passing to the test. The error message tells you that you're getting a coroutine passed into your test method rather than the results of the coroutine being executed.

Upvotes: 0

Related Questions