Framework Mode - Async fixtures (pytest-asyncio)
Folder Structure
tests/ ├── __init__.py ├── test_async_feature.py ├── conftest.py # async fixtures here utilities/ ├── async_helpers.py pytest.ini # pytest config requirements.txt
Jump into concepts and practice - no test required
tests/ ├── __init__.py ├── test_async_feature.py ├── conftest.py # async fixtures here utilities/ ├── async_helpers.py pytest.ini # pytest config requirements.txt
async def with pytest.mark.asyncio or pytest-asyncio plugin.async def in conftest.py to setup async resources (e.g., database connections, web servers).pytest-asyncio plugin and set options.pytest-asyncio plugin in pytest.ini:
[pytest] addopts = -p pytest_asyncio
pytest command line options to select async backend or environment.conftest.py for shared async fixtures to avoid duplication.--tb=short for concise tracebacks.--junitxml=report.xml for CI dashboards.pytest-cov) to measure test coverage.async def and use await inside them.pytest-asyncio plugin to enable async test support seamlessly.await in tests and fixtures to ensure proper async execution.Where would you add a new async fixture that provides a mock async database connection for multiple tests?
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.