【问题标题】:How to test api that uses django-rest-auth token authentication?如何测试使用 django-rest-auth 令牌认证的 api?
【发布时间】:2019-08-18 20:36:08
【问题描述】:

我正在使用 django-rest-auth 进行身份验证,并使用它提供的令牌进行授权。我使用了 django-rest 也提供的一些权限类。 我在每个方法之前都关注了views.py。

views.py

@api_view(['GET'])
@authentication_classes((TokenAuthentication))
@permission_classes((permissions.IsAuthenticated,))

在测试这些 api 时,如何进行身份验证以访问 views.py 中的这些方法。因为没有身份验证它会给出 403 禁止。 如何在测试中模拟身份验证。

【问题讨论】:

标签: django-rest-framework django-rest-auth


【解决方案1】:

首先你需要为这个用户创建一个用户和一个令牌, 之后创建一个django.test.Client 使用令牌作为标头。

from rest_framework.authtoken.models import Token                                  

from django.test import Client 

self.user = Usuario.objects.create_user(                                   
    nome='test',                                                                                   
    email='test@email.com',                                                                   
    password='test',                                                    
)                                                                             
token, created = Token.objects.get_or_create(user=self.user)                
self.client = Client(HTTP_AUTHORIZATION='Token ' + token.key)

然后您可以使用此经过身份验证的客户端发出任何请求。

self.client.get('url')

【讨论】:

    猜你喜欢
    • 2019-04-11
    • 1970-01-01
    • 2013-02-25
    • 2017-12-11
    • 2017-01-24
    • 2013-01-28
    • 2023-03-29
    • 2021-08-03
    • 1970-01-01
    相关资源
    最近更新 更多