import hashlib import sys import time import uuid from datetime import datetime, timedelta, timezone from pathlib import Path from botocore.exceptions import ClientError ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(ROOT / "tests")) from client import Client from app.core.config import settings from app.db.models import AttachmentUpload from app.db.session import SessionLocal from app.services.object_storage import client as s3_client BASE_URL = "http://localhost:8080" FIXTURE = ROOT / "tests" / "fixtures" / "sample.png" def main(): content = FIXTURE.read_bytes() digest = hashlib.sha256(content).hexdigest() api = Client(BASE_URL) alice, _, _, chat = api.bootstrap() upload_id = uuid.uuid4() object_key = f"cleanup-test/{chat['id']}/{upload_id}" # Host-side test uses the published S3 endpoint. s3 = s3_client() s3.put_object( Bucket=settings.s3_bucket, Key=object_key, Body=content, ContentType="image/png", ) with SessionLocal() as db: upload = AttachmentUpload( id=upload_id, chat_id=uuid.UUID(chat["id"]), owner_id=uuid.UUID(alice["id"]), filename="cleanup-test.png", content_type="image/png", expected_size_bytes=len(content), expected_sha256=digest, object_key=object_key, status="pending", # Older than expiry + 10-minute grace period. expires_at=datetime.now(timezone.utc) - timedelta(minutes=11), ) db.add(upload) db.commit() print(f"Created synthetic pending upload: {upload_id}") print("Waiting for background cleanup (up to 90 seconds)...") deadline = time.monotonic() + 90 final_status = None while time.monotonic() < deadline: with SessionLocal() as db: row = db.get(AttachmentUpload, upload_id) final_status = row.status if row else None if final_status == "expired": break time.sleep(2) if final_status != "expired": raise SystemExit( f"FAIL: expected status expired, got {final_status!r}" ) try: s3.head_object(Bucket=settings.s3_bucket, Key=object_key) except ClientError as exc: code = exc.response.get("Error", {}).get("Code", "") status = exc.response.get("ResponseMetadata", {}).get("HTTPStatusCode") if code not in ("404", "NoSuchKey", "NotFound") and status != 404: raise else: raise SystemExit("FAIL: S3 object still exists") print("PASS: abandoned upload marked expired") print("PASS: corresponding S3 object deleted") print(f"Upload ID: {upload_id}") print(f"Object size: {len(content)} bytes") print(f"SHA-256: {digest}") if __name__ == "__main__": main()