Q&A
How do you properly clean up database state between pytest tests without killing speed?
Ajitesh MohantaAmbassador
3w ago 1,127 0
Our API test suite uses a real PostgreSQL database (Docker, spun up in CI). Each test creates data and we need isolation.
Current approach: truncate all tables in a session-scoped fixture after each test module. It works but is slow and sometimes leaves foreign key violations.
Options I'm considering:
1. Wrap each test in a transaction and roll back — cleanest but some tests do multi-connection operations
2. Use `pytest-postgresql` to spin up a fresh DB per test — too slow
3. Truncate only the tables each test touches — complex to maintain
What's your pattern? We're using SQLAlchemy + alembic.