"""Run inside an API image: python - < student-tests/test_upload_failure.py.""" import asyncio import io import unittest from contextlib import contextmanager from unittest.mock import Mock, patch from uuid import uuid4 from fastapi import HTTPException from src import attachments class UploadFailureTests(unittest.TestCase): def test_post_put_database_failure_compensates(self): client = Mock() with patch.object(attachments, "storage", return_value=client), patch.object( attachments, "connection", side_effect=HTTPException(503) ): with self.assertRaises(HTTPException) as failure: attachments.persist_attachment(str(uuid4()), str(uuid4()), "test.png", "image/png", 3, "0" * 64, io.BytesIO(b"png")) self.assertEqual(failure.exception.status_code, 503) key = client.put_object.call_args.args[1] client.remove_object.assert_called_once_with(attachments.BUCKET, key) def test_s3_failure_does_not_touch_database(self): client = Mock() client.put_object.side_effect = OSError("simulated outage") with patch.object(attachments, "storage", return_value=client), patch.object(attachments, "connection") as db: with self.assertRaises(HTTPException) as failure: attachments.persist_attachment(str(uuid4()), str(uuid4()), "test.png", "image/png", 3, "0" * 64, io.BytesIO(b"png")) self.assertEqual(failure.exception.status_code, 503) db.assert_not_called() def test_ambiguous_commit_keeps_object_for_reconciliation(self): @contextmanager def ambiguous_commit(): connection = Mock() connection.execute.return_value.fetchone.return_value = {} yield connection raise HTTPException(503) client = Mock() with patch.object(attachments, "storage", return_value=client), patch.object( attachments, "connection", side_effect=ambiguous_commit ): with self.assertRaises(HTTPException) as failure: attachments.persist_attachment(str(uuid4()), str(uuid4()), "test.png", "image/png", 3, "0" * 64, io.BytesIO(b"png")) self.assertEqual(failure.exception.status_code, 503) client.remove_object.assert_not_called() def test_interrupted_request_never_starts_s3_put(self): class Interrupted: headers = {"content-type": "image/png"} async def stream(self): yield b"partial" raise OSError("client disconnected") with patch.object(attachments.store, "chat"), patch.object(attachments, "storage") as client: with self.assertRaises(OSError): asyncio.run(attachments.upload(Interrupted(), str(uuid4()), str(uuid4()), "test.png")) client.assert_not_called() if __name__ == "__main__": unittest.main()