8

how is possible to add 'Authorization': 'Token' to TEST request in Django/DRF?

If i use simple requests.get(url, headers={'Authorization': 'Token'} all work perfect but how to do such request in TestCase?

Beliaf
  • 577
  • 2
  • 8
  • 25

2 Answers2

15

Ref: http://www.django-rest-framework.org/api-guide/testing/#credentialskwargs

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)
origamic
  • 1,076
  • 8
  • 18
1

If you are testing for multiple headers in your Django test cases, you can use the following code as an example:

HTTP_X_RAPIDAPI_PROXY_SECRET = '<value>'
HTTP_X_RAPIDAPI_HOST = '<value>'
TEST_HTTP_AUTHORIZATION = '<value>'
HTTP_X_RAPIDAPI_SUBSCRIPTION = '<value>'

class YourTestCase(TestCase):
    def setUp(self):
        self.user = User.objects.create(
            username='testuser',
            email='test@test.com',
            password='password',
            subscription=self.subscription
        )
        self.token = Token.objects.create(user=self.user)
        self.user.save()
        self.client = APIClient()
        self.headers = {
            'HTTP_AUTHORIZATION': f'{self.token.key}',
            'HTTP_X_RAPIDAPI_HOST': HTTP_X_RAPIDAPI_HOST,
            'HTTP_X_RAPIDAPI_PROXY_SECRET': HTTP_X_RAPIDAPI_PROXY_SECRET,
            'HTTP_X_RAPIDAPI_SUBSCRIPTION': HTTP_X_RAPIDAPI_SUBSCRIPTION
        }
        self.client.credentials(**self.headers)

    def test_your_view(self):
        response = self.client.get('/your-url/')
        self.assertEqual(response.status_code, 200)
        # Add your assertions here
Philip Mutua
  • 6,016
  • 12
  • 41
  • 84