Лабораторная 5

This commit is contained in:
2026-11-24 17:58:42 +03:00
parent 276dbdad8a
commit 3938900ec6
40 changed files with 3130 additions and 27 deletions
+87
View File
@@ -0,0 +1,87 @@
import json
import unittest
from contextlib import contextmanager
from datetime import datetime, timezone
from unittest.mock import patch
from src.worker import PermanentJobError, TransientJobError, record_failure
class FakeDatabase:
def __init__(self, attempt):
self.row = {
"id": "job-id",
"attachment_id": "9c554d5e-2d59-4c10-ae40-7f6f7aef6350",
"attempt": attempt,
"pipeline_version": 2,
"created_at": datetime.now(timezone.utc),
"status": "processing",
}
self.job_status = "processing"
self.attachment_status = "processing"
self.attempt_records = []
self.outbox = []
@contextmanager
def transaction(self):
yield self
def execute(self, query, params=()):
statement = " ".join(query.split())
if statement.startswith("SELECT j.id,j.attachment_id,j.attempt"):
self.result = self.row
elif statement.startswith("INSERT INTO job_attempts"):
self.attempt_records.append(params)
elif statement.startswith("UPDATE jobs SET status='failed'"):
self.job_status = "failed"
elif statement.startswith("UPDATE attachments SET status='failed'"):
self.attachment_status = "failed"
elif statement.startswith("INSERT INTO outbox"):
self.outbox.append({
"event_type": params[1],
"payload": json.loads(params[2]),
})
else:
raise AssertionError(f"Unexpected SQL in test fake: {statement}")
return self
def fetchone(self):
return self.result
class FailureRegistryTests(unittest.TestCase):
def make_job(self, db):
return {
"job_id": db.row["id"],
"attachment_id": db.row["attachment_id"],
"attempt": db.row["attempt"],
"pipeline_version": db.row["pipeline_version"],
}
def test_permanent_failure_is_recorded_and_sent_to_failed_route(self):
db = FakeDatabase(attempt=1)
with patch("src.worker.transaction", db.transaction):
record_failure(self.make_job(db), PermanentJobError("invalid_image"))
self.assertEqual(db.job_status, "failed")
self.assertEqual(db.attachment_status, "failed")
self.assertEqual(db.attempt_records[0][2:], ("failed", "invalid_image"))
self.assertEqual(db.outbox[0]["event_type"], "attachment.failed")
self.assertEqual(db.outbox[0]["payload"]["type"], "attachment.failed.v1")
self.assertEqual(db.outbox[0]["payload"]["error_code"], "invalid_image")
def test_transient_failure_at_attempt_limit_is_terminal(self):
db = FakeDatabase(attempt=5)
with patch("src.worker.transaction", db.transaction):
record_failure(self.make_job(db), TransientJobError("temporary"))
self.assertEqual(db.job_status, "failed")
self.assertEqual(db.attempt_records[0][2:], ("failed", "retry_exhausted"))
self.assertEqual(db.outbox[0]["event_type"], "attachment.failed")
self.assertEqual(db.outbox[0]["payload"]["error_code"], "retry_exhausted")
if __name__ == "__main__":
unittest.main()
+68
View File
@@ -0,0 +1,68 @@
import io
import unittest
from PIL import Image
from src.worker import crop, decode_image, optimized, thumbnail
def encoded_image(image, image_format="PNG", **save_options):
buffer = io.BytesIO()
image.save(buffer, format=image_format, **save_options)
return buffer.getvalue()
class ImageVariantTests(unittest.TestCase):
def test_variants_follow_contract_dimensions_and_formats(self):
image = decode_image(encoded_image(Image.new("RGB", (320, 200), "navy")))
thumb_bytes, thumb_width, thumb_height = thumbnail(image)
crop_bytes, crop_width, crop_height = crop(image)
webp_bytes, webp_width, webp_height = optimized(image)
self.assertEqual((thumb_width, thumb_height), (256, 160))
self.assertEqual((crop_width, crop_height), (128, 128))
self.assertEqual((webp_width, webp_height), (320, 200))
self.assertEqual(Image.open(io.BytesIO(thumb_bytes)).format, "JPEG")
self.assertEqual(Image.open(io.BytesIO(crop_bytes)).format, "JPEG")
self.assertEqual(Image.open(io.BytesIO(webp_bytes)).format, "WEBP")
self.assertEqual(Image.open(io.BytesIO(webp_bytes)).getexif(), {})
def test_small_optimized_image_is_not_upscaled(self):
image = decode_image(encoded_image(Image.new("RGB", (64, 32), "white")))
_, width, height = optimized(image)
self.assertEqual((width, height), (64, 32))
def test_large_optimized_image_fits_inside_1280(self):
image = decode_image(encoded_image(Image.new("RGB", (1600, 800), "white")))
_, width, height = optimized(image)
self.assertEqual((width, height), (1280, 640))
def test_crop_and_thumbnail_composite_transparency_on_white(self):
image = decode_image(encoded_image(Image.new("RGBA", (320, 200), (0, 0, 0, 0))))
thumb_bytes, _, _ = thumbnail(image)
crop_bytes, _, _ = crop(image)
self.assertEqual(Image.open(io.BytesIO(thumb_bytes)).getpixel((0, 0)), (255, 255, 255))
self.assertEqual(Image.open(io.BytesIO(crop_bytes)).getpixel((0, 0)), (255, 255, 255))
def test_decode_applies_exif_orientation(self):
exif = Image.Exif()
exif[274] = 6
data = encoded_image(Image.new("RGB", (320, 200), "navy"), "JPEG", exif=exif)
image = decode_image(data)
self.assertEqual(image.size, (200, 320))
def test_decode_rejects_non_image_payload(self):
with self.assertRaises((ValueError, OSError)):
decode_image(b"not an image")
if __name__ == "__main__":
unittest.main()
+60
View File
@@ -0,0 +1,60 @@
import json
import unittest
from contextlib import contextmanager
from datetime import datetime, timezone
from unittest.mock import patch
from src.worker import recover_expired_leases
class FakeDatabase:
def __init__(self):
self.job = {
"id": "job-id",
"attachment_id": "attachment-id",
"pipeline_version": 2,
"created_at": datetime.now(timezone.utc),
"attempt": 1,
}
self.job_status = "processing"
self.attachment_status = "processing"
self.outbox = []
@contextmanager
def transaction(self):
yield self
def execute(self, query, params=()):
statement = " ".join(query.split())
if statement.startswith("SELECT j.id,j.attachment_id,j.pipeline_version"):
self.rows = [self.job] if self.job_status == "processing" else []
elif statement.startswith("UPDATE jobs SET status='queued'"):
self.job_status = "queued"
elif statement.startswith("UPDATE attachments SET status='queued'"):
self.attachment_status = "queued"
elif statement.startswith("INSERT INTO outbox"):
self.outbox.append(json.loads(params[2]))
else:
raise AssertionError(f"Unexpected SQL in test fake: {statement}")
return self
def fetchall(self):
return self.rows
class LeaseRecoveryTests(unittest.TestCase):
def test_expired_lease_is_requeued_with_the_next_attempt(self):
db = FakeDatabase()
with patch("src.worker.transaction", db.transaction):
recover_expired_leases()
self.assertEqual(db.job_status, "queued")
self.assertEqual(db.attachment_status, "queued")
self.assertEqual(len(db.outbox), 1)
self.assertEqual(db.outbox[0]["attempt"], 2)
self.assertEqual(db.outbox[0]["pipeline_version"], 2)
if __name__ == "__main__":
unittest.main()
+89
View File
@@ -0,0 +1,89 @@
import json
import unittest
from contextlib import contextmanager
from unittest.mock import patch
from src.worker import publish_one_outbox_event
class FakeDatabase:
def __init__(self, payload=None):
self.row = None if payload is None else {
"id": "outbox-id",
"event_type": "attachment.process",
"payload": json.dumps(payload),
"available": True,
"published_at": None,
"publish_attempt": 0,
}
@contextmanager
def transaction(self):
snapshot = None if self.row is None else dict(self.row)
try:
yield self
except Exception:
self.row = snapshot
raise
def execute(self, query, params=()):
statement = " ".join(query.split())
if statement.startswith("SELECT id,event_type,payload"):
self.result = (
{key: self.row[key] for key in ("id", "event_type", "payload")}
if self.row and self.row["available"] and self.row["published_at"] is None
else None
)
elif statement.startswith("UPDATE outbox SET publish_attempt"):
self.row["publish_attempt"] += 1
elif statement.startswith("UPDATE outbox SET published_at=NOW()"):
self.row["published_at"] = "confirmed"
else:
raise AssertionError(f"Unexpected SQL in test fake: {statement}")
return self
def fetchone(self):
return self.result
class OutboxPublisherTests(unittest.TestCase):
def test_published_timestamp_is_set_only_after_broker_confirm(self):
payload = {"job_id": "job-id", "type": "attachment.process.v1"}
db = FakeDatabase(payload)
published = []
def confirm(message, routing_key):
self.assertEqual(db.row["published_at"], None)
self.assertEqual(db.row["publish_attempt"], 1)
published.append((message, routing_key))
with patch("src.worker.transaction", db.transaction), \
patch("src.worker.publish", side_effect=confirm):
self.assertTrue(publish_one_outbox_event())
self.assertEqual(published, [(payload, "attachment.process")])
self.assertEqual(db.row["published_at"], "confirmed")
def test_publish_failure_leaves_row_unpublished_for_retry(self):
db = FakeDatabase({"job_id": "job-id"})
with patch("src.worker.transaction", db.transaction), \
patch("src.worker.publish", side_effect=RuntimeError("broker unavailable")):
with self.assertRaisesRegex(RuntimeError, "broker unavailable"):
publish_one_outbox_event()
self.assertIsNone(db.row["published_at"])
self.assertEqual(db.row["publish_attempt"], 0)
def test_empty_outbox_does_not_publish(self):
db = FakeDatabase()
with patch("src.worker.transaction", db.transaction), \
patch("src.worker.publish") as publish:
self.assertFalse(publish_one_outbox_event())
publish.assert_not_called()
if __name__ == "__main__":
unittest.main()
+195
View File
@@ -0,0 +1,195 @@
import hashlib
import io
import json
import unittest
from contextlib import contextmanager
from datetime import datetime, timezone
from unittest.mock import patch
from PIL import Image
from src.pipeline import CURRENT_PIPELINE_VERSION, pipeline_qualities
from src.worker import PermanentJobError, TransientJobError, process, record_failure
class InjectedCrash(BaseException):
pass
class FakeDatabase:
def __init__(self, attachment_id, job_id, image_bytes, pipeline_version=2):
self.attachment_id = attachment_id
self.job_id = job_id
self.image_bytes = image_bytes
self.staging_key = f"staging/{attachment_id}/original"
self.content_type = "image/png"
self.sha256 = hashlib.sha256(image_bytes).hexdigest()
self.attachment_status = "queued"
self.job_status = "queued"
self.attempt = 0
self.pipeline_version = pipeline_version
self.created_at = datetime.now(timezone.utc)
self.outbox = []
self.attempts = []
self.variants = []
@contextmanager
def transaction(self):
yield self
def execute(self, query, params=()):
statement = " ".join(query.split())
if statement.startswith("SELECT a.staging_key"):
if str(params[0]) != self.attachment_id or str(params[1]) != self.job_id:
self.result = None
else:
self.result = {
"staging_key": self.staging_key,
"status": self.attachment_status,
"content_type": self.content_type,
"size_bytes": len(self.image_bytes),
"sha256": self.sha256,
"job_status": self.job_status,
"lease_until": None,
"attempt": self.attempt,
"pipeline_version": self.pipeline_version,
}
elif statement.startswith("UPDATE attachments SET status='processing'"):
self.attachment_status = "processing"
elif statement.startswith("UPDATE jobs SET attempt=attempt+1"):
self.attempt += 1
self.job_status = "processing"
elif statement.startswith("UPDATE attachments SET status='ready'"):
self.attachment_status = "ready"
self.variants = json.loads(params[1])
elif statement.startswith("UPDATE jobs SET status='ready'"):
self.job_status = "ready"
elif statement.startswith("SELECT j.id,j.attachment_id,j.attempt"):
self.result = {
"id": self.job_id,
"attachment_id": self.attachment_id,
"attempt": self.attempt,
"pipeline_version": self.pipeline_version,
"created_at": self.created_at,
"status": self.attachment_status,
}
elif statement.startswith("INSERT INTO job_attempts"):
self.attempts.append(params)
elif statement.startswith("UPDATE jobs SET status='queued'"):
self.job_status = "queued"
elif statement.startswith("UPDATE attachments SET status='queued'"):
self.attachment_status = "queued"
elif statement.startswith("INSERT INTO outbox"):
payload = params[2]
self.outbox.append(json.loads(payload) if isinstance(payload, str) else payload)
else:
raise AssertionError(f"Unexpected SQL in test fake: {statement}")
return self
def fetchone(self):
return self.result
class FakeStorage:
def __init__(self, image_bytes):
self.image_bytes = image_bytes
def get_object(self, **kwargs):
return {"Body": io.BytesIO(self.image_bytes)}
def png_fixture():
buffer = io.BytesIO()
Image.new("RGB", (320, 200), "navy").save(buffer, format="PNG")
return buffer.getvalue()
class PipelineFaultTests(unittest.TestCase):
def test_pipeline_versions_are_explicit_and_quality_is_versioned(self):
self.assertEqual(CURRENT_PIPELINE_VERSION, 2)
self.assertEqual(pipeline_qualities(1), (88, 82))
self.assertEqual(pipeline_qualities(2), (86, 80))
def make_job(self, db, attempt=1, pipeline_version=2):
return {
"job_id": db.job_id,
"attachment_id": db.attachment_id,
"attempt": attempt,
"pipeline_version": pipeline_version,
}
def run_process(self, db, objects, job):
def put_object(_bucket, key, data, _content_type):
objects[key] = data
with patch("src.worker.transaction", db.transaction), \
patch("src.worker.s3_client", return_value=FakeStorage(db.image_bytes)), \
patch("src.worker.put_object", side_effect=put_object), \
patch.dict("os.environ", {"S3_BUCKET": "test-bucket"}):
process(job)
def test_crash_before_and_after_object_write_retries_idempotently(self):
for stage in ("before_original_put", "after_original_put"):
with self.subTest(stage=stage):
image_bytes = png_fixture()
attachment_id = "9c554d5e-2d59-4c10-ae40-7f6f7aef6350"
job_id = "8f4b65d8-091d-423f-9565-d6ab08c8814c"
db = FakeDatabase(attachment_id, job_id, image_bytes)
objects = {}
first_job = self.make_job(db)
injection = f"{attachment_id}:1:{stage}"
with patch("src.worker.transaction", db.transaction), \
patch("src.worker.s3_client", return_value=FakeStorage(image_bytes)), \
patch("src.worker.put_object", side_effect=lambda _b, key, data, _c: objects.__setitem__(key, data)), \
patch.dict("os.environ", {"S3_BUCKET": "test-bucket", "WORKER_FAULT_INJECTION": injection}), \
patch("src.worker.os._exit", side_effect=InjectedCrash):
with self.assertRaises(InjectedCrash):
process(first_job)
original_key = f"final/{attachment_id}/original"
self.assertEqual(original_key in objects, stage == "after_original_put")
self.assertEqual(db.job_status, "processing")
with patch("src.worker.transaction", db.transaction):
record_failure(first_job, TransientJobError("worker_process_failed"))
self.assertEqual(db.outbox[0]["attempt"], 2)
# The redelivered first attempt is stale; the scheduled retry owns the next attempt.
self.run_process(db, objects, first_job)
self.assertEqual(db.job_status, "queued")
self.run_process(db, objects, db.outbox[0])
self.assertEqual(db.job_status, "ready")
self.assertEqual(db.attachment_status, "ready")
self.assertEqual(set(objects), {
original_key,
f"final/{attachment_id}/thumbnail",
f"final/{attachment_id}/crop",
f"final/{attachment_id}/optimized",
})
objects_before_duplicate = dict(objects)
self.run_process(db, objects, db.outbox[0])
self.assertEqual(objects, objects_before_duplicate)
def test_old_pipeline_message_cannot_overwrite_new_version(self):
image_bytes = png_fixture()
attachment_id = "9c554d5e-2d59-4c10-ae40-7f6f7aef6350"
job_id = "8f4b65d8-091d-423f-9565-d6ab08c8814c"
db = FakeDatabase(attachment_id, job_id, image_bytes, pipeline_version=2)
objects = {}
with self.assertRaises(PermanentJobError):
self.run_process(db, objects, self.make_job(db, pipeline_version=3))
self.run_process(db, objects, self.make_job(db, pipeline_version=1))
self.assertEqual(objects, {})
self.assertEqual(db.job_status, "queued")
self.run_process(db, objects, self.make_job(db, pipeline_version=2))
self.assertEqual(db.job_status, "ready")
self.assertTrue(objects)
if __name__ == "__main__":
unittest.main()
+81
View File
@@ -0,0 +1,81 @@
import json
import unittest
from contextlib import contextmanager
from datetime import datetime, timezone
from unittest.mock import patch
from src.replay import replay_failed_attachment
class FakeDatabase:
def __init__(self, status="failed"):
self.row = {
"id": "job-id",
"attachment_id": "9c554d5e-2d59-4c10-ae40-7f6f7aef6350",
"pipeline_version": 1,
"created_at": datetime.now(timezone.utc),
"status": status,
"attachment_status": status,
}
self.job_status = status
self.attachment_status = status
self.attempt = 5
self.replay_count = 0
self.audit = []
self.outbox = []
@contextmanager
def transaction(self):
yield self
def execute(self, query, params=()):
statement = " ".join(query.split())
if statement.startswith("SELECT j.id,j.attachment_id,j.pipeline_version"):
self.result = self.row if str(params[0]) == self.row["attachment_id"] else None
elif statement.startswith("UPDATE jobs"):
self.job_status = "queued"
self.attempt = 0
self.replay_count += 1
elif statement.startswith("UPDATE attachments"):
self.attachment_status = "queued"
elif statement.startswith("INSERT INTO job_replays"):
self.audit.append(params)
elif statement.startswith("INSERT INTO outbox"):
self.outbox.append(json.loads(params[1]))
else:
raise AssertionError(f"Unexpected SQL in test fake: {statement}")
return self
def fetchone(self):
return self.result
class ReplayTests(unittest.TestCase):
def test_failed_attachment_replay_is_audited_and_uses_transactional_outbox(self):
db = FakeDatabase()
with patch("src.replay.transaction", db.transaction):
result = replay_failed_attachment(db.row["attachment_id"], " operator-1 ")
self.assertEqual(result["status"], "queued")
self.assertEqual(db.job_status, "queued")
self.assertEqual(db.attachment_status, "queued")
self.assertEqual(db.attempt, 0)
self.assertEqual(db.replay_count, 1)
self.assertEqual(db.audit[0][3], "operator-1")
self.assertEqual(db.outbox[0]["pipeline_version"], 1)
self.assertEqual(db.outbox[0]["attempt"], 1)
def test_ready_attachment_cannot_be_replayed(self):
db = FakeDatabase(status="ready")
with patch("src.replay.transaction", db.transaction):
with self.assertRaisesRegex(ValueError, "only a failed attachment"):
replay_failed_attachment(db.row["attachment_id"], "operator-1")
self.assertEqual(db.replay_count, 0)
self.assertEqual(db.outbox, [])
if __name__ == "__main__":
unittest.main()
+50
View File
@@ -0,0 +1,50 @@
import unittest
from unittest.mock import Mock, patch
from src.worker import handle_message, retry_delay
class RetryPolicyTests(unittest.TestCase):
def test_exponential_backoff_is_jittered_within_attempt_window(self):
with patch("src.worker.RETRY_BASE_SECONDS", 1), patch("src.worker.RETRY_MAX_SECONDS", 60):
delay = retry_delay(4)
self.assertGreaterEqual(delay, 4)
self.assertLessEqual(delay, 8)
def test_backoff_respects_configured_cap(self):
with patch("src.worker.RETRY_BASE_SECONDS", 1), patch("src.worker.RETRY_MAX_SECONDS", 20):
delay = retry_delay(10)
self.assertGreaterEqual(delay, 10)
self.assertLessEqual(delay, 20)
def test_malformed_job_is_dead_lettered_without_processing(self):
channel = Mock()
body = b'{"schema_version":1,"type":"attachment.process.v1","job_id":"bad","attachment_id":"bad","pipeline_version":1,"attempt":1,"created_at":"now"}'
with patch("src.worker.process_with_timeout") as process:
handle_message(channel, 7, body)
channel.basic_nack.assert_called_once_with(delivery_tag=7, requeue=False)
process.assert_not_called()
def test_valid_job_is_acknowledged_after_processing(self):
channel = Mock()
job_id = "1b671a64-40d5-491e-99b0-da01ff1f3341"
attachment_id = "0e8c4c49-6d3e-4d3e-8ca0-cf4ed9a36e9a"
body = (
'{"schema_version":1,"type":"attachment.process.v1",'
f'"job_id":"{job_id}","attachment_id":"{attachment_id}",'
'"pipeline_version":1,"attempt":1,"created_at":"2026-01-01T00:00:00Z"}'
).encode()
with patch("src.worker.process_with_timeout"):
handle_message(channel, 8, body)
channel.basic_ack.assert_called_once_with(delivery_tag=8)
channel.basic_nack.assert_not_called()
if __name__ == "__main__":
unittest.main()
+72
View File
@@ -0,0 +1,72 @@
import unittest
from contextlib import contextmanager
from unittest.mock import patch
from src.worker import cleanup_staging
class FakeDatabase:
def __init__(self, status):
self.status = status
self.staging_deleted_at = None
@contextmanager
def transaction(self):
yield self
def execute(self, query, params=()):
statement = " ".join(query.split())
if statement.startswith("SELECT id,staging_key"):
self.result = (
{"id": "attachment-id", "staging_key": "staging/attachment-id/original"}
if self.status == "ready" and self.staging_deleted_at is None
else None
)
elif statement.startswith("UPDATE attachments SET staging_deleted_at=NOW()"):
self.staging_deleted_at = "deleted"
else:
raise AssertionError(f"Unexpected SQL in test fake: {statement}")
return self
def fetchone(self):
return self.result
class FakeStorage:
def __init__(self):
self.deleted = []
def delete_object(self, **kwargs):
self.deleted.append(kwargs)
class StagingCleanupTests(unittest.TestCase):
def test_only_ready_objects_are_deleted_and_cleanup_is_idempotent(self):
db = FakeDatabase(status="ready")
storage = FakeStorage()
with patch("src.worker.transaction", db.transaction), \
patch("src.worker.s3_client", return_value=storage), \
patch.dict("os.environ", {"S3_BUCKET": "test-bucket"}):
self.assertEqual(cleanup_staging(), 1)
self.assertEqual(cleanup_staging(), 0)
self.assertEqual(storage.deleted, [{
"Bucket": "test-bucket",
"Key": "staging/attachment-id/original",
}])
def test_processing_attachment_is_not_cleaned(self):
db = FakeDatabase(status="processing")
storage = FakeStorage()
with patch("src.worker.transaction", db.transaction), \
patch("src.worker.s3_client", return_value=storage), \
patch.dict("os.environ", {"S3_BUCKET": "test-bucket"}):
self.assertEqual(cleanup_staging(), 0)
self.assertEqual(storage.deleted, [])
if __name__ == "__main__":
unittest.main()