如何在Django/DRF中的测试请求中添加'Authorization': 'Token'?
如果我使用简单的requests.get(url, headers={'Authorization': 'Token'}
,一切都能完美地运作,但是如何在TestCase中进行此类请求呢?
如何在Django/DRF中的测试请求中添加'Authorization': 'Token'?
如果我使用简单的requests.get(url, headers={'Authorization': 'Token'}
,一切都能完美地运作,但是如何在TestCase中进行此类请求呢?
参考: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)
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