如何在django rest_framework test中的APIClient标头中添加身份验证令牌

Sud*_*r K 6 django django-testing oauth-provider django-unittest django-rest-framework

我正在用oauth2_provider我的rest_framework。我正在尝试为我的api编写测试用例。我已经获得了访问令牌。但是我无法在使用access token中验证用户使用的APIClient curl命令APIClient

curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/api/v1/users/current/
Run Code Online (Sandbox Code Playgroud)

我试过了

client.get('/api/v1/users/current/',  headers={'Authorization': 'Bearer {}'.format(self.access_token)})
Run Code Online (Sandbox Code Playgroud)

client.credentials(HTTP_AUTHORIZATION='Token ' + self.access_token)
Run Code Online (Sandbox Code Playgroud)

这是片段的一部分

from rest_framework.test import APIClient    
from rest_framework.test import APITestCase
....

class APITest(APITestCase):
    def setUp(self):
        ...
        self.client = APIClient()
        ...
        response = self.client.post('/api/v1/oauth2/token/', post_data)
        self.access_token = response.json()['access_token']

    def test_get_current_user(self):
        client.get('/api/v1/users/current/',  headers={'Authorization': 'Bearer {}'.format(self.access_token)})
Run Code Online (Sandbox Code Playgroud)

我正在回应

<HttpResponseForbidden status_code=403, "text/html; charset=utf-8">
Run Code Online (Sandbox Code Playgroud)

nev*_*ner 5

由于您使用Authorization: Bearer的卷发,你也应该使用client.credentialsBearer字代替Token

client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.access_token)
Run Code Online (Sandbox Code Playgroud)