0

I am writing a test for an API using Django rest framework.

The user has to register and then login to acces my endpoint.

If I register (post) with postman, then login (post) and I get the access_token that I consequently pass to the post request I get a 200.

Also using curl

curl --location --request GET 'localhost:8000/api/v1/signals/' \
--header 'Authorization: token eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1LCJleHAiOjE2MzI4NTc2MzIsImlhdCI6MTYzMjg1NzMzMn0.WCjjg3jSZ4TO_Q51hGwZmj04iFeV9ffRnp9GaFch_IM' \
--header 'Cookie: csrftoken=HrgKpprN95ExIPmm6Y2Qqc3WvDrfqQRgqUY9v4bTN9gT7nETEuBjhtY6IS7Sv9Ky; sessionid=ml04spqh6gmjuicp8vnda1t0lqopnuvx' \
--data-raw ''

but If I write a test, it fails

def test_get_signal(client):
    form_data = {
        "username": "testuser",
        "password": "mytestpassword",
    }
    CustomUser.objects.create_user(**form_data)
    response = client.post("/accounts/login/", form_data, follow=True)
    assert response.status_code == 200
    response_content = json.loads(response.content)
    token = response_content["access_token"]
    headers = {
        "Authorization": "Token " + token,
        "Content-Type": "application/json",
    }
    response = client.get(
        path="/api/v1/signals/",
        headers=headers,
    )

    assert response.status_code == 200

I get a 403. what am I doing wrong?

bruvio
  • 853
  • 1
  • 9
  • 30
  • A 403 is typical of invalid CSRF token or a token not being supplied. How do you define client? This question may be more helpful: https://stackoverflow.com/questions/29749046/test-csrf-verification-with-django-rest-framework – schillingt Sep 28 '21 at 19:45
  • I am suspecting that the request is not using the headers you provided. Are you writing this function in a class? And also, what the request on POSTMAN without the token will return as status code? 403? – Kolawôlé Mangabo Sep 29 '21 at 00:39

1 Answers1

0

The solution was that I was not sending the correct request.

Found answer here

I rewrote the test as:

def test_get_signal():

    form_data = {
        "username": "testuser",
        "password": "mytestpassword",
    }
    CustomUser.objects.create_user(**form_data)
    response = APIclient.post("/accounts/login/", form_data, follow=True)


    assert response.status_code == 200

    response_content = json.loads(response.content)
    token = response_content["access_token"]
    APIclient.credentials(HTTP_AUTHORIZATION="Bearer " + token)

    response = APIclient.get(
        path="/api/v1/signals/",
    )

    assert response.status_code == 200
bruvio
  • 853
  • 1
  • 9
  • 30