Introduced unit tests for `get_current_user`, `get_current_active_user`, and security functions like token creation and decoding. Also refactored imports for consistency and cleaned up unused or misplaced code to improve maintainability.
68 lines
2.1 KiB
Python
68 lines
2.1 KiB
Python
import pytest
|
|
from datetime import timedelta
|
|
from jose import jwt, JWTError
|
|
from app.auth.security import (
|
|
get_password_hash, verify_password,
|
|
create_access_token, create_refresh_token,
|
|
decode_token, SECRET_KEY, ALGORITHM
|
|
)
|
|
from app.schemas.token import TokenPayload
|
|
|
|
|
|
def test_password_hashing():
|
|
plain_password = "securepassword123"
|
|
hashed_password = get_password_hash(plain_password)
|
|
|
|
# Ensure hashed passwords are not the same
|
|
assert hashed_password != plain_password
|
|
# Test password verification
|
|
assert verify_password(plain_password, hashed_password)
|
|
assert not verify_password("wrongpassword", hashed_password)
|
|
|
|
|
|
def test_access_token_creation():
|
|
user_id = "123e4567-e89b-12d3-a456-426614174000"
|
|
token = create_access_token({"sub": user_id})
|
|
decoded_payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
|
|
|
assert decoded_payload.get("sub") == user_id
|
|
assert decoded_payload.get("type") == "access"
|
|
|
|
|
|
def test_refresh_token_creation():
|
|
user_id = "123e4567-e89b-12d3-a456-426614174000"
|
|
token = create_refresh_token({"sub": user_id})
|
|
decoded_payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
|
|
|
assert decoded_payload.get("sub") == user_id
|
|
assert decoded_payload.get("type") == "refresh"
|
|
|
|
|
|
def test_decode_token_valid():
|
|
user_id = "123e4567-e89b-12d3-a456-426614174000"
|
|
access_token = create_access_token({"sub": user_id})
|
|
token_payload = decode_token(access_token)
|
|
|
|
assert isinstance(token_payload, TokenPayload)
|
|
assert token_payload.sub == user_id
|
|
assert token_payload.type == "access"
|
|
|
|
|
|
def test_decode_token_expired():
|
|
user_id = "123e4567-e89b-12d3-a456-426614174000"
|
|
token = create_access_token({"sub": user_id}, expires_delta=timedelta(seconds=-1))
|
|
|
|
with pytest.raises(JWTError):
|
|
decode_token(token)
|
|
|
|
|
|
def test_decode_token_invalid_signature():
|
|
token = jwt.encode({"some": "data"}, "invalid_key", algorithm=ALGORITHM)
|
|
with pytest.raises(JWTError):
|
|
decode_token(token)
|
|
|
|
|
|
def test_decode_token_malformed():
|
|
malformed_token = "malformed.header.payload"
|
|
with pytest.raises(JWTError):
|
|
decode_token(malformed_token) |