As a follow-up to my post Starting a Django Project the Right Way, I wanted to talk about the importance of writing tests for Django applications. I previously mentioned that my first site IllestRhyme, has no app specific tests for it. This is both embarrassing and true. I've lost countless hours to fixing problems caused by new changes. I wasn't going to make the same mistake with linkrdr. Having a set of unit tests that I can run in an automated fashion has made a world of difference.
The Django unittest
framework (really the Python unittest
framework) is both simple and powerful. Along with the test client (django.test.client.Client
), there's a lot you can
do with Django right out of the box.
Setup
To start, we'll want to create a dump of our database data to use during testing.
$ ./manage.py dumpdata --format=json > my/app/directory/initial_data.json
This will give us a json fixture that mimics the current state of our production database. Note that since this is a fixture for all of the apps installed, we've put it in a non-standard directory. To let the test runner find our fixture, we'll need to set FIXTURE_DIRS
to the directory we just dumped our data to.
Now that we have our data copied, let's run whatever tests our installed apps have already:
$ python manage.py test
This hopefully gives us output like:
..................................................................................................................................................................................................................................................................................................................................................................... ---------------------------------------------------------------------- Ran 357 tests in 30.025s OK
This is also a good check of the integrity of your database, as Django will try to load a fixture representing all of your data. If you've been screwing around with the admin interface or the shell adding and deleting records, you may have integrity errors. If you do (like I did), you'll have to fix them manually and re-dump your data.