How to write a unit test for a django view?

Viewed 48729

I have problems understanding how the unit tests should be designed for django.

From my understanding testing the whole view in one go seems impossible. We need to distinguish between pre-post and post states of request. But I have no idea how to design this. Is there any real life example?

Looking at the documentation the examples are too simplified and only focused on the model.

@login_required
def call_view(request, contact_id):
    profile = request.user.get_profile()
    if request.POST:        
        form = CallsForm(profile.company, request.POST)           
        if form.is_valid()
        return HttpResponseRedirect('/contact/' + contact_id + '/calls/')
    else:        
        form = CallsForm(profile.company, instance=call)              
    variables = RequestContext(request, {'form':form}
    return render_to_response('conversation.html', variables)

update:

trying to make a success test work, but it still fails:

def test_contact_view_success(self):
    # same again, but with valid data, then
    self.client.login(username='username1', password='password1')
    response = self.client.post('/contact/add/', {u'last_name': [u'Johnson'], }) 
    self.assertRedirects(response, '/')

error message:

AssertionError: Response didn't redirect as expected: Response code was 200 (expected 302)

I think this is because the form.is_valid() fails and it doesn't redirect, correct?

2 Answers
Related