如何在Django中使用Pytest正确测试经过身份验证的POST方法

时间:2019-07-23 09:34:34

标签: python django django-rest-framework automated-tests pytest

我想使用Pytest在API上测试经过身份验证的post方法。这是我到目前为止所做的:

 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

如果有人可以指出我正确的方向,那就太好了!提前谢谢

2 个答案:

答案 0 :(得分:1)

您可以使用用户名和密码访问登录URL并获取令牌。 创建像headers = {'Authorization': 'JWT <token>'}

这样的标头字典

,并在使用post时使用标题。

client.post(url, json=data, headers=headers)

答案 1 :(得分:1)

要为client.{request}提供标头,请将其分别作为关键字词组传递:

client.post(url, data, HTTP_FIRST_HEADER='...', HTTP_SECOND_HEADER='...')

尽管您不太可能与post调用链中的任何保留参数名称发生冲突,但最好在字典中收集所需的所有标头:

headers = {
    'HTTP_FIRST_HEADER': '...',
    'HTTP_SECOND_HEADER': '...',
}

并将它们作为任意数量的关键字参数传递给请求:

client.post(url, data, **headers)

**自变量视为extra information and are automatically added as headers