"""Проверка компенсации объекта при ошибке commit метаданных.""" import asyncio from datetime import datetime, timezone from pathlib import Path from uuid import uuid4 import pytest from app.domain.errors import Conflict from app.domain.models import Attachment from app.domain.models import User from app.services.attachments import AttachmentService class FailingRepository: async def chat_exists_for_member(self, chat_id, user_id): return True async def create(self, **kwargs): raise RuntimeError('injected database commit failure') class RecordingStorage: def __init__(self): self.put_key = None self.removed_key = None async def put(self, key, source, length, content_type): self.put_key = key async def remove(self, key): self.removed_key = key class FailedAttachmentRepository: def __init__(self, attachment): self.attachment = attachment async def get_for_member(self, attachment_id, user_id): return self.attachment class StorageThatMustNotBeRead: async def get(self, key): raise AssertionError('failed attachment must not read S3') def test_uploaded_object_is_removed_when_metadata_commit_fails(): """Удаляет объект после ошибки сохранения метаданных.""" storage = RecordingStorage() service = AttachmentService(FailingRepository(), storage, 10 * 1024 * 1024, 40_000_000) actor = User(uuid4(), 'tester', 'Tester', datetime.now(timezone.utc)) content = (Path(__file__).parent / 'fixtures/sample.png').read_bytes() async def chunks(): yield content with pytest.raises(RuntimeError, match='injected database commit failure'): asyncio.run( service.upload( actor, uuid4(), 'sample.png', 'image/png', chunks(), ) ) assert storage.put_key is not None assert storage.removed_key == storage.put_key def test_failed_attachment_content_returns_conflict_without_s3_read(): """Возвращает конфликт для ошибочного вложения без чтения S3.""" now = datetime.now(timezone.utc) attachment = Attachment( id=uuid4(), chat_id=uuid4(), owner_id=uuid4(), filename='missing.png', object_key=f'originals/{uuid4()}', content_type='image/png', size_bytes=1, sha256='0' * 64, width=1, height=1, status='failed', error_code='original_missing', created_at=now, updated_at=now, ) service = AttachmentService( FailedAttachmentRepository(attachment), StorageThatMustNotBeRead(), 1, 1 ) actor = User(uuid4(), 'tester', 'Tester', now) with pytest.raises(Conflict, match='недоступен'): asyncio.run(service.content(actor, attachment.id))