Pytest Asyncio Fixture Lifespan
Share async resources across tests with pytest-asyncio fixtures, scoping engine creation per session and cleaning up deterministically.
Code
import asyncio
import pytest
import pytest_asyncio
class FakeMailer:
def __init__(self):
self.sent: list[dict] = []
async def send(self, to: str, subject: str) -> None:
self.sent.append({'to': to, 'subject': subject})
@pytest_asyncio.fixture(scope='session')
async def mailer():
client = FakeMailer()
yield client
assert all(item['to'] for item in client.sent) # 收尾自检
print(f'mailer sent {len(client.sent)} messages in total')
@pytest_asyncio.fixture
async def clean_mailer(mailer):
snapshot = len(mailer.sent)
yield mailer
# 用例级隔离:只保留快照之前的历史
del mailer.sent[:snapshot]
@pytest.mark.asyncio
async def test_welcome_email(clean_mailer):
await clean_mailer.send('ada@example.com', 'Welcome')
assert clean_mailer.sent[-1]['subject'] == 'Welcome'
@pytest.mark.asyncio
async def test_reset_email(clean_mailer):
await clean_mailer.send('bob@example.com', 'Reset password')
assert len(clean_mailer.sent) == 1 # 上一个用例的信件被隔离
@pytest.mark.asyncio
async def test_concurrent_sends(clean_mailer):
await asyncio.gather(
clean_mailer.send('a@example.com', 'One'),
clean_mailer.send('b@example.com', 'Two'),
)
assert len(clean_mailer.sent) == 2How it works
The working surface is the class FakeMailer and the functions __init__, send, mailer and clean_mailer — everything else is wiring.
Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed.
Points of care
- Dependency check:
asyncio,pytestandpytest_asyncio— not built-in, must be present in the project.
Using it
The primary signature is def send(self, to: str, subject: str) -> None
Look for the mailer sent prefixes when the file runs; they tie each line to its step.
send is the public entry point; everything else in the file exists to support it.
Key statements
async def send(self, to: str, subject: str) -> None:
self.sent.append({'to': to, 'subject': subject})
async def test_concurrent_sends(clean_mailer):
await asyncio.gather(
clean_mailer.send('a@example.com', 'One'),
clean_mailer.send('b@example.com', 'Two'),
)
assert len(clean_mailer.sent) == 2
async def test_welcome_email(clean_mailer):
await clean_mailer.send('ada@example.com', 'Welcome')
assert clean_mailer.sent[-1]['subject'] == 'Welcome'
Interactive Tools for This Topic
CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Systemd Unit File GeneratorGenerate hardened systemd .service unit files ([Unit], [Service], [Install]) with security sandboxing presets, restart policies, and resource limits.
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `asyncio`, `pytest` and `pytest_asyncio`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.