Django unit test without creating test database every time I run

From Django 1.8 on you could use the --keepdb flag, when calling the manage.py

New in Django 1.8: You can prevent the test databases from being destroyed by adding the --keepdb flag to the test command. This will preserve the test database between runs. If the database does not exist, it will first be created. Any migrations will also be applied in order to keep it up to date. (https://docs.djangoproject.com/en/1.8/topics/testing/overview/#the-test-database)

So your call could look as follows:

python manage.py test --keepdb

Or using the shorthand -k it could look like that:

python manage.py test -k

Depending on your needs you have a few choices:

  • You could write a custom test runner or adjust the default one: https://docs.djangoproject.com/en/1.6/topics/testing/advanced/#other-testing-frameworks

  • You could use SimpleTestCase

  • There are also add-ons like django-test-utils (although I'm not sure if that specific one works with modern Django versions).

  • Alternatively, to speed everything up, you could use SQLite's in-memory database OR create your test database in RAM disk (like tmpfs or ramfs) - in fact this is orthogonal to using other techniques.


You maybe can try with test runner

Example:

First, create test_runners.py

from django.test.runner import DiscoverRunner


class NoDbTestRunner(DiscoverRunner):

    def setup_databases(self, **kwargs):
        """ Override the database creation defined in parent class """
        pass

    def teardown_databases(self, old_config, **kwargs):
        """ Override the database teardown defined in parent class """
        pass

Then declare above runner in settings.py

TEST_RUNNER = 'api.tests.test_runners.NoDbTestRunner'