Files
F-r-ldraledigplannerare/backend/tests/unit/test_services/test_auth_service.py
T
2026-06-01 16:48:21 +02:00

63 lines
2.9 KiB
Python

"""Tests for AuthService: register, login, token round-trip."""
import pytest
from app.services.auth_service import AuthService
from app.utils.errors import AuthError, ConflictError, UnauthorizedError
class TestAuthServiceRegisterLogin:
async def test_register_creates_user_and_personal_data(self, auth_service: AuthService) -> None:
user, pd = await auth_service.register("alice@example.com", "securepassword", "Alice")
assert user.email == "alice@example.com"
assert pd.name == "Alice"
assert user.personal_data_uuid == pd.uuid
async def test_register_duplicate_email_raises_conflict(
self, auth_service: AuthService
) -> None:
await auth_service.register("bob@example.com", "password123", "Bob")
with pytest.raises(ConflictError):
await auth_service.register("bob@example.com", "otherpass", "Bob2")
async def test_login_success(self, auth_service: AuthService) -> None:
await auth_service.register("carol@example.com", "mypassword", "Carol")
user = await auth_service.login("carol@example.com", "mypassword")
assert user.email == "carol@example.com"
async def test_login_wrong_password_raises(self, auth_service: AuthService) -> None:
await auth_service.register("dave@example.com", "correctpass", "Dave")
with pytest.raises(AuthError):
await auth_service.login("dave@example.com", "wrongpass")
async def test_login_unknown_email_raises(self, auth_service: AuthService) -> None:
with pytest.raises(AuthError):
await auth_service.login("nobody@example.com", "anything")
class TestAuthServiceTokens:
async def test_access_token_round_trip(self, auth_service: AuthService) -> None:
user, _ = await auth_service.register("eve@example.com", "pass1234", "Eve")
token = auth_service.create_access_token(user.id)
decoded_user = await auth_service.get_user_from_token(token)
assert decoded_user.id == user.id
async def test_refresh_token_issues_new_access_token(self, auth_service: AuthService) -> None:
user, _ = await auth_service.register("frank@example.com", "pass5678", "Frank")
refresh = auth_service.create_refresh_token(user.id)
access = await auth_service.refresh_access_token(refresh)
decoded = await auth_service.get_user_from_token(access)
assert decoded.id == user.id
async def test_using_refresh_as_access_raises_unauthorized(
self, auth_service: AuthService
) -> None:
user, _ = await auth_service.register("grace@example.com", "pass9012", "Grace")
refresh = auth_service.create_refresh_token(user.id)
with pytest.raises(UnauthorizedError):
await auth_service.get_user_from_token(refresh)
async def test_invalid_token_raises_unauthorized(self, auth_service: AuthService) -> None:
with pytest.raises(UnauthorizedError):
await auth_service.get_user_from_token("not.a.valid.jwt")