Version 6 (modified by nielsw, 6 years ago) (diff)

--

Django Testing Guide

Testing web applications has historically been hard. It's even harder to write unit tests that work well when someone integrates your app. This guide aims to provide pointers and best practises for testing your apps and writing portable unit tests.

Writing portable tests

tests should run in isolation

Whenever possible use test_urls and dedicated test templates to make sure your tests run as isolated. Usually you will want to write your test in such a way that they will only fail when there a failure in what you're testing. What you don't want is your unit tests failing because someone decided to put a bad template tag in your non-test template.

If at all possible you should avoid using Django's test client, too. Why? Because it often introduces failures which are not related to your code (e.g. middleware). If you're going to do anything more complex than getting or setting a variable in Django, write a method class to do that and test it directly.

test_urls

Never use test_urls if your don't have a dedicated test template. Someone else may insert {% url %} tags in there (or template tags that do url reversing) causing your unit tests to fail.

Solving specific problems

Testing view classes

Testing view classes through the test.client() can often require you to write lots of views that call the test class. It's often convenient to write a mapper view class that allows you to map a function to a temporary url.

Other pages about testing and django

CookBookTestingTools describes test runners like nose

Back to Top