Using a Test Database in Django

At Govnex we’re using MySQL on our development machines. It has several advantages, but one of the drawbacks is unittests run slower when not using Sqlite (big ups to MockSoul for posting his benchmarks). The reason for this is when running unittests in Django with a Sqlite database, the database is run in memory (RAM) instead of being written to the disk.

Django only allows you to specify one database, and although a new database is created for unittests, it still uses most of the same settings (auto prepending “test_” to the database name), which means a Django install using MySQL also uses MySQL for unittests.

To get around this problem, I created a file in my project root called containing the following lines:

I then opened my, imported sys, and inserted the following lines at the end of the file:

If one of the command line arguments is “test”, that means a unittest is being run, in which case Django will attempt to import, which will override the database settings and use Sqlite instead. Migrations won’t be an issue, since Django South uses the old syncdb command for generating databases for unittests.

Hope this helps you save some time testing.

4 thoughts on “Using a Test Database in Django

  1. Pingback: 5 Ways to Speed Up Your Django Tests | Seán Hayes