【发布时间】:2019-12-01 07:38:21
【问题描述】:
我想使用 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
如果有人能指出我正确的方向,那就太棒了!提前非常感谢
【问题讨论】:
标签: python django django-rest-framework automated-tests pytest