0

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

4

1 回答 1

1

您可以使用rest_framework.APITestCase.

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

在此之前,您需要一个访问令牌,您可以从用于获取 JWT 访问令牌的 API 中获取该令牌。这是我在制作测试用例时所做的:

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)
于 2020-05-30T00:55:24.353 回答