【问题标题】:Can not authorize in unittest无法在单元测试中授权
【发布时间】:2015-02-23 07:54:11
【问题描述】:

我有一个带有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

我做错了什么?

【问题讨论】:

  • 请记住,在运行测试时,您没有任何用户可以进行身份​​验证。您需要先将它们添加到数据库中。您可能还需要使用 Mock 来模拟您的请求和访问令牌。
  • 如果您使用的是login_required,那么在您的测试中伪造 HTTP 授权将毫无帮助。
  • 那么我怎样才能让我的测试通过?
  • 302 意味着您正在获得重定向,不一定是灾难——如果您跟随重定向会发生什么...?

标签: python django unit-testing python-unittest


【解决方案1】:

HTTP 代码 302 表示您的服务器正在发送重定向响应。您应该告诉您的客户遵循重定向,以便您处理实际的登录页面。您可以像这样更改您的 get 电话:

response = c.get('/classroom/', follow=True, **auth_headers)

如果您想检查中间重定向步骤,您可以检查response.redirect_chain。这一切都记录在案here

【讨论】:

    【解决方案2】:

    您是否尝试为您的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')
    

    【讨论】:

      猜你喜欢
      • 2017-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-03
      相关资源
      最近更新 更多