a.zand
a.zand

Reputation: 11

django rest frame work API Test case (Authentication needed)

I am using (simple JWT rest framework) as a default AUTHENTICATION CLASSES Now I want to write an API test case for one of my view which needed authentication I don't know how to add "access" token and how to use this in rest framework test cases

I will be thankful if you answer to my question

Upvotes: 0

Views: 1556

Answers (1)

Kyell
Kyell

Reputation: 636

You can do this using a rest_framework.APITestCase.

self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + token)

Before that you need an access token which you can get from the API you are using to obtain a JWT access token. This is what I did in making test cases:

class BaseAPITestCase(APITestCase):
    def get_token(self, email=None, password=None, access=True):
        email = self.email if (email is None) else email
        password = self.password if (password is None) else password

        url = reverse("token_create")  # path/url where of API where you get the access token
        resp = self.client.post(
            url, {"email": email, "password": password}, format="json"
        )
        self.assertEqual(resp.status_code, status.HTTP_200_OK)
        self.assertTrue("access" in resp.data)
        self.assertTrue("refresh" in resp.data)
        token = resp.data["access"] if access else resp.data["refresh"]
        return token

    def api_authentication(self, token=None):
        token = self.token if (token is None) else token
        self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + token)

Upvotes: 1

Related Questions