Files
mtusi2026lab4-fork/student-tests/test_compensation.py
T
2026-11-01 01:18:40 +03:00

61 lines
2.5 KiB
Python

"""Deterministic proof of compensation: S3 PUT succeeded but the metadata INSERT/COMMIT failed.
Needs: pip install -r requirements.txt httpx (no running services: S3, PostgreSQL are replaced by fakes)."""
import sys, unittest, uuid
from contextlib import contextmanager
from pathlib import Path
from unittest import mock
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(Path(__file__).parent))
import imagegen
from fastapi.testclient import TestClient
from src import main
import psycopg
class Compensation(unittest.TestCase):
def setUp(self):
self.puts, self.deletes = [], []
self.client = TestClient(main.app, raise_server_exceptions=False)
self.patches = [
mock.patch.object(main, "current_user", lambda r: {"id": uuid.uuid4()}),
mock.patch.object(main, "ensure_member", lambda a, c: None),
mock.patch.object(main, "s3_put", lambda key, spool, size, ct: self.puts.append(key)),
mock.patch.object(main, "s3_delete_quietly", lambda key: self.deletes.append(key)),
]
for p in self.patches: p.start()
self.url = f"/api/v1/chats/{uuid.uuid4()}/attachments?filename=a.png"
self.png = imagegen.png(16, 16)
def tearDown(self):
for p in self.patches: p.stop()
def post(self, data=None, ctype="image/png"):
return self.client.post(self.url, content=data or self.png, headers={"Content-Type": ctype})
def test_db_failure_after_put_deletes_object(self):
@contextmanager
def broken_db():
raise psycopg.OperationalError("simulated COMMIT failure")
yield
with mock.patch.object(main, "db", broken_db):
r = self.post()
self.assertEqual(r.status_code, 503)
self.assertEqual(len(self.puts), 1)
self.assertEqual(self.deletes, self.puts) # exactly the object that was written
def test_corrupt_image_never_reaches_s3(self):
r = self.post(self.png[:40])
self.assertEqual(r.status_code, 415)
self.assertEqual((self.puts, self.deletes), ([], []))
def test_put_failure_is_compensated_and_503(self):
def failing_put(key, spool, size, ct):
self.puts.append(key); raise main.BotoCoreError()
with mock.patch.object(main, "s3_put", failing_put):
r = self.post()
self.assertEqual(r.status_code, 503)
self.assertEqual(self.deletes, self.puts) # a PUT with a lost reply may have stored the object
if __name__ == "__main__":
unittest.main()