Process versioned image variants with leased worker (U3)

This commit is contained in:
Самохвалов Андрей Ремович
2026-10-02 14:39:08 +03:00
parent b23ecc111f
commit 03899d790b
5 changed files with 492 additions and 0 deletions
+74
View File
@@ -0,0 +1,74 @@
"""Small checks for the worker's deterministic image and payload boundary."""
import json
import unittest
from io import BytesIO
from PIL import Image
from src.image_variants import InvalidImage, render
from src.worker import parse_message
def encoded(image, format="PNG", **options):
stream = BytesIO()
image.save(stream, format=format, **options)
return stream.getvalue()
class ImagePipelineTest(unittest.TestCase):
def test_contract_sizes_original_and_content_types(self):
original = encoded(Image.new("RGB", (320, 200), "red"))
result = render(original, "image/png")
self.assertEqual(result["original"]["data"], original)
self.assertEqual((result["thumbnail"]["width"], result["thumbnail"]["height"]), (256, 160))
self.assertEqual((result["crop"]["width"], result["crop"]["height"]), (128, 128))
self.assertEqual((result["optimized"]["width"], result["optimized"]["height"]), (320, 200))
self.assertEqual([result[name]["content_type"] for name in ("thumbnail", "crop", "optimized")],
["image/jpeg", "image/jpeg", "image/webp"])
def test_alpha_is_white_and_small_image_is_not_upscaled(self):
original = encoded(Image.new("RGBA", (24, 12), (255, 0, 0, 0)))
result = render(original, "image/png")
self.assertEqual((result["thumbnail"]["width"], result["thumbnail"]["height"]), (24, 12))
with Image.open(BytesIO(result["thumbnail"]["data"])) as thumb:
self.assertTrue(all(channel >= 245 for channel in thumb.getpixel((0, 0))))
def test_exif_orientation_and_center_crop(self):
image = Image.new("RGB", (30, 10), "green")
image.paste("red", (0, 0, 10, 10))
image.paste("blue", (20, 0, 30, 10))
exif = Image.Exif()
exif[274] = 6
original = encoded(image, "JPEG", exif=exif)
result = render(original, "image/jpeg")
self.assertEqual((result["thumbnail"]["width"], result["thumbnail"]["height"]), (10, 30))
with Image.open(BytesIO(result["crop"]["data"])) as crop:
red, green, blue = crop.getpixel((64, 64))
self.assertGreater(green, red)
self.assertGreater(green, blue)
def test_rejects_wrong_type_and_corrupt_file(self):
original = encoded(Image.new("RGB", (2, 2), "black"))
with self.assertRaises(InvalidImage):
render(original, "image/jpeg")
with self.assertRaises(InvalidImage):
render(b"broken", "image/png")
def test_payload_contains_only_versioned_job_identifiers(self):
body = {
"schema_version": 1,
"job_id": "11111111-1111-4111-8111-111111111111",
"type": "attachment.process.v1",
"attachment_id": "22222222-2222-4222-8222-222222222222",
"pipeline_version": 1,
"attempt": 1,
"created_at": "2026-09-01T12:00:00Z",
}
self.assertEqual(parse_message(json.dumps(body).encode()), body)
with self.assertRaises(ValueError):
parse_message(json.dumps({**body, "staging_key": "private"}).encode())
if __name__ == "__main__":
unittest.main()
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Check every public variant against committed metadata and original bytes."""
import hashlib
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, arguments, check, run # noqa: E402
def main():
args = arguments("Lab5 ready variants")
client = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
ready = client.wait_ready(bob, attachment)
variants = {item["name"]: item for item in ready["variants"]}
check(set(variants) == {"thumbnail", "crop", "optimized"}, "incomplete variant set")
expected = {
"thumbnail": ("image/jpeg", 256, 160),
"crop": ("image/jpeg", 128, 128),
"optimized": ("image/webp", 320, 200),
}
for name, (content_type, width, height) in expected.items():
variant = variants[name]
check((variant["content_type"], variant["width"], variant["height"]) ==
(content_type, width, height), f"wrong {name} metadata")
response = client.call(
"GET", f"/api/v1/attachments/{attachment['id']}/content?variant={name}", actor=bob
)
check(response["headers"].get_content_type() == content_type, f"wrong {name} MIME")
check(len(response["bytes"]) == variant["size_bytes"] and
hashlib.sha256(response["bytes"]).hexdigest() == variant["sha256"],
f"wrong {name} bytes")
client.call(
"GET", f"/api/v1/attachments/{attachment['id']}/content?variant={name}",
404, actor=eve,
)
downloaded = client.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)
check(downloaded["bytes"] == original, "original bytes changed")
print("PASS: all three variants match metadata; original preserved; outsider denied")
if __name__ == "__main__":
run(main)