Test Overview
This test uses an async fixture to set up a resource before the test runs. It verifies that the async fixture provides the expected value to the test function.
Jump into concepts and practice - no test required
This test uses an async fixture to set up a resource before the test runs. It verifies that the async fixture provides the expected value to the test function.
import pytest import asyncio @pytest.fixture async def async_resource(): await asyncio.sleep(0.1) # Simulate async setup return "resource_ready" @pytest.mark.asyncio async def test_async_fixture(async_resource): assert async_resource == "resource_ready"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest test runner initialized with pytest-asyncio plugin | — | PASS |
| 2 | pytest discovers test_async_fixture and async_resource fixture | Test and fixture functions loaded | — | PASS |
| 3 | pytest calls async_resource fixture asynchronously | async_resource fixture running, awaiting asyncio.sleep(0.1) | — | PASS |
| 4 | async_resource fixture returns value 'resource_ready' | Fixture setup complete, value ready for test | — | PASS |
| 5 | pytest calls test_async_fixture with async_resource value | Test function running with async_resource='resource_ready' | assert async_resource == 'resource_ready' | PASS |
| 6 | Test completes successfully | Test passed, no errors | — | PASS |
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.