Wednesday, June 20, 2007

Testing Django applications


For example:

from django.db import model

class Animal(models.Model):
An animal that knows how to make noise

# Create some animals
>>> lion = Animal.objects.create(name="lion", sound="roar")
>>> cat = Animal.objects.create(name="cat", sound="meow")

# Make 'em speak
>>> lion.speak()
'The lion says "roar"'
>>> cat.speak()
'The cat says "meow"'

name = models.CharField(maxlength=20)
sound = models.CharField(maxlength=20)

def speak(self):
return 'The %s says "%s"' % (, self.sound)

When you run your tests, the test utility will find this docstring, notice that portions of it look like an interactive Python session, and execute those lines while checking that the results match.

For more details about how doctest works, see the standard library documentation for doctest


Like doctests, Django’s unit tests use a standard library module: unittest. As with doctests, Django’s test runner looks for any unit test cases defined in, or in a file stored in the application directory.

An equivalent unittest test case for the above example would look like:

import unittest
from myapp.models import Animal

class AnimalTestCase(unittest.TestCase):

def setUp(self):
self.lion = Animal.objects.create(name="lion", sound="roar") = Animal.objects.create(name="cat", sound="meow")

def testSpeaking(self):
self.assertEquals(self.lion.speak(), 'The lion says "roar"')
self.assertEquals(, 'The cat says "meow"')

When you run your tests, the test utility will find all the test cases (that is, subclasses of unittest.TestCase) in and, automatically build a test suite out of those test cases, and run that suite.

For more details about unittest, see the standard library unittest documentation.

Testing Tools

To assist in testing various features of your application, Django provides tools that can be used to establish tests and test conditions.

Running tests

Run your tests using your project’s utility:

$ ./ test

If you only want to run tests for a particular application, add the application name to the command line. For example, if your INSTALLED_APPS contains myproject.polls and myproject.animals, but you only want to run the animals unit tests, run:

$ ./ test animals

When you run your tests, you’ll see a bunch of text flow by as the test database is created and models are initialized. This test database is created from scratch every time you run your tests.

No comments: