【问题标题】:Unit testing an authenticated user in Django在 Django 中对经过身份验证的用户进行单元测试
【发布时间】:2022-01-22 08:37:04
【问题描述】:

我正在尝试以登录用户的身份测试访问权限。我在使用 Client() 时遇到问题。

def test_taking_too_much_time(self):
    my_client = Client()
    my_client.login(username='exampleuser', password='testing12345')
    response = my_client.get('/example/link/')
    self.assertEqual(response.status_code, 200)

好的,您能否也提供整个堆栈跟踪?

我明白了,那个朋友也有类似的问题。 Django - Testing Login View - AttributeError: 'HttpRequest' object has no attribute 'user' 在参数中添加“用户”实例并替换为请求后。

@receiver (user_logged_in, sender = Person)
def when_logging_in (request, sender, user, ** kwargs):
     messages.info (request, f '{user.username} hello.')

问题依旧,同样的东西出现了,就是AttributeError: 'HttpRequest' object has no attribute 'user'。下面的answer是主题的扩展。

【问题讨论】:

  • 能否提供登录视图的代码和抛出错误的视图?
  • @jmangold 我更新了问题。
  • 好的,你能不能也提供整个堆栈跟踪? ^^
  • 我添加了一个答案。

标签: django unit-testing django-testing


【解决方案1】:

我不熟悉Client(),而是使用RequestFactory 并将生成的request 对象直接传递给视图。

def test_taking_too_much_time(self):
    factory = RequestFactory()
    request= factory.get('/example/link/',)
    request.user = self.user
    response = ExampleLinkView.as_view()(request)
    self.assertEqual(response.status_code, 200)

绕过登录,因为不会应用任何中间件。 你可以在这里Advanced Testing阅读更多相关信息。

【讨论】:

  • 我在很多测试中也使用了'RequestFactory()'。在那里我还添加了不同类型的用户、他们的权限并检查他们的行为。我创建了不同的用户,也包括匿名用户,但我想在考虑整个身份验证后端的情况下运行“客户端”测试。即使在“客户端”挂起授权的高级测试中,“RequestFactory”也没有给我带来太多麻烦。
【解决方案2】:

我花了更多时间在上面,检查了所有的信号代码、相关函数、依赖关系、项目设置。有很多。罪魁祸首是Client(),它服务于后端,但HttpRequest 有问题。

@receiver (user_logged_in, sender = Person)
def when_logging_in (request, sender, user, ** kwargs):
      messages.info (request, f '{user.username} hello.')

可以使用instance 代替request,但不能用于messages,其中一个参数是request。因此,可以将message 放置在用户的哪个位置,以免失去功能,而是使用Client() 执行单元测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    • 1970-01-01
    • 2021-11-28
    • 2012-05-17
    • 2021-10-22
    • 1970-01-01
    • 2021-06-11
    相关资源
    最近更新 更多