Files
mtusi2026lab6/student-tests/pipeline_critical.py
T
2026-11-06 11:12:38 +03:00

118 lines
5.0 KiB
Python

"""Offline regression checks for delivery and terminal-state safety."""
import asyncio
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from io import BytesIO
import json
from pathlib import Path
import sys
from types import SimpleNamespace
import unittest
from unittest.mock import AsyncMock, MagicMock, patch
from uuid import uuid4
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from src.storage.postgres import PostgresStore
from src.worker import process_locked as process, settle_delivery
from concurrent.futures import Future
from src.broker import _publish_to
class CriticalTests(unittest.IsolatedAsyncioTestCase):
def test_failed_or_unrecorded_work_is_requeued(self):
for result in (False, None, RuntimeError('database unavailable')):
future, channel = Future(), MagicMock()
if isinstance(result, Exception):
future.set_exception(result)
else:
future.set_result(result)
settle_delivery(channel, 7, future)
channel.basic_ack.assert_not_called()
channel.basic_nack.assert_called_once_with(7, requeue=True)
def test_durable_success_is_acked(self):
future, channel = Future(), MagicMock()
future.set_result(True)
settle_delivery(channel, 7, future)
channel.basic_ack.assert_called_once_with(7)
channel.basic_nack.assert_not_called()
async def test_outbox_decodes_jsonb(self):
store = PostgresStore('unused')
store._pool = AsyncMock()
payload = {'type': 'attachment.process.v1', 'attachment_id': str(uuid4())}
store.pool.fetch.return_value = [{'id': uuid4(), 'payload': json.dumps(payload)}]
event, = await store.due_outbox_events()
self.assertEqual(json.loads(json.dumps(event['payload'])), payload)
async def run_processing(self, committed):
store, s3 = AsyncMock(), AsyncMock()
stamp = datetime.now(timezone.utc)
store.claim_attachment_job.return_value = {
'claim_time': stamp, 'staging_key': 'staging/test',
'content_type': 'image/png', 'size_bytes': 1, 'sha256': 'unused',
}
store.complete_attachment_job.return_value = committed
store.ready_seconds.return_value = 0.25
s3.settings = SimpleNamespace(max_pixels=40000000)
s3.download_key.return_value = b'fixture'
s3.delete.side_effect = RuntimeError('storage temporarily unavailable')
payload = {'attachment_id': str(uuid4())}
with patch('src.worker.render_isolated', return_value=[('thumbnail', b'jpeg', 'image/jpeg', 1, 1)]):
outcome = await process(store, s3, payload, 60)
self.assertEqual(outcome, "success" if committed else "skipped")
self.assertEqual(store.complete_attachment_job.call_args.args[-1], stamp)
return store, s3
async def test_cleanup_error_does_not_retry_ready(self):
store, s3 = await self.run_processing(True)
s3.delete.assert_awaited_once()
store.retry_attachment_job.assert_not_awaited()
async def test_stale_completion_keeps_staging(self):
_, s3 = await self.run_processing(False)
s3.delete.assert_not_awaited()
async def test_duplicate_is_skipped_not_successful(self):
store, s3 = AsyncMock(), AsyncMock()
store.claim_attachment_job.return_value = None
result = await process(store, s3, {'attachment_id': str(uuid4())}, 60)
self.assertEqual(result, 'skipped')
store.complete_attachment_job.assert_not_awaited()
s3.copy.assert_not_awaited()
async def test_stale_claim_cannot_publish_metadata(self):
store = PostgresStore('unused')
connection = AsyncMock()
connection.fetchval.return_value = None
@asynccontextmanager
async def context():
yield connection
connection.transaction = context
store._pool = SimpleNamespace(acquire=context)
self.assertFalse(await store.complete_attachment_job(uuid4(), 'original', [], datetime.now(timezone.utc)))
connection.execute.assert_not_awaited()
async def test_retry_of_terminal_or_stale_attempt_is_noop(self):
store = PostgresStore('unused')
connection = AsyncMock()
connection.fetchrow.return_value = None
@asynccontextmanager
async def context():
yield connection
connection.transaction = context
store._pool = SimpleNamespace(acquire=context)
self.assertFalse(await store.retry_attachment_job(uuid4(), 5, 1, datetime.now(timezone.utc)))
connection.execute.assert_not_awaited()
def test_dlq_waits_for_publisher_confirm(self):
connection = MagicMock()
with patch('src.broker._connection', return_value=connection):
_publish_to('dlq', {'failure': 'invalid_job'})
connection.channel.return_value.confirm_delivery.assert_called_once()
self.assertTrue(connection.channel.return_value.basic_publish.call_args.kwargs['mandatory'])
if __name__ == '__main__':
unittest.main()