Test async fixture setup and usage with pytest-asyncio
Preconditions (2)
✅ Expected Result: The test runs successfully using the async fixture without errors
Jump into concepts and practice - no test required
import pytest import pytest_asyncio @pytest_asyncio.fixture async def async_resource(): # Simulate async setup await asyncio.sleep(0.1) return 'resource_ready' @pytest.mark.asyncio async def test_async_fixture_usage(async_resource): assert async_resource == 'resource_ready'
The code defines an async fixture async_resource using @pytest_asyncio.fixture. It simulates asynchronous setup by awaiting asyncio.sleep(0.1) and then returns a string.
The test function test_async_fixture_usage is marked with @pytest.mark.asyncio to allow async execution. It receives the fixture as a parameter and asserts the returned value is as expected.
This setup ensures the fixture is awaited properly and the test runs asynchronously without blocking.
Now add data-driven testing with 3 different async fixture setups returning different strings
async def in pytest fixtures with pytest-asyncio?async def allows the fixture to run asynchronous code, which is necessary for async setup or cleanup tasks.async def in fixtures.async def and use yield to allow setup and cleanup.async def and yield. def my_fixture(): yield 'data' is synchronous. async def my_fixture(): return 'data' uses return which does not support cleanup. def my_fixture(): return 'data' is synchronous and uses return.import pytest
import asyncio
@pytest.fixture
async def async_resource():
print('Setup')
yield 'resource'
print('Cleanup')
@pytest.mark.asyncio
def test_example(async_resource):
print(f'Test using {async_resource}')
import pytest
@pytest.fixture
async def resource():
data = await get_data()
return data
get_data() is an async function.yield to separate setup and teardown phases.return, so it cannot perform cleanup after the test. Using yield is required for cleanup.@pytest.fixture and defined as async def to support async setup and cleanup.open_db(), yields the connection, and awaits conn.close() after the test. async def db_conn():
conn = await open_db()
yield conn
await conn.close() misses the decorator. @pytest.fixture
async def db_conn():
conn = open_db()
yield conn
conn.close() misses awaits. @pytest.fixture
async def db_conn():
conn = await open_db()
return conn uses return, so no cleanup.