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

1

5

I am using django-rest-auth for authentication and using token provided by it for authorization. I have use some permission_class also provided by django-rest. I have folloging in views.py before my each methods.

views.py

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

How can I authenticate to access that methods inside views.py while testing those api. Because without authentication it gives 403 forbidden. How can I mock the authentication in test.

Biological answered 28/3, 2019 at 6:29 Comment(1)
Take a look here: django-rest-framework.org/api-guide/testing/#authenticatingEdieedification
D
10

First you need create a user and a token for this user, after that create a django.test.Client using token as header.

from rest_framework.authtoken.models import Token                                  

from django.test import Client 

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

Then you can make any request using this authenticated client.

self.client.get('url')

Dressler answered 28/3, 2019 at 22:58 Comment(1)
It didn't work for me!Stichous

© 2022 - 2024 — McMap. All rights reserved.