"""Собственные проверки лабораторной 5: асинхронный pipeline и варианты. Проверки идут через публичный контракт и LB; Docker-сценарии (остановка worker, брокера, fault injection) лежат в отдельных probes и в evidence. """ from __future__ import annotations import hashlib import struct import unittest import uuid import zlib from pathlib import Path from urllib.parse import quote import harness from client import Client from image_probe import jpeg_size ROOT = Path(__file__).resolve().parents[1] PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() JPEG = (Path(__file__).resolve().parent / "fixtures" / "sample.jpg").read_bytes() MAX_BYTES = 10_485_760 EXPECTED_VARIANTS = {"thumbnail", "crop", "optimized"} def webp_size(data: bytes) -> tuple[int, int]: """Размеры WebP без внешних библиотек: VP8X, VP8L или lossy VP8.""" assert data[:4] == b"RIFF" and data[8:12] == b"WEBP", "not WebP" offset = 12 while offset + 8 <= len(data): fourcc = data[offset : offset + 4] length = int.from_bytes(data[offset + 4 : offset + 8], "little") payload = data[offset + 8 : offset + 8 + length] if fourcc == b"VP8X" and len(payload) >= 10: width = 1 + int.from_bytes(payload[4:7], "little") height = 1 + int.from_bytes(payload[7:10], "little") return width, height if fourcc == b"VP8L" and len(payload) >= 5: bits = int.from_bytes(payload[1:5], "little") return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1 if fourcc == b"VP8 " and len(payload) >= 10: assert payload[3:6] == b"\x9d\x01\x2a", "not a VP8 keyframe" width = int.from_bytes(payload[6:8], "little") & 0x3FFF height = int.from_bytes(payload[8:10], "little") & 0x3FFF return width, height offset += 8 + length + (length & 1) raise AssertionError("WebP dimensions not found") def upload( api: Client, actor: dict, chat: dict, content: bytes, *, filename: str = "photo.png", content_type: str = "image/png", expected: int = 202, ): path = "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], quote(filename, safe="")) return api.call( "POST", path, expected, actor=actor, raw=content, headers={"Content-Type": content_type}, schema="Attachment" if expected == 202 else None, ) def png_with_dimensions(width: int, height: int) -> bytes: """Меняет IHDR у реального PNG и пересчитывает CRC: файл остаётся PNG.""" data = bytearray(PNG) struct.pack_into(">I", data, 16, width) struct.pack_into(">I", data, 20, height) struct.pack_into(">I", data, 29, zlib.crc32(bytes(data[12:29])) & 0xFFFFFFFF) return bytes(data) class Lab5AttachmentTests(unittest.TestCase): @classmethod def setUpClass(cls) -> None: harness.wait_ready() cls.api = harness.client() cls.alice, cls.bob, cls.eve, cls.chat = cls.api.bootstrap() cls.other_chat = cls.api.call( "POST", "/api/v1/chats", 201, actor=cls.alice, body={"title": "Другой чат lab5", "member_ids": [cls.alice["id"], cls.bob["id"]]}, schema="Chat", )["json"] def test_01_png_and_jpeg_pipeline(self) -> None: for content, content_type, filename in ( (PNG, "image/png", "sample.png"), (JPEG, "image/jpeg", "sample.jpg"), ): queued = upload( self.api, self.alice, self.chat, content, filename=filename, content_type=content_type )["json"] self.assertEqual(queued["status"], "queued") self.assertEqual(queued["variants"], []) self.assertIsNone(queued["error_code"]) self.assertEqual(queued["sha256"], hashlib.sha256(content).hexdigest()) self.assertEqual(queued["size_bytes"], len(content)) ready = self.api.wait_ready(self.bob, queued) self.assertEqual(ready["status"], "ready") self.assertIsNone(ready["error_code"]) names = {item["name"] for item in ready["variants"]} self.assertEqual(names, EXPECTED_VARIANTS) variants = {item["name"]: item for item in ready["variants"]} self.assertEqual( (variants["thumbnail"]["content_type"], variants["thumbnail"]["width"], variants["thumbnail"]["height"]), ("image/jpeg", 256, 160), ) self.assertEqual( (variants["crop"]["content_type"], variants["crop"]["width"], variants["crop"]["height"]), ("image/jpeg", 128, 128), ) self.assertEqual(variants["optimized"]["content_type"], "image/webp") self.assertLessEqual(max(variants["optimized"]["width"], variants["optimized"]["height"]), 1280) original = self.api.call("GET", "/api/v1/attachments/" + queued["id"] + "/content", actor=self.bob) self.assertEqual(original["bytes"], content) self.assertEqual(original["headers"].get_content_type(), content_type) self.assertEqual(original["headers"].get("Content-Length"), str(len(content))) for name, expected_size in (("thumbnail", (256, 160)), ("crop", (128, 128))): response = self.api.call( "GET", "/api/v1/attachments/" + queued["id"] + "/content?variant=" + name, actor=self.bob, ) self.assertEqual(response["headers"].get_content_type(), "image/jpeg") self.assertEqual(hashlib.sha256(response["bytes"]).hexdigest(), variants[name]["sha256"]) self.assertEqual(len(response["bytes"]), variants[name]["size_bytes"]) self.assertEqual(jpeg_size(response["bytes"]), expected_size) optimized = self.api.call( "GET", "/api/v1/attachments/" + queued["id"] + "/content?variant=optimized", actor=self.bob, ) self.assertEqual(optimized["headers"].get_content_type(), "image/webp") self.assertEqual(hashlib.sha256(optimized["bytes"]).hexdigest(), variants["optimized"]["sha256"]) self.assertEqual( webp_size(optimized["bytes"]), (variants["optimized"]["width"], variants["optimized"]["height"]), ) def test_02_stranger_and_nonmember(self) -> None: attachment = upload(self.api, self.alice, self.chat, PNG)["json"] for suffix in ("", "/content"): self.api.call("GET", "/api/v1/attachments/" + attachment["id"] + suffix, 404, actor=self.eve) upload(self.api, self.eve, self.chat, PNG, expected=404) self.api.call( "GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=thumbnail", 404, actor=self.eve, ) def test_03_attachment_from_another_chat_is_404(self) -> None: foreign = upload(self.api, self.alice, self.other_chat, PNG)["json"] self.api.call( "POST", "/api/v1/chats/" + self.chat["id"] + "/messages", 404, actor=self.alice, body={"text": "", "attachment_ids": [foreign["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex}, ) own = self.api.message(self.alice, self.other_chat, "", attachments=[foreign["id"]])["json"] self.assertEqual(own["attachment_ids"], [foreign["id"]]) def test_04_queued_attachment_can_be_message_and_idempotency(self) -> None: attachment = upload(self.api, self.alice, self.chat, PNG)["json"] path = "/api/v1/chats/" + self.chat["id"] + "/messages" self.api.call("POST", path, 400, actor=self.alice, body={"text": ""}, headers={"Idempotency-Key": uuid.uuid4().hex}) self.api.call( "POST", path, 400, actor=self.alice, body={"text": "too many", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]}, headers={"Idempotency-Key": uuid.uuid4().hex}, ) self.api.call( "POST", path, 400, actor=self.alice, body={"text": "duplicate", "attachment_ids": [attachment["id"], attachment["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex}, ) key = uuid.uuid4().hex first = self.api.message(self.alice, self.chat, "", key=key, attachments=[attachment["id"]])["json"] self.assertEqual(first["text"], "") self.assertEqual(first["attachment_ids"], [attachment["id"]]) replay = self.api.message(self.alice, self.chat, "", key=key, attachments=[attachment["id"]])["json"] self.assertEqual(replay, first) self.api.call( "POST", path, 409, actor=self.alice, body={"text": "different", "attachment_ids": []}, headers={"Idempotency-Key": key}, ) def test_05_rejects_bad_images_and_filenames(self) -> None: upload(self.api, self.alice, self.chat, b"\x00" * (MAX_BYTES + 1), expected=413) upload(self.api, self.alice, self.chat, PNG[:100], expected=415) upload(self.api, self.alice, self.chat, PNG, content_type="image/jpeg", expected=415) upload(self.api, self.alice, self.chat, b"not an image", expected=415) upload(self.api, self.alice, self.chat, b"", expected=415) upload(self.api, self.alice, self.chat, png_with_dimensions(8000, 6000), expected=413) upload(self.api, self.alice, self.chat, png_with_dimensions(10000, 10000), expected=413) for bad in ("../secret.png", "a/b.png", "a\\b.png", "a\x00b.png", "a\nb.png", "x" * 256): upload(self.api, self.alice, self.chat, PNG, filename=bad, expected=400) def test_06_unknown_variant_is_400(self) -> None: attachment = upload(self.api, self.alice, self.chat, PNG)["json"] ready = self.api.wait_ready(self.bob, attachment) self.api.call( "GET", "/api/v1/attachments/" + ready["id"] + "/content?variant=bogus", 400, actor=self.bob, ) if __name__ == "__main__": unittest.main(verbosity=2)