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()