检查模板失败,因为 "No templates used to render the response"

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

我正在通过 Harry J. W. Percival 的 Python 进行测试驱动开发。我有一个包含以下代码的 Django 视图:

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})

以及以下 Django 测试:

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 具有以下条目:

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

测试失败并出现以下错误:

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

这是非常令人惊讶的,因为当我使用浏览器手动评估时,视图呈现成功。自动化功能测试没有错误。

我查看了 HTTP 服务器,它显示了与此测试类似情况的重定向: [时间] "GET /lists/2 HTTP/1.1" 301 0 [时间] "GET /lists/2/ HTTP/1.1" 200 476

由于 URL 是 /lists/%d 而不是 /lists/%d/(请注意第二个 URL 上的尾部斜线),测试失败的原因有些武断。 , self.client.get 导致重定向 (301) 而不是成功 (200)。使用末尾的斜杠更改测试。

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

另请注意,在 obeythetestinggoat.com 珀西瓦尔州 "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."