我正在为需要不记名令牌身份验证的端点编写测试,但在尝试将身份验证错误传递给 HTTP 方法时遇到错误,例如client.post(url,data,**auth_header)
我尝试过同时使用client.login(username=username,password=pass)
and client.force_login(user=Users.objects.get(username='admin'))
then 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)
我期待来自响应 var 的 json 响应和 200 的 status_code,相反,如果您未经过身份验证,我要么获取堆栈跟踪,要么从端点返回错误。