Auth service tests update

This commit is contained in:
2025-09-24 21:44:48 +02:00
parent 8b86b3225a
commit f9879126c8
6 changed files with 436 additions and 192 deletions

View File

@@ -1,10 +1,14 @@
# tests/test_auth_service.py
import pytest
from fastapi import HTTPException
from app.exceptions.auth import (
UserAlreadyExistsException,
InvalidCredentialsException,
UserNotActiveException,
)
from app.exceptions.base import ValidationException
from app.services.auth_service import AuthService
from models.schemas.auth import UserLogin, UserRegister
from models.database.user import User
@pytest.mark.unit
@@ -39,11 +43,14 @@ class TestAuthService:
password="securepass123",
)
with pytest.raises(HTTPException) as exc_info:
with pytest.raises(UserAlreadyExistsException) as exc_info:
self.service.register_user(db, user_data)
assert exc_info.value.status_code == 400
assert "Email already registered" in str(exc_info.value.detail)
exception = exc_info.value
assert exception.error_code == "USER_ALREADY_EXISTS"
assert exception.status_code == 409
assert "Email already registered" in exception.message
assert exception.details["field"] == "email"
def test_register_user_username_already_exists(self, db, test_user):
"""Test registration fails when username already exists"""
@@ -53,11 +60,14 @@ class TestAuthService:
password="securepass123",
)
with pytest.raises(HTTPException) as exc_info:
with pytest.raises(UserAlreadyExistsException) as exc_info:
self.service.register_user(db, user_data)
assert exc_info.value.status_code == 400
assert "Username already taken" in str(exc_info.value.detail)
exception = exc_info.value
assert exception.error_code == "USER_ALREADY_EXISTS"
assert exception.status_code == 409
assert "Username already taken" in exception.message
assert exception.details["field"] == "username"
def test_login_user_success(self, db, test_user):
"""Test successful user login"""
@@ -79,11 +89,13 @@ class TestAuthService:
"""Test login fails with wrong username"""
user_credentials = UserLogin(username="nonexistentuser", password="testpass123")
with pytest.raises(HTTPException) as exc_info:
with pytest.raises(InvalidCredentialsException) as exc_info:
self.service.login_user(db, user_credentials)
assert exc_info.value.status_code == 401
assert "Incorrect username or password" in str(exc_info.value.detail)
exception = exc_info.value
assert exception.error_code == "INVALID_CREDENTIALS"
assert exception.status_code == 401
assert "Incorrect username or password" in exception.message
def test_login_user_wrong_password(self, db, test_user):
"""Test login fails with wrong password"""
@@ -91,11 +103,13 @@ class TestAuthService:
username=test_user.username, password="wrongpassword"
)
with pytest.raises(HTTPException) as exc_info:
with pytest.raises(InvalidCredentialsException) as exc_info:
self.service.login_user(db, user_credentials)
assert exc_info.value.status_code == 401
assert "Incorrect username or password" in str(exc_info.value.detail)
exception = exc_info.value
assert exception.error_code == "INVALID_CREDENTIALS"
assert exception.status_code == 401
assert "Incorrect username or password" in exception.message
def test_login_user_inactive_user(self, db, test_user):
"""Test login fails for inactive user"""
@@ -107,11 +121,17 @@ class TestAuthService:
username=test_user.username, password="testpass123"
)
with pytest.raises(HTTPException) as exc_info:
with pytest.raises(UserNotActiveException) as exc_info:
self.service.login_user(db, user_credentials)
assert exc_info.value.status_code == 401
assert "Incorrect username or password" in str(exc_info.value.detail)
exception = exc_info.value
assert exception.error_code == "USER_NOT_ACTIVE"
assert exception.status_code == 403
assert "User account is not active" in exception.message
# Reactivate for cleanup
test_user.is_active = True
db.commit()
def test_get_user_by_email(self, db, test_user):
"""Test getting user by email"""
@@ -196,6 +216,21 @@ class TestAuthService:
assert isinstance(token_data["expires_in"], int)
assert token_data["expires_in"] > 0
def test_create_access_token_failure(self, test_user, monkeypatch):
"""Test creating access token handles failures"""
# Mock the auth_manager to raise an exception
def mock_create_token(*args, **kwargs):
raise Exception("Token creation failed")
monkeypatch.setattr(self.service.auth_manager, "create_access_token", mock_create_token)
with pytest.raises(ValidationException) as exc_info:
self.service.create_access_token(test_user)
exception = exc_info.value
assert exception.error_code == "VALIDATION_ERROR"
assert "Failed to create access token" in exception.message
def test_hash_password(self):
"""Test password hashing"""
password = "testpassword123"
@@ -212,3 +247,41 @@ class TestAuthService:
hash2 = self.service.hash_password(password)
assert hash1 != hash2 # Should be different due to salt
def test_hash_password_failure(self, monkeypatch):
"""Test password hashing handles failures"""
# Mock the auth_manager to raise an exception
def mock_hash_password(*args, **kwargs):
raise Exception("Hashing failed")
monkeypatch.setattr(self.service.auth_manager, "hash_password", mock_hash_password)
with pytest.raises(ValidationException) as exc_info:
self.service.hash_password("testpassword")
exception = exc_info.value
assert exception.error_code == "VALIDATION_ERROR"
assert "Failed to hash password" in exception.message
# Test database error handling
def test_register_user_database_error(self, db_with_error):
"""Test user registration handles database errors"""
user_data = UserRegister(
email="test@example.com",
username="testuser",
password="password123"
)
with pytest.raises(ValidationException) as exc_info:
self.service.register_user(db_with_error, user_data)
exception = exc_info.value
assert exception.error_code == "VALIDATION_ERROR"
assert "Registration failed" in exception.message
def test_login_user_database_error(self, db_with_error):
"""Test user login handles database errors"""
user_credentials = UserLogin(username="testuser", password="password123")
with pytest.raises(InvalidCredentialsException):
self.service.login_user(db_with_error, user_credentials)