我想使用Pytest在API上测试经过身份验证的发布请求。这是我到目前为止所做的:
def test_auth_user_can_create(self, client):
url = api_reverse('crud-simulation_api')
data = {
"project": "testproject",
....
}
response = client.post(url, json=data)
assert response.status_code == 200
这是行不通的,因为它给了我401(未经授权)而不是200。这是有道理的,因为固定装置是客户端,而不是管理员客户端。
但是,如果我传递admin_client而不是client,则会给我一个错误的请求。我发送的数据应该没问题。
我还尝试像这样传递标头(因为我使用了JWT授权):
token = "bigassstringwhichismytoken"
headers = {
"Authorization": "JWT " + token
}
最后,我尝试登录,然后给我403(禁止访问):
def test_auth_user_can_create_simulation_api(self, client, django_user_model):
username = "Jack"
password = "password"
django_user_model.objects.create_user(username=username, password=password)
client.login(username=username, password=password)
url = api_reverse('crud-simulation_api')
data = {
"project": "testproject",
...
}
response = client.post(url, json=data)
assert response.status_code == 200
如果有人能指出我正确的方向,那就太好了!在此先多谢
您可以使用用户名和密码访问登录网址并获得令牌。创建标题字典,例如headers = {'Authorization': 'JWT <token>'}
并在使用post时使用标题。
client.post(url, json=data, headers=headers)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句