Skip to content

Commit

Permalink
test(users): verify each case of logout endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
mateusvrs committed Nov 23, 2023
1 parent bf85a23 commit e3fe1fc
Showing 1 changed file with 44 additions and 1 deletion.
45 changes: 44 additions & 1 deletion api/users/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from rest_framework import status
from rest_framework.test import APITestCase
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.token_blacklist.models import BlacklistedToken
from users.models import User
from http.cookies import SimpleCookie
from django.http import HttpResponse
Expand Down Expand Up @@ -196,7 +197,7 @@ def make_login_post_request(self, cookie_enable: bool = True, cookie_expired: bo
cookie_enable (bool): Habilita o uso de cookies.
cookie_expired (bool): Habilita o cookie expirado.
cookie_value (str | None): Valor do cookie.
Returns:
response (HttpResponse): Resposta do servidor.
"""
Expand Down Expand Up @@ -309,3 +310,45 @@ def test_user_login_with_expired_cookie(self) -> None:
self.assertEqual(response.data.get('code'), 'token_not_valid')
self.assertEqual(response.data.get('detail'), 'Token is invalid or expired')
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)


class UserSessionLogoutTests(APITestCase):

def setUp(self):
self.user, _ = User.objects.get_or_create(
first_name="test",
last_name="banana",
picture_url="https://photo.aqui.com",
email="[email protected]")
self.user.save()

self.refresh_token = TokenObtainPairSerializer.get_token(self.user)

def make_logout_post_request(self, cookie_enable: bool = True, cookie_value: str | None = None) -> HttpResponse:
if cookie_enable:
self.client.cookies = SimpleCookie(
{'refresh': self.refresh_token if not cookie_value else cookie_value}
)

url = reverse('users:logout')
return self.client.post(url, {}, format='json')

def test_logout_user_with_valid_token(self):
response = self.make_logout_post_request()

jti_token = self.refresh_token.payload.get('jti')
check_revoke = BlacklistedToken.objects.filter(
token__jti=jti_token).exists()

self.assertTrue(check_revoke)
self.assertEqual(response.status_code, status.HTTP_200_OK)

def test_logout_user_with_invalid_refresh_token(self):
response = self.make_logout_post_request(cookie_value='wrong_token')

self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

def test_logout_user_without_refresh_token(self):
response = self.make_logout_post_request(cookie_enable=False)

self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

0 comments on commit e3fe1fc

Please sign in to comment.