Skip to content
Advertisement

How to test authenticated POST request with Pytest in Django

I want to test an authenticated post request on an API using Pytest. This is what I am doing so far:

 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

This doesn’t work because it gives me back a 401 (Unauthorized) instead of a 200. That makes sense since the fixture is a client and not an admin client.

Yet if I pass in admin_client instead of client it gives me a Bad Request. The data that I send should be fine though.

I also tried to pass in the headers like so (since I use JWT authorization):

token = "bigassstringwhichismytoken"

headers = {
        "Authorization": "JWT " + token
    }

Finally I tried to log in before which gives me a 403 (Forbidden):

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

If someone could point me into the right direction that would be fantastic! Thanks a lot in advance

Advertisement

Answer

You can hit the login url with username and password and get the token. creade a header dictionary like headers = {'Authorization': 'JWT <token>'}

and use the header when using post.

client.post(url, json=data, headers=headers)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement