refactor
This commit is contained in:
@@ -0,0 +1,127 @@
|
||||
"""Contract, isolated-render and benchmark regressions without Docker."""
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import importlib.util
|
||||
from io import BytesIO
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from PIL import Image
|
||||
from src.worker import variants, render_isolated, PermanentFailure
|
||||
from src.storage.postgres import PostgresStore
|
||||
from src.reconcile import scan
|
||||
from src.errors import ApiError
|
||||
|
||||
|
||||
def png(width, height):
|
||||
buffer = BytesIO()
|
||||
Image.new('RGBA', (width, height), (255, 0, 0, 0)).save(buffer, 'PNG')
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
class Regressions(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_failed_attachment_is_rejected(self):
|
||||
store, connection = PostgresStore('unused'), AsyncMock()
|
||||
connection.fetchval.side_effect = [1, 1, 1]
|
||||
@asynccontextmanager
|
||||
async def context():
|
||||
yield connection
|
||||
connection.transaction = context
|
||||
store._pool = SimpleNamespace(acquire=context)
|
||||
with self.assertRaises(ApiError) as error:
|
||||
await store.create_message_idempotent(uuid4(), uuid4(), '', 'key', 86400, [uuid4()])
|
||||
self.assertEqual(error.exception.status_code, 409)
|
||||
connection.fetchrow.assert_not_awaited()
|
||||
|
||||
def test_floor_and_small_images(self):
|
||||
self.assertEqual(variants(png(300, 200))[0][3:], (256, 170))
|
||||
self.assertEqual(variants(png(200, 300))[0][3:], (170, 256))
|
||||
self.assertEqual(variants(png(10, 8))[0][3:], (10, 8))
|
||||
for name, data, mime, width, height in variants(png(300, 200)):
|
||||
with Image.open(BytesIO(data)) as image:
|
||||
self.assertEqual(image.size, (width, height))
|
||||
self.assertTrue(all(value > 240 for value in image.convert('RGB').getpixel((0, 0))))
|
||||
|
||||
def test_renderer_success_and_permanent_error(self):
|
||||
self.assertEqual(render_isolated(png(300, 200), 10)[0][3:], (256, 170))
|
||||
with self.assertRaises(PermanentFailure):
|
||||
render_isolated(b'not an image', 10)
|
||||
|
||||
def test_renderer_is_killed_on_deadline(self):
|
||||
started = time.monotonic()
|
||||
with self.assertRaises(TimeoutError):
|
||||
render_isolated(png(300, 200), .0001)
|
||||
self.assertLess(time.monotonic() - started, 2)
|
||||
|
||||
async def test_cleanup_retains_active_and_failed_staging(self):
|
||||
old = datetime.now(timezone.utc) - timedelta(days=2)
|
||||
db, s3 = AsyncMock(), AsyncMock()
|
||||
db.attachment_keys.return_value = {'staging/active': uuid4(), 'staging/failed': uuid4(), 'originals/ready': uuid4()}
|
||||
s3.list_with_pages.side_effect = [({'staging/active': old, 'staging/failed': old, 'staging/orphan': old}, 1),
|
||||
({'originals/ready': old}, 1), ({'variants/orphan': old}, 1)]
|
||||
report = await scan(SimpleNamespace(grace_seconds=60, apply=True, object_key=[]), db, s3)
|
||||
self.assertEqual(report['deleted'], ['staging/orphan', 'variants/orphan'])
|
||||
|
||||
async def test_permanent_failure_is_atomic_and_not_retried(self):
|
||||
store = PostgresStore('unused')
|
||||
connection = AsyncMock()
|
||||
connection.fetchrow.return_value = {'attempt': 1}
|
||||
@asynccontextmanager
|
||||
async def context():
|
||||
yield connection
|
||||
connection.transaction = context
|
||||
store._pool = SimpleNamespace(acquire=context)
|
||||
result = await store.retry_attachment_job(uuid4(), 5, 1, datetime.now(timezone.utc), 'invalid_image')
|
||||
self.assertFalse(result)
|
||||
self.assertEqual(connection.execute.await_count, 2)
|
||||
for call in connection.execute.call_args_list:
|
||||
self.assertIn("status='failed'", call.args[0])
|
||||
self.assertEqual(call.args[2], 'invalid_image')
|
||||
|
||||
def test_benchmark_partial_batch_and_recovery(self):
|
||||
spec = importlib.util.spec_from_file_location('track1', ROOT / 'scripts/track1.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
jobs, lock = {}, threading.Lock()
|
||||
class FakeClient:
|
||||
def __init__(self, *args, **kwargs): pass
|
||||
def bootstrap(self): return {}, {}, {}, {'id': str(uuid4())}
|
||||
def call(self, method, path, *args, **kwargs):
|
||||
if method == 'POST':
|
||||
key = str(uuid4())
|
||||
with lock: jobs[key] = {'id': key, 'status': 'ready', 'queue_wait_seconds': .01}
|
||||
return {'status': 202, 'json': {'id': key}}
|
||||
return {'json': {'status': 'ready'}}
|
||||
def attachment(self, *args): return {}, b''
|
||||
def wait_ready(self, *args, **kwargs): return {}
|
||||
def metrics(_):
|
||||
with lock:
|
||||
return {'jobs': list(jobs.values()), 'pending': 0, 'rss_bytes': 1000, 'concurrency': 2, 'prefetch': 2}
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
destination = str(Path(directory) / 'result.json')
|
||||
args = SimpleNamespace(run_name='test', workers=2, prefetch=2, max_pending=20, images=10,
|
||||
concurrency=8, size=8, max_ready_seconds=2, require_backpressure=False,
|
||||
output=destination, base_url=None, ca_file=None)
|
||||
info = {'Config': {'Env': ['MAX_PENDING_JOBS=20']}, 'HostConfig': {'Memory': 4096, 'NanoCpus': 2}}
|
||||
with patch.object(module, 'arguments', return_value=args), patch.object(module, 'Client', FakeClient), \
|
||||
patch.object(module, 'metrics', side_effect=metrics), patch.object(module, 'container_info', return_value=info), \
|
||||
patch.object(module, 'broker_depth', return_value={'messages_ready': 0, 'messages_unacknowledged': 0}):
|
||||
module.main()
|
||||
report = json.loads(Path(destination).read_text())
|
||||
self.assertEqual(report['results']['ready'], 10)
|
||||
self.assertTrue(report['results']['recovery_upload_ready'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user