Skip to Content

How do you make pytest work async + use a fresh DB per run?

Category: DevOps & Deployment

Answer

pytest-asyncio with asyncio_mode=auto runs every test in an event loop. A self-healing fixture creates the test database if missing, runs alembic upgrade, and uses NullPool so each test gets a fresh engine. One fixture, zero shared state, no ordering bugs.

Concrete examples from the fca project context

Example 1

conftest.py: create test DB if missing, alembic upgrade, NullPool engine per test.

Example 2

asyncio_mode=auto runs pytest-anyio tests transparently.

Example 3

Override app.config.settings via env so prod credentials never leak into tests.

Data flow / flow chart

pytest -> asyncio_mode=auto -> conftest fixture
  create test DB -> alembic upgrade -> NullPool engine -> test

Takeaway

Async tests with a self-healing fixture feel boring. That’s the goal.