Django assertTemplateUsed 使用 RequestFactory() 静默失败

Django assertTemplateUsed Fails silently with RequestFactory()

我正在使用一个名为 books 的简单应用程序开发 Django 1.7.1 应用程序。在为各种视图创建集成测试时,我创建了测试来检查每个视图的模板和响应代码。由于一些视图是@login_required,我将它们分成一个新的测试class。问题是该行:

self.assertTemplateUsed(response, 'browse.html') 

默默失败。我已经运行了多种测试变体,例如:

self.assertTemplateUsed(response, 'index.html') 
self.assertTemplateUsed(response, 'brow---se.html')

全部通过!即使这些不是该测试的准确模板。

# integration_tests.py

from django.contrib.auth.models import User
from django.test import TestCase, RequestFactory
from ..views import browse

class BookAppUserIntegrationTests(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.user = User.objects.create_user(username='user',
                                         email='user@example.com',
                                         password='password')

    def test_browse_normal(self):
        """
        Tests the browse page for normal user
        """
        request = self.factory.get('/url-is-unimportant')
        request.user = self.user
        response = browse(request)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'browse.html')


# views.py
@login_required(login_url='error')
def browse(request):
    detail_list = Detail.objects.all()
    context = {'detail_list': detail_list}
    return render(request, 'book_app/browse.html', context)

欢迎提出任何建议!

您需要使用 assertTemplateUsed 作为 context manager 并在响应中调用 render()。试试这个(请注意,您不再需要将响应作为第一个参数):

def test_browse_normal(self):
    """
    Tests the browse page for normal user
    """
    request = self.factory.get('/url-is-unimportant')
    request.user = self.user

    response = browse(request)

    self.assertEqual(response.status_code, 200)
    with self.assertTemplateUsed('browse.html'):
        response.render()