Files
mtusi2026lab6/service-tests/unit/test_unit_of_work.py
T
ricoromaandClaude Opus 5.5 9cc6c0c7a6 chore: port lab 5 solution into the lab 6 skeleton
Source: mtusi2026lab5-safronov, solution/bvt2301-safronov, 046ec9e.
Contracts, public tests and evidence of lab 5 are not carried over.
The compose project, image and CI prefix are renamed to lab6; the first
broker start defect is recorded in KNOWN_ISSUES.md; PLAN.md outlines the
OpenSpec changes of lab 6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 04:46:56 +03:00

162 lines
4.8 KiB
Python

"""Спек `unit-of-work`: граница транзакции на фейке, те же правила базового
класса, что у настоящей единицы работы."""
from dataclasses import replace
from datetime import UTC, datetime
from uuid import uuid4
import pytest
from fakes import FakeDatabase, FakeUnitOfWork
from src.core import exceptions
from src.core.ports.uow import UnitOfWorkError
from src.schemas.dataclasses import UserFullDTO
pytestmark = pytest.mark.anyio
NOW = datetime(2026, 1, 1, tzinfo=UTC)
def _user() -> UserFullDTO:
return UserFullDTO(
id=uuid4(),
username=f"u{uuid4().hex[:8]}",
display_name="User",
created_at=NOW,
)
async def _found(database: FakeDatabase, username: str) -> bool:
async with FakeUnitOfWork(database) as other:
found = await other.users.get_user_credentials(username=username)
return found is not None
async def test_exit_without_commit_rolls_back(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
"""Сценарий «Выход без фиксации»."""
user = _user()
async with uow:
await uow.users.insert_user(user=user, password_hash="h")
assert not await _found(database, user.username)
async def test_exception_rolls_back_and_propagates(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
"""Сценарий «Исключение внутри блока»."""
user = _user()
with pytest.raises(exceptions.UsernameTaken):
async with uow:
await uow.users.insert_user(user=user, password_hash="h")
raise exceptions.UsernameTaken
assert not await _found(database, user.username)
async def test_commit_is_visible_to_other_unit(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
"""Сценарий «Фиксация»."""
user = _user()
async with uow:
await uow.users.insert_user(user=user, password_hash="h")
await uow.commit()
assert await _found(database, user.username)
async def test_repo_after_commit_is_an_error(uow: FakeUnitOfWork) -> None:
"""Сценарий «Работа после фиксации»."""
async with uow:
await uow.commit()
with pytest.raises(UnitOfWorkError):
_ = uow.users
async def test_second_commit_is_an_error(uow: FakeUnitOfWork) -> None:
async with uow:
await uow.commit()
with pytest.raises(UnitOfWorkError):
await uow.commit()
async def test_nested_block_is_an_error(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
"""Сценарий «Вложенный блок»: второго блока нет."""
with pytest.raises(UnitOfWorkError):
async with uow, uow:
pass
assert database.events.count("enter") == 1
async def test_repo_outside_block_is_an_error(uow: FakeUnitOfWork) -> None:
"""Сценарий «Repo вне блока»: и до входа, и после выхода."""
with pytest.raises(UnitOfWorkError):
_ = uow.users
async with uow:
pass
with pytest.raises(UnitOfWorkError):
_ = uow.users
async def test_commit_outside_block_is_an_error(uow: FakeUnitOfWork) -> None:
with pytest.raises(UnitOfWorkError):
await uow.commit()
async def test_failed_commit_ends_block_and_rolls_back(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
user = _user()
database.fail_commit = exceptions.ServiceUnavailable()
with pytest.raises(exceptions.ServiceUnavailable):
async with uow:
await uow.users.insert_user(user=user, password_hash="h")
await uow.commit()
assert not await _found(database, user.username)
async def test_block_can_reopen_and_counts_entries(
uow: FakeUnitOfWork,
) -> None:
async with uow:
pass
async with uow:
await uow.commit()
assert uow.blocks_opened == 2
async def test_rollback_restores_and_ends_block(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
user = _user()
async with uow:
await uow.users.insert_user(user=user, password_hash="h")
await uow.rollback()
with pytest.raises(UnitOfWorkError):
_ = uow.users
assert not await _found(database, user.username)
async def test_snapshot_returns_previous_row(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
"""Откат возвращает снимок, а не только убирает новое."""
user = _user()
async with uow:
await uow.users.insert_user(user=user, password_hash="h")
await uow.commit()
database.users[user.id] = user
before = database.users[user.id]
async with uow:
database.users[user.id] = replace(user, display_name="Changed")
assert database.users[user.id] == before