Reputation: 615
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?
Upvotes: 8
Views: 6616
Reputation: 6891
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='[email protected]',
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
Upvotes: 1
Reputation: 1116
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)
Upvotes: 15