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.

, ,

  1. #1 by Aaron Maxwell on December 12, 2008 - 3:06 pm

    Very useful, thank you!

  2. #2 by Robbie Podosek on December 17, 2008 - 11:44 am

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

  3. #3 by boyombo on December 19, 2008 - 5:36 pm

    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. #4 by batter on March 13, 2010 - 11:24 pm

    Hi,

    It does not work for my. When I’am run Django test it always make database in MySQL storage instead of sqlite3. It look like that django test omit –settings=test-settings param.

    I’m use django 1.1 version.

  5. #5 by Cássio Nandi on August 18, 2011 - 4:27 am

    Unfortunately this aproach do not resolve my problem. I have native sql calls with specific Postgres function calls. With sqlite3, I got some errors.

    But, great tip anyway. Hugs!

  1. Even Faster Django Unit Tests « mindless technology

Leave a comment