Creating a Django test database for unit testing
Creating a Django test database for unit testing
March 27, 2009
I needed to run tests involving a Django application but without using the
manage.py test management command. So I need my own test suite that
sets up the test database and drops it after, leaving my real database untouched.
As of Django 1.0.2 the default behaviour for the test runner is the run_tests
function in django.test.simple. Here is the bones of that function
with the required setup and teardown calls.
from django.conf import settings
from django.test.utils import setup_test_environment, teardown_test_environment
verbosity = 1
interactive = True
setup_test_environment()
settings.DEBUG = False
old_name = settings.DATABASE_NAME
from django.db import connection
connection.creation.create_test_db(verbosity, autoclobber=not interactive)
# Here you run tests using the test database and with mock SMTP objects
connection.creation.destroy_test_db(old_name, verbosity)
teardown_test_environment()
Hmmm… Wouldn’t this be a good candidate to be wrapped up for use with
Python 2.5’s with statement?
Last updated on