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`][runtests]. 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][with]?
[runtests]: http://code.djangoproject.com/browser/django/tags/releases/1.0.2/django/test/simple.py#L102
[with]: http://docs.python.org/reference/datamodel.html#context-managers
Pingback: Reliably Broken » Django test database runner as a context manager
Pingback: how to properly use create/destroy_test_db() | Jisku.com - Developers Network