Faster django unit tests

I was reading through some of the django test documentation and discovered that when your db backend is sqlite3, your test database is created in-memory. I don’t run my test suite as often as I should because it takes a long time (several minutes — I have a real short attention span). An in-memory database means that there’s no disk activity, which means it’s going to be fast.

I almost hacked the django.core.management.commands.test to add a command line switch to flip to the sqlite database backend, but luckily I found this discussion http://groups.google.com/group/django-developers/browse_thread/thread/210a3d91aec17141/6177289b341c8100 (someone alread thought of this idea about 2 years ago :P )

The solution is this:

Create a new test-settings.py file next to your app’s settings.py containing:

from projectname.settings import *
DATABASE_ENGINE = 'sqlite3'

Then when you want to run tests real fast, instead of manage.py test, you run

manage.py test --settings=test-settings

This runs my test suite in less than 5 seconds.

Obviously you still want to run tests on your real db backend, but this is awesome for sanity checks, and while you’re doing test development.

4 Responses to “Faster django unit tests”

  1. Aaron Maxwell Says:

    Very useful, thank you!

  2. Robbie Podosek Says:

    This is legit, thanks! One comment, instead of appname.settings it should be projectname.settings, this may be confusing to others.

  3. boyombo Says:

    saved me loads of seconds. btw have you used brian rosner’s run_test_faster ?
    i replaced the run_tests function in django.tests.simple with run_tests_faster (changed the name to run_tests)
    but i am getting all sorts of errors

  4. Even Faster Django Unit Tests « mindless technology Says:

    [...] Faster Django Unit Tests Last year, I wrote about speeding up django unit tests. With this method, I’ve been able to significantly reduce the time it takes to run my unit [...]

Leave a Reply