samedi 9 décembre 2017

How to use token authentication while testing REST API

I am trying to use test the API request by using tokens. I was able to extract the token but I struggle to find a way to use it.

This is how I get my token:

@pytest.mark.django_db
class TestUserAPI(APITestCase):

    def setUp(self):
        self.created_user = UserFactory()
        User.objects.create_user(username='test', password='pass1234')

    def test_authentification(self):
        request = self.client.post('http://localhost:8000/api/v1/auth/',
                                  {
                                      "username": "test",
                                      "password": "pass1234"
                                  })

        TestUserAPI.token = request.data["token"]

        assert request.status_code == 200

and this is how I use it:

def test_profile(self):
    request = self.client.get('http://localhost:8000/api/v1/profile/',
                              TokenAuthentication = 'token {}'.format(TestUserAPI.token))

    assert request.status_code == status.HTTP_200_OK

It gives me 401 error. What is the correct way of using token?

Aucun commentaire:

Enregistrer un commentaire