django unit tests without a db

paweloque picture paweloque · May 7, 2011 · Viewed 39.3k times · Source

Is there a possibility to write django unittests without setting up a db? I want to test business logic which doesn't require the db to set up. And while it is fast to setup a db, I really don't need it in some situations.

Answer

mohi666 picture mohi666 · Aug 10, 2011

You can subclass DjangoTestSuiteRunner and override setup_databases and teardown_databases methods to pass.

Create a new settings file and set TEST_RUNNER to the new class you just created. Then when you're running your test, specify your new settings file with --settings flag.

Here is what I did:

Create a custom test suit runner similar to this:

from django.test.simple import DjangoTestSuiteRunner

class NoDbTestRunner(DjangoTestSuiteRunner):
  """ A test runner to test without database creation """

  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

Create a custom settings:

from mysite.settings import *

# Test runner with no database creation
TEST_RUNNER = 'mysite.scripts.testrunner.NoDbTestRunner'

When you're running your tests, run it like the following with --settings flag set to your new settings file:

python manage.py test myapp --settings='no_db_settings'

UPDATE: April/2018

Since Django 1.8, the module django.test.simple.DjangoTestSuiteRunner were moved to 'django.test.runner.DiscoverRunner'.

For more info check official doc section about custom test runners.