小编Chr*_*son的帖子

如何将身份验证不记名令牌传递给 django.test.Client 中的 HTTP 方法?

我正在为需要承载令牌身份验证的端点编写测试,但是我在尝试将身份验证错误传递给 HTTP 方法时遇到错误,例如 client.post(url,data,**auth_header)

我一直在使用这两种尝试client.login(username=username,password=pass)client.force_login(user=Users.objects.get(username='admin'))client.post(url,data)

我也试过:client.post(url,data,**{'HTTP_AUTHORIZATION': 'Bearer {}'.format(token)})client.post(url,data,HTTP_AUTHORIZATION='Bearer {}'.format(token))这两个输出堆栈跟踪

我也尝试使用AUTHORIZATION,Authorization作为密钥,但如果您不进行身份验证,我会收到端点发送的权限错误。

from django.test import TestCase
from django.test import Client
from django.contrib.auth.models import User
login = client.post('/api/users/login/',{'username':username,'password': password})
bearer = {'HTTP_AUTHORIZATION':'Bearer {}'.format(login.json()['access'])}
response = client.post(url, {'key':'value'}, **bearer)
Run Code Online (Sandbox Code Playgroud)

我期待来自响应变量的 json 响应和 200 的 status_code 相反,如果您未通过身份验证,我将获得堆栈跟踪或从端点返回的错误。

python unit-testing django-rest-framework bearer-token

5
推荐指数
1
解决办法
2167
查看次数