我有login_required
装饰器的页面,我想测试是否使用了正确的模板。在stackoverflow上,我找到了单元测试的授权方法,但对我来说,由于某些原因它不起作用。这是我的测试:
from django.test import TestCase
from django.test import Client
import base64
class TestUsingCorrectTemplates(TestCase):
def test_correct_classroom_template_used(self):
auth_headers = {'HTTP_AUTHORIZATION': 'Basic '+base64.b64encode('admin@dot.com:admin')}
c = Client()
response = c.get('/classroom/', **auth_headers)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response,'classroom.html')
还想提一下使用OpenId / AllAuth处理的授权,并且没有/login
页面,用户从起始页面/
登录
response
变量的内容如下:
Vary: Cookie
X-Frame-Options: SAMEORIGIN
Content-Type: text/html; charset=utf-8
Location: http://testserver/?next=/classroom/
测试错误:
self.assertEqual(response.status_code, 200)
AssertionError: 302 != 200
我做错了什么?
答案 0 :(得分:3)
HTTP代码302表示您的服务器正在发送重定向响应。您应该告诉客户端遵循重定向,以便您处理实际的登录页面。您可以像这样更改get
来电:
response = c.get('/classroom/', follow=True, **auth_headers)
如果要检查中间重定向步骤,可以检查response.redirect_chain
。全部记录在案here。
答案 1 :(得分:1)
您是否尝试过创建Client
实例的用户和calling the login
方法?
import base64
from django.test import TestCase
class TestUsingCorrectTemplates(TestCase):
def setUp(self):
# Create your user here
# self.user = ...
def test_correct_classroom_template_used(self):
self.client.login('admin@dot.com', 'admin')
response = self.client.get('/classroom/') # XXX: You should use url reversal here.
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'classroom.html')