Django assertTemplateUsed使用RequestFactory()静默失败

时间:2015-01-06 13:52:08

标签: django integration-testing

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

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)

欢迎任何建议!

1 个答案:

答案 0 :(得分:2)

您需要将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()