Files
mtusi2026lab4/scripts/test_presigned_upload.py

124 lines
3.3 KiB
Python

import hashlib
import json
import sys
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, check
BASE_URL = "http://localhost:8080"
IMAGE = ROOT / "tests" / "fixtures" / "sample.png"
def response_json(response):
"""Decode JSON from the raw response bytes."""
return json.loads(response["bytes"].decode("utf-8"))
def main():
content = IMAGE.read_bytes()
digest = hashlib.sha256(content).hexdigest()
client = Client(BASE_URL)
alice, bob, eve, chat = client.bootstrap()
# 1. Request a short-lived upload URL.
create_response = client.call(
"POST",
f"/api/v1/chats/{chat['id']}/attachments/presigned",
201,
actor=alice,
body={
"filename": "sample.png",
"content_type": "image/png",
"size_bytes": len(content),
"sha256": digest,
},
)
created = response_json(create_response)
check(created["method"] == "PUT", "unexpected upload method")
check(bool(created["upload_id"]), "missing upload_id")
check(created["expires_in"] > 0, "invalid upload expiration")
# 2. Upload directly to S3, without sending the file through the API.
request = urllib.request.Request(
created["upload_url"],
data=content,
headers=created["headers"],
method="PUT",
)
with urllib.request.urlopen(request, timeout=30) as response:
check(
response.status in (200, 201, 204),
"S3 upload failed",
)
# 3. Complete the upload.
complete_path = (
f"/api/v1/attachments/uploads/{created['upload_id']}/complete"
)
complete_response = client.call(
"POST",
complete_path,
200,
actor=alice,
)
attachment = response_json(complete_response)
check(attachment["status"] == "ready", "attachment is not ready")
check(attachment["chat_id"] == chat["id"], "wrong attachment chat")
check(attachment["owner_id"] == alice["id"], "wrong attachment owner")
check(attachment["sha256"] == digest, "attachment checksum mismatch")
check(
attachment["size_bytes"] == len(content),
"attachment size mismatch",
)
# 4. Complete again: must return the same attachment.
repeated_response = client.call(
"POST",
complete_path,
200,
actor=alice,
)
repeated = response_json(repeated_response)
check(
repeated["id"] == attachment["id"],
"repeated completion created a duplicate",
)
# 5. Download through the authorized API endpoint.
downloaded = client.call(
"GET",
f"/api/v1/attachments/{attachment['id']}/content",
200,
actor=alice,
)["bytes"]
check(downloaded == content, "downloaded bytes differ from original")
check(
hashlib.sha256(downloaded).hexdigest() == digest,
"downloaded checksum mismatch",
)
print("PASS: presigned upload, completion, idempotency and download")
print(f"Upload ID: {created['upload_id']}")
print(f"Attachment ID: {attachment['id']}")
print(f"File size: {len(content)} bytes")
print(f"SHA-256: {digest}")
if __name__ == "__main__":
main()