2

I try to create a unittest for method logout, I have this for this purpose:

    response = client.get('/api/v1/logout')
    self.assertEquals(response.status_code, 200)

but in my logout controller I have this:

permission_classes = (IsAuthenticated,)

thus I changed my above code to this:

    response = self.client.post('/api/v1/login', data={'username': 'testuser', 'password': '12345678'})
    client = APIClient()
    client.credentials(HTTP_AUTHORIZATION='Bearer ' + response.json()['access_token'])
    response = client.get('/api/v1/logout')
    self.assertEquals(response.status_code, 200)

but when I run my test I get 401 as result

      self.assertEquals(response.status_code, 200)
      AssertionError: 401 != 200

I am not sure how can I pass token to my request

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
user907988
  • 625
  • 1
  • 5
  • 17
  • Check login response first. And your test/testsuit/testcase code has to explicitly create user. https://stackoverflow.com/questions/7367509/login-in-django-testing-framework – Ivan Starostin May 26 '19 at 08:32
  • I reaaly need to send token with my request and I try this https://stackoverflow.com/a/53128368/10087274 but still I have error – user907988 May 26 '19 at 08:38

1 Answers1

2

tldr, for login use https://www.django-rest-framework.org/api-guide/testing/#forcing-authentication


Why ?

unittest as the name suggests should test only a single unit at a time.

Here we're testing two things, even though not explicitly but implicitly we're.

  1. The login logic : We're passing username and password and taking access_token from response [even though we're not asserting here but this will affect next block]
  2. The logout logic : We're using access_token from previous blocking and testing logout functionality based on that.

I strongly think that we should testing only single component at a time in unit test else call it integration test.

For our current scenario we can write two test cases:

  1. Test login logic : Pass username and password and assert correct access_token is returned.
  2. Test the logout logic : Mock the login logic and only test logout logic.

For mocking login we can use something like this https://www.django-rest-framework.org/api-guide/testing/#forcing-authentication

Umair Mohammad
  • 4,489
  • 2
  • 20
  • 34