Files
mtusi2026lab5/service-tests/unit/test_session_service.py
T
ricoromaandClaude Opus 5.5 6ba74b18f3 refactor: move services to a unit of work over repository ports
Services depend only on src/core/ports: async with self.uow is one
transaction, commit is explicit, leaving without it rolls back. A
connection is held per step, the JSON routers keep a shared request
deadline, and rollback runs under the block deadline. Adds
service-tests with fakes, a repo contract run on both the fake and SQL,
and make service_test / service_test_db. API, schema and settings are
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 23:14:16 +03:00

152 lines
4.7 KiB
Python

"""`SessionService`: вход двумя блоками, отказ одинаков, токен и отзыв."""
from datetime import timedelta
import pytest
from builders import user_dto
from fakes import FakeDatabase, FakeUnitOfWork
from src.core import exceptions, services
from src.core.services import session as session_module
from src.core.services.session import hash_token
from src.schemas import dataclasses
from src.utils.utc import utcnow
pytestmark = pytest.mark.anyio
PASSWORD = "password-1234"
@pytest.fixture(autouse=True)
def cheap_kdf(monkeypatch: pytest.MonkeyPatch, database: FakeDatabase) -> None:
async def verify_password(*, password: str, password_hash: str | None):
database.events.append("kdf")
return password_hash == f"hash:{password}"
monkeypatch.setattr(session_module, "verify_password", verify_password)
async def _user(uow: FakeUnitOfWork) -> dataclasses.UserFullDTO:
user = user_dto(username="alice")
async with uow:
await uow.users.insert_user(
user=user,
password_hash=f"hash:{PASSWORD}",
)
await uow.commit()
return user
async def test_login_two_blocks_kdf_outside(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
user = await _user(uow)
database.events.clear()
result = await services.SessionService(uow).login(
username="alice",
password=PASSWORD,
)
assert result.user == user
assert database.events == [
"enter",
"users.get_user_credentials",
"exit",
"kdf",
"enter",
"sessions.insert_session",
"commit",
"exit",
]
stored = next(iter(database.sessions.values()))
assert stored.token_hash == hash_token(result.token)
@pytest.mark.parametrize(
("username", "password"),
[("alice", "wrong-password"), ("unknown", PASSWORD)],
ids=["wrong_password", "unknown_user"],
)
async def test_login_failure_same_and_no_write_block(
uow: FakeUnitOfWork,
database: FakeDatabase,
username: str,
password: str,
) -> None:
await _user(uow)
database.events.clear()
with pytest.raises(exceptions.InvalidCredentials):
await services.SessionService(uow).login(
username=username,
password=password,
)
# неизвестный пользователь тоже проходит KDF, блока записи нет
assert "kdf" in database.events
assert database.events.count("enter") == 1
assert database.sessions == {}
async def test_authenticate_without_token_opens_no_block(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
with pytest.raises(exceptions.Unauthenticated):
await services.SessionService(uow).authenticate(token=None)
assert database.events == []
async def test_authenticate_valid_expired_unknown(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
user = await _user(uow)
service = services.SessionService(uow)
login = await service.login(username="alice", password=PASSWORD)
current = await service.authenticate(token=login.token)
assert current.user == user
with pytest.raises(exceptions.Unauthenticated):
await service.authenticate(token="unknown-token")
# истёкшая сессия
stored = next(iter(database.sessions.values()))
database.sessions[stored.id] = dataclasses.SessionFullDTO(
id=stored.id,
user_id=stored.user_id,
token_hash=stored.token_hash,
created_at=stored.created_at,
expires_at=utcnow() - timedelta(seconds=1),
)
with pytest.raises(exceptions.Unauthenticated):
await service.authenticate(token=login.token)
async def test_revoke_and_second_revoke(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
await _user(uow)
service = services.SessionService(uow)
login = await service.login(username="alice", password=PASSWORD)
current = await service.authenticate(token=login.token)
await service.revoke(session_id=current.id)
assert database.sessions == {}
# параллельный выход уже удалил: не ошибка
await service.revoke(session_id=current.id)
with pytest.raises(exceptions.Unauthenticated):
await service.authenticate(token=login.token)
async def test_database_failure_on_login_propagates(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
await _user(uow)
database.fail_on["sessions.insert_session"] = (
exceptions.ServiceUnavailable()
)
with pytest.raises(exceptions.ServiceUnavailable):
await services.SessionService(uow).login(
username="alice",
password=PASSWORD,
)
assert database.sessions == {}