from django.db import 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
'The lion says "roar"'
'The cat says "meow"'
name = models.CharField(maxlength=20)
sound = models.CharField(maxlength=20)
return 'The %s says "%s"' % (self.name, 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 models.py, or in a tests.py file stored in the application directory.
An equivalent unittest test case for the above example would look like:
from myapp.models import Animal
self.lion = Animal.objects.create(name="lion", sound="roar")
self.cat = Animal.objects.create(name="cat", sound="meow")
self.assertEquals(self.lion.speak(), 'The lion says "roar"')
self.assertEquals(self.cat.speak(), '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 models.py and tests.py, 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.
To assist in testing various features of your application, Django provides tools that can be used to establish tests and test conditions.
Run your tests using your project’s manage.py utility:
$ ./manage.py 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:
$ ./manage.py 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.