Sometimes, we want to add Python Django unit tests without a database.
In this article, we’ll look at how to add Python Django unit tests without a database.
How to add Python Django unit tests without a database?
To add Python Django unit tests without a database, we can create our own test runner class.
For instance, we write
from django.test.runner import DiscoverRunner
class NoDbTestRunner(DiscoverRunner):
def setup_databases(self, **kwargs):
pass
def teardown_databases(self, old_config, **kwargs):
pass
to add the NoDbTestRunner
that overrides the code to set up the test database in setup_databases
.
And in teardown_databases
we override the code to clean the database after tests are run.
Then we create a settings file that makes Django use the test runner that we just created with
from mysite.settings import *
TEST_RUNNER = 'mysite.scripts.testrunner.NoDbTestRunner'
We put that in the no_db_settings.py file.
Then when we run our test, we run
python manage.py test myapp --settings='no_db_settings'
to run our tests with the no_db_settings.py file as the settings file.
Conclusion
To add Python Django unit tests without a database, we can create our own test runner class.