Automated testing is an extremely useful bug-killing tool for the modern Web developer. You can use a collection of tests – a test suite – to solve, or avoid, a number of problems:
Testing a Web application is a complex task, because a Web application is made of several layers of logic – from HTTP-level request handling, to form validation and processing, to template rendering. With Django’s test-execution framework and assorted utilities, you can simulate requests, insert test data, inspect your application’s output and generally verify your code is doing what it should be doing.
The best part is, it’s really easy.
There are two primary ways to write tests with Django, corresponding to the two test frameworks that ship in the Python standard library. The two frameworks are:
Unit tests – tests that are expressed as methods on a Python class that subclasses unittest.TestCase or Django’s customized TestCase. For example:
import unittest
class MyFuncTestCase(unittest.TestCase):
def testBasic(self):
a = ['larry', 'curly', 'moe']
self.assertEqual(my_func(a, 0), 'larry')
self.assertEqual(my_func(a, 1), 'curly')
Doctests – tests that are embedded in your functions’ docstrings and are written in a way that emulates a session of the Python interactive interpreter. For example:
def my_func(a_list, idx):
"""
>>> a = ['larry', 'curly', 'moe']
>>> my_func(a, 0)
'larry'
>>> my_func(a, 1)
'curly'
"""
return a_list[idx]
Because Django supports both of the standard Python test frameworks, it’s up to you and your tastes to decide which one to use. You can even decide to use both.
For developers new to testing, however, this choice can seem confusing. Here, then, are a few key differences to help you decide which approach is right for you:
As unit tests are preferred in Django, we treat them in detail in the Testing Django applications document.
Django and doctests describes Django-specific features when using doctests.
You can also use any other Python test framework, Django provides an API and tools for that kind of integration. They are described in the Using different testing frameworks section of Advanced testing topics.
Dec 23, 2012