Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for template fails because "No templates used to render the response"

Tags:

I am working through Test-Driven Development with Python by Harry J. W. Percival. I have a Django view with the following code:

def view_list(request, list_id):
        list_ = List.objects.get(id=list_id)
        items = Item.objects.filter(list=list_)
        return render(request, 'list.html', {'items':items})

And the following Django test:

def test_uses_list_template(self):
        list_ = List.objects.create()
        response = self.client.get('/lists/%d' % (list_.id,))
        self.assertTemplateUsed(response, 'list.html')

urls.py has the following entry:

url(r'^lists/(.+)/$', views.view_list, name='view_list'),

The test fails with the following error:

self.fail(msg_prefix + "No templates used to render the response")
AssertionError: No templates used to render the response

This was very surprising, because the view rendered successfully when I used the browser to evaluate it manually. And an automated functional test worked without error.

I looked at the HTTP server, and it was showing a redirect for a circumstance similar to this test: [time] "GET /lists/2 HTTP/1.1" 301 0 [time] "GET /lists/2/ HTTP/1.1" 200 476

like image 285
M. K. Hunter Avatar asked Mar 09 '17 02:03

M. K. Hunter


1 Answers

The test is failing for the somewhat arbitrary reason that the URL is /lists/%d instead of /lists/%d/ (notice the trailing slash on the second URL.) Therefore, self.client.get is resulting in a redirect (301) instead of success (200). Change the test using the slash at the end.

response = self.client.get('/lists/%d/' % (list_.id,))

Also note that on obeythetestinggoat.com Percival states "Django has some built-in code to issue a permanent redirect (301) whenever someone asks for a URL which is almost right, except for a missing slash."

like image 93
M. K. Hunter Avatar answered Oct 11 '22 12:10

M. K. Hunter