Files
mtusi2026lab5/student-tests/test_outbox_publisher.py
2026-11-24 17:58:42 +03:00

90 lines
3.1 KiB
Python

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