Pytest Asyncio Fixture Lifespan

Share async resources across tests with pytest-asyncio fixtures, scoping engine creation per session and cleaning up deterministically.

PythonCli Tooling

Code

pythonsnippet
49 lines
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) == 2

How 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, pytest and pytest_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

FAQ

Which packages must be installed first?
Yes. The imports resolve to `asyncio`, `pytest` and `pytest_asyncio`, which the package manager must provide.