Testing a View - Ambiguous-Squids/Bangazon_initial_site GitHub Wiki
Test a view
Before we try to fix anything, let’s have a look at the tools at our disposal.
The Django test client
Django provides a test Client to simulate a user interacting with the code at the view level. We can use it in tests.py or even in the shell.
We will start again with the shell, where we need to do a couple of things that won’t be necessary in tests.py. The first is to set up the test environment in the shell:
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
setup_test_environment() installs a template renderer which will allow us to examine some additional attributes on responses such as response.context that otherwise wouldn’t be available. Note that this method does not setup a test database, so the following will be run against the existing database and the output may differ slightly depending on what questions you already created. You might get unexpected results if your TIME_ZONE in settings.py isn’t correct. If you don’t remember setting it earlier, check it before continuing.
Next we need to import the test client class (later in tests.py we will use the django.test.TestCase class, which comes with its own client, so this won’t be required):
>>> from django.test import Client
>>> # create an instance of the client for our use
>>> client = Client()
With that ready, we can ask the client to do some work for us:
Get a response from '/':
>>> response = client.get('/')
We should expect a 404 from that address:
>>> response.status_code
404
On the other hand we should expect to find something at '/polls/'. We'll use 'reverse()' rather than a hardcoded URL
>>> from django.urls import reverse
>>> response = client.get(reverse('polls:index'))
>>> response.status_code
200
>>> response.content
If the following doesn't work, you probably omitted the call to setup_test_environment()
>>> response.context['latest_question_list']
EXAMPLE:
client = Client()
response = client.get('/products')
self.assertContains(response.content, "Baseball")