From e3fe1fc7ee8e86819a25f5180df87f6d85ea1fb7 Mon Sep 17 00:00:00 2001 From: mateuvrs Date: Wed, 22 Nov 2023 21:28:52 -0300 Subject: [PATCH] test(users): verify each case of logout endpoint --- api/users/tests.py | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/api/users/tests.py b/api/users/tests.py index 62af371f..488464f9 100644 --- a/api/users/tests.py +++ b/api/users/tests.py @@ -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 @@ -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. """ @@ -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="uiui@pichuruco.com") + 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)