Make Django Tests Always Rebuild the Database if It Exists2020-01-13
If you use Django’s test runner, you’ll probably have encountered this message:
The main reason this happens is that the last test run crashed and it left the database around. It can be annoying when you start the test run, go for a cup of tea, and come back to this prompt still waiting, rather than a complete test run.
Here’s how to make Django always rebuild the database in this case.
We’ll do it by extending
test with our own custom management command.
Create a new
test management command inside one of your Django apps, for example
Then add this content:
This works by intercepting the normal
handle() method to first always set the
interactive option to
This is the same as always passing the
--noinput command line flag, the documented way of forcing a database rebuild.
Hope this saves you some time from stalled test runs,
Are your Django project's tests slow? Read Speed Up Your Django Tests now!
One summary email a week, no spam, I pinky promise.
- Getting a Django Application to 100% Test Coverage
- Django's Test Case Classes and a Three Times Speed-Up
- How to Add Database Modifications Beyond Migrations to Your Django Project
© 2020 All rights reserved.