Skip to content

Commit

Permalink
Add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
rolodato committed Mar 7, 2025
1 parent 6f8448e commit 5b357b4
Showing 1 changed file with 71 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
from unittest.mock import MagicMock, patch

import pytest
from rest_framework.request import Request
from rest_framework_simplejwt.exceptions import (
AuthenticationFailed,
InvalidToken,
TokenError,
)
from rest_framework_simplejwt.tokens import Token

from custom_auth.jwt_cookie.authentication import JWTCookieAuthentication
from custom_auth.jwt_cookie.constants import JWT_SLIDING_COOKIE_KEY
from users.models import FFAdminUser


class TestJWTCookieAuthentication:
def test_authenticate_without_cookie(self) -> None:
# Given
auth = JWTCookieAuthentication()
request = MagicMock(spec=Request)
request.COOKIES = {}

# When
result = auth.authenticate(request)

# Then
assert result is None

def test_authenticate_valid_cookie(self) -> None:
# Given
auth = JWTCookieAuthentication()
request = MagicMock(spec=Request)
raw_token = "valid_token"
request.COOKIES = {JWT_SLIDING_COOKIE_KEY: raw_token}

validated_token = MagicMock(spec=Token)
user = MagicMock(spec=FFAdminUser)

# Mock the validation and user retrieval
with patch.object(
auth, "get_validated_token", return_value=validated_token
) as mock_validate:
with patch.object(auth, "get_user", return_value=user) as mock_get_user:
# When
result = auth.authenticate(request)

# Then
assert result == (user, validated_token)
mock_validate.assert_called_once_with(raw_token)
mock_get_user.assert_called_once_with(validated_token)

@pytest.mark.parametrize(
"exception_class", [InvalidToken, TokenError, AuthenticationFailed]
)
def test_authenticate_invalid_cookie(self, exception_class) -> None:
# Given
auth = JWTCookieAuthentication()
request = MagicMock(spec=Request)
raw_token = "invalid_token"
request.COOKIES = {JWT_SLIDING_COOKIE_KEY: raw_token}

# Test that no further exceptions are raised if the token is invalid in any way
with patch.object(
auth, "get_validated_token", side_effect=exception_class("Error")
):
# When
result = auth.authenticate(request)

# Then
assert result is None

0 comments on commit 5b357b4

Please sign in to comment.