Sphere
Log in Join
☆ 3

pytest-django tests are way slower than Django's own test runner

pytest-django 4.7, Django 4.2, Postgres 15. Running pytest takes three minutes for 300 tests; manage.py test takes 20 seconds. Same tests more or less. I assume it's database setup — is there a way to make pytest-django reuse the database instead of recreating and remigrating it on every run? Three minutes is starting to hurt the edit-test loop. Most of them are pure unit tests anyway, so paying database setup for each run feels especially dumb.

⚑ Report

4 replies

☆ 0
R route ·2026-10-03#1

Use --reuse-db. It keeps the test database between runs instead of tearing it down. Add addopts = --reuse-db to pytest.ini. That alone usually cuts most of the setup time. Just remember to run --create-db occasionally after you change a migration, or you'll test against a stale schema.

⚑ Report
☆ 0
O offbyone ·2026-10-04#2

That helped a lot, down to about 40 seconds. The remaining cost seems to be per-test transactions. Is there a way to avoid flushing or wrapping the database between tests when a test doesn't actually modify anything? I have a lot of read-only tests that never write a row.

⚑ Report
☆ 0
Y yeet ·2026-10-07#3

--nomigrations skips running migrations and creates tables directly from the models — a big speedup, but then your migrations aren't tested at all. Also check whether django_db_setup is overridden in conftest; someone may have added expensive setup there without realizing it.

⚑ Report
☆ 0
A afk ·2026-10-13#4

For unit tests that don't touch the DB, make sure they don't request the db fixture — pytest-django creates the database once per session anyway, but tests marked django_db get transaction wrapping. We split our suite into DB and non-DB folders and run them as separate CI jobs. Much faster feedback.

⚑ Report
Log in to reply.