在DRF的测试模式下,向头部请求中添加令牌。

8

如何在Django/DRF中的测试请求中添加'Authorization': 'Token'?

如果我使用简单的requests.get(url, headers={'Authorization': 'Token'},一切都能完美地运作,但是如何在TestCase中进行此类请求呢?

2个回答

15

参考: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)

谢谢,兄弟。这非常有帮助。 - Ardi Nusawan

1
如果您在Django测试用例中测试多个标头,可以使用以下代码作为示例:
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接