如何测试使用 django-rest-auth 令牌身份验证的 api?

How to test api that uses django-rest-auth token authentication?

我正在使用 django-rest-auth 进行身份验证,并使用它提供的令牌进行授权。我使用了一些 permission_class 也由 django-rest 提供。 在我的每个方法之前,我在 views.py 中进行了跟踪。

views.py

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

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

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

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')