Toast Driven

← Back to October 31, 2008

NaBloPoMo & Testing Views

Since it's November and it's National Blog Posting Month, I'm going to give it a go, despite some other big deadlines. We'll see if how long this lasts.

Let's talk about using Django's test client interactively. Let's say you want to simulate a request(s) from the command line as the Django test client would. This is useful for tracking down what's going wrong in a failing test without messing with test file.

You'll want to fire up a Django shell (./manage.py shell or similar) as normal. BUT, there's an additional piece of setup you'll want to perform to make the shell behave like the test client.

>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()

This overrides the standard HttpResponse class, causing extra data, like the context and template used, to be shunted into the response objects just like the test client has. You can then test your views as you normally would, with all data present that would be there in the test client.

>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
>>>
>>> from django.test import Client
>>> c = Client()
>>>
>>> r = c.get('/')
>>> r.status_code
200
>>> r.context[0]['greeting']
u'Hello, world!'
Toast Driven