1

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?

3 Answers 3

1

The solution is simple and it's because of my inexperience with testing. The test_profile function doesn't register that a token has been asked in the test_authentification function. So I had to put both of them in the SetUp function for the token to be registered for every function in the class.

Sign up to request clarification or add additional context in comments.

Comments

0

According to documentation correct header format is Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b

Comments

0

According to official documentation the the token key should be Authentication and the token should be should be trailing Token and a white space. In your code change token {} to Token {}. If the problem persists try to print request headers in you view by printing request.META to check the key.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.