File size: 2,630 Bytes
6bed18e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | import pytest
from jose import JWTError, jwt
from backend.src.auth.security import verify_token, create_access_token
from backend.src.core.config import settings
from datetime import datetime, timedelta
def test_jwt_token_validation_with_valid_token():
"""Test that a valid JWT token can be successfully validated"""
# Create a valid token
data = {"user_id": "test_user_123", "role": "user"}
token = create_access_token(data=data)
# Verify the token
payload = verify_token(token)
# Assert the payload is returned correctly
assert payload is not None
assert payload["user_id"] == "test_user_123"
assert payload["role"] == "user"
assert "exp" in payload
def test_jwt_token_validation_with_invalid_token():
"""Test that an invalid JWT token returns None"""
# Create an invalid token (tampered with)
invalid_token = "invalid.token.string"
# Try to verify the token
payload = verify_token(invalid_token)
# Assert the payload is None
assert payload is None
def test_jwt_token_validation_with_expired_token():
"""Test that an expired JWT token returns None"""
# Create an expired token
data = {"user_id": "test_user_123", "role": "user"}
expired_token = create_access_token(data=data, expires_delta=timedelta(seconds=-1))
# Try to verify the expired token
payload = verify_token(expired_token)
# Assert the payload is None
assert payload is None
def test_jwt_token_contains_correct_claims():
"""Test that JWT tokens contain the expected claims"""
# Create a token with specific data
user_data = {"user_id": "test_user_456", "role": "admin", "email": "test@example.com"}
token = create_access_token(data=user_data)
# Decode the token without verification to check claims
decoded_payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])
# Assert the expected claims are present
assert decoded_payload["user_id"] == "test_user_456"
assert decoded_payload["role"] == "admin"
assert decoded_payload["email"] == "test@example.com"
assert "exp" in decoded_payload
def test_jwt_algorithm_compliance():
"""Test that JWT tokens are created and validated with the correct algorithm"""
# Create a token
data = {"user_id": "test_user_789"}
token = create_access_token(data=data)
# Verify the token using the configured algorithm
payload = verify_token(token)
# Assert the payload is valid
assert payload is not None
assert payload["user_id"] == "test_user_789"
if __name__ == "__main__":
pytest.main([__file__]) |