This article is part 8 of 14 in the series Python Django Tutorial

Last Updated: Thursday 12th December 2013

Testing a Django Application's View

In our previous article, we learned how to write automated tests for our Django application, which involves writing a simple test to verify the behaviour of the model method m.Post.recent_posts() and fixing the bug where the method recent_posts() returns future posts.

In this article, we are going to learn how to write tests for a view such as the myblog.views.post_detail(request, post_id). In order to do that, we're going to utilize Django's test client to simulate the user performing actions towards a view.

The Django Test Client

In the next code snippet, we're going to use django.test.utils.setup_test_environment and django.test.client.Client to simulate user's interactions with our website's views.

In the previous code snippet, response.context is a dictionary that includes information about all the keys and values relevant to the current request-response life cycle of our Django server. It won't be available unless we call setup_test_environment() to make the current shell a test environment. Such a call to setup the test environment is not necessary in tests.py since it's already constructed by Django during python manage.py test.

Writing Test Code to Verify Post Detail View

Our existing post detail view returns a post according to the Post.id value passed inside the URL:

Now we can write test cases to verify that the post_detail view does return a post when the post_id is provided in the URL and raise a 404 error when the post does not exist. Insert the following code into myblog/tests.py:

Testing Django Views Summary

In this article, we learned how to write automated tests for views in our Django application. We utilized Django's test client to simulate GET requests to our server and check the returned responses to make sure that they satisfy different use cases.

About The Author