"""Run inside the maintenance image: python - < student-tests/test_reconcile.py.""" import hashlib import importlib.util import io import time import unittest from datetime import datetime, timedelta, timezone from pathlib import Path from types import SimpleNamespace from unittest.mock import Mock from urllib.error import HTTPError from urllib.request import Request, urlopen from uuid import UUID, uuid4 import psycopg from psycopg.rows import dict_row from src.db import database_url from src.store import store spec = importlib.util.spec_from_file_location("reconciler", "scripts/reconcile-attachments.py") reconciler = importlib.util.module_from_spec(spec) spec.loader.exec_module(reconciler) class ReconcileTests(unittest.TestCase): def test_delete_rechecks_database_and_object_version(self): key = f"originals/{uuid4()}" item = SimpleNamespace(object_name=key, etag="old", size=10, last_modified=datetime.now(timezone.utc) - timedelta(hours=2)) conn, client = Mock(), Mock() conn.execute.return_value.fetchone.return_value = {"id": uuid4()} self.assertFalse(reconciler.delete_orphan(client, conn, item, 3600)) client.remove_object.assert_not_called() conn.execute.return_value.fetchone.return_value = None client.stat_object.return_value = SimpleNamespace(etag="replaced", size=10, last_modified=item.last_modified) self.assertFalse(reconciler.delete_orphan(client, conn, item, 3600)) client.remove_object.assert_not_called() def test_orphans_missing_repair_and_live_reference(self): client = reconciler.storage() fixture = Path("/fixtures/sample.png") data = fixture.read_bytes() digest = hashlib.sha256(data).hexdigest() username = "reconcile_" + uuid4().hex[:16] owner = store.register(username, "Reconciler test", "Test-password-123") session = store.create_session(username, "Test-password-123") chat = store.create_chat(owner["id"], "Reconciler test", [owner["id"]]) active_id, missing_id = uuid4(), uuid4() active_key, missing_key = f"originals/{active_id}", f"originals/{missing_id}" old_key, fresh_key = f"originals/{uuid4()}", f"originals/{uuid4()}" def put(key): client.put_object(reconciler.BUCKET, key, io.BytesIO(data), len(data), content_type="image/png") put(active_key) put(missing_key) put(old_key) with self.assertRaises(psycopg.errors.ForeignKeyViolation): with psycopg.connect(database_url()) as failed: failed.execute( "INSERT INTO attachments (id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256) " "VALUES (%s,%s,%s,%s,%s,%s,%s,%s)", (UUID(old_key.split("/")[1]), uuid4(), UUID(owner["id"]), "orphan.png", old_key, "image/png", len(data), digest), ) with psycopg.connect(database_url(), row_factory=dict_row) as conn: for item_id, key in ((active_id, active_key), (missing_id, missing_key)): conn.execute( "INSERT INTO attachments (id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256) " "VALUES (%s,%s,%s,%s,%s,%s,%s,%s)", (item_id, UUID(chat["id"]), UUID(owner["id"]), "sample.png", key, "image/png", len(data), digest), ) message_id = uuid4() conn.execute( "INSERT INTO messages (id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s)", (message_id, UUID(chat["id"]), UUID(owner["id"]), ""), ) conn.execute( "INSERT INTO message_attachments (message_id,chat_id,attachment_id,position) VALUES (%s,%s,%s,0)", (message_id, UUID(chat["id"]), active_id), ) client.remove_object(reconciler.BUCKET, missing_key) time.sleep(6) put(fresh_key) with psycopg.connect(database_url(), row_factory=dict_row) as conn: preview = reconciler.reconcile(client, conn, False, 5, None, None) self.assertIn(old_key, preview["old_orphans"]) self.assertIn(fresh_key, preview["fresh_orphans"]) self.assertIn(str(missing_id), preview["missing_attachment_ids"]) self.assertNotIn(active_key, preview["old_orphans"]) self.assertFalse(reconciler.absent(client, old_key)) wrong = Path("/tmp/reconcile-wrong-source") wrong.write_bytes(b"not the original") with self.assertRaisesRegex(ValueError, "size/SHA-256 mismatch"): reconciler.reconcile(client, conn, True, 5, missing_id, wrong) self.assertFalse(reconciler.absent(client, old_key)) applied = reconciler.reconcile(client, conn, True, 5, None, None) self.assertIn(old_key, applied["deleted"]) self.assertTrue(reconciler.absent(client, old_key)) self.assertFalse(reconciler.absent(client, fresh_key)) self.assertFalse(reconciler.absent(client, active_key)) self.assertTrue(reconciler.absent(client, missing_key)) request = Request( f"http://api:8080/api/v1/attachments/{missing_id}/content", headers={"Authorization": "Bearer " + session["token"]}, ) with self.assertRaises(HTTPError) as unavailable: urlopen(request, timeout=5) self.assertEqual(unavailable.exception.code, 503) with self.assertRaisesRegex(ValueError, "size/SHA-256 mismatch"): reconciler.restore_missing(client, conn, missing_id, wrong, True) self.assertTrue(reconciler.absent(client, missing_key)) self.assertEqual(reconciler.restore_missing(client, conn, missing_id, fixture, True), "restored") self.assertEqual(reconciler.restore_missing(client, conn, missing_id, fixture, True), "already_present") final = reconciler.reconcile(client, conn, False, 5, None, None) self.assertNotIn(old_key, final["old_orphans"]) self.assertNotIn(str(missing_id), final["missing_attachment_ids"]) self.assertIsNotNone(conn.execute( "SELECT 1 FROM message_attachments WHERE attachment_id=%s", (active_id,) ).fetchone()) response = client.get_object(reconciler.BUCKET, missing_key) try: self.assertEqual(hashlib.sha256(response.read()).hexdigest(), digest) finally: response.close() response.release_conn() with urlopen(request, timeout=5) as response: self.assertEqual(response.read(), data) print("PASS: old orphan dry-run/apply, fresh and linked objects retained, missing restored from verified fixture") if __name__ == "__main__": unittest.main()