【问题标题】:django test doesn't populate request.authdjango 测试不填充 request.auth
【发布时间】:2015-11-09 11:01:57
【问题描述】:

我创建了一个名为/cars 的端点。 一个人可以使用前端创建汽车,但设备读取汽车使用具有 API 密钥的 SDK。这样,两家租车公司就可以使用 API 而不会混淆汽车。每个应用都有自己的 API 密钥和自己的内容管理人员。

这是通过 django restframework 3.x 和 django-oauth-toolkit 实现的。

我正在为人类检索汽车和另一个设备编写测试。

这失败了:

def test_get_list(self):
    # devices have a django user (AUTH_USER_MODEL ---onetoone--- Device)
    self.client.force_authenticate(user=self.user_device)
    self._get_list()
    self.client.force_authenticate(user=None)

force_authentication 将 request.auth 设置为 None。但是,对于 postman 或 httpie,request.auth 包含 Application 对象。

查询集是:

def get_queryset(self):
    if hasattr(self.request.user, 'device'):
        # get the cars created by the owner of the API Key
        return self.request.auth.application.user.cars.all()
    return self.request.user.cars.all() # get my cars
  1. 查询集中的这种方法有意义吗?
  2. 我是否以错误的方式测试它?
  3. 为什么 request.auth 为空? force_authentication 是否使用 BasicAuthentication?

【问题讨论】:

    标签: django unit-testing django-rest-framework


    【解决方案1】:
    1. 我建议使用check_object_permission 进行此类检查。你可以阅读更多here

    2. DRF 文档指出,如果您使用 APIRequestFactory,则需要强制验证请求。来自documentation

      from rest_framework.test import force_authenticate
      
      factory = APIRequestFactory()
      user = User.objects.get(username='olivia')
      view = AccountDetail.as_view()
      
      # Make an authenticated request to the view...
      request = factory.get('/accounts/django-superstars/')
      force_authenticate(request, user=user)
      response = view(request)
      

      要使用APIClient 进行身份验证,请尝试使用credentials。来自documentation 的示例:

      from rest_framework.authtoken.models import Token
      from rest_framework.test import APIClient
      
      # Include an appropriate `Authorization:` header on all requests.
      token = Token.objects.get(user__username='lauren')
      client = APIClient()
      client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
      
    3. 第二个问题也一样。

    【讨论】:

    • 事情突然变得如此有意义。谢谢!我得到了它的工作。
    【解决方案2】:

    正如documentation force_authenticate 绕过身份验证中所指出的,因此您的工作是模拟缺少的身份验证部分,包括填写 request.auth。

    否则,您需要配置数据集并在 APIClient 实例上调用登录或凭据。

    【讨论】:

      猜你喜欢
      • 2010-12-23
      • 1970-01-01
      • 2018-08-27
      • 2019-08-25
      • 2020-09-18
      • 2021-12-15
      • 2018-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多