"""Тесты асинхронного конвейера вложений lab5 (контракт вариантов, состояния, права). Запуск: python -m unittest discover -s student-tests -p "test_pipeline.py" -v Пиксельные проверки выполняются, если установлен Pillow (иначе пропускаются); размеры проверяются по заголовкам файлов. """ import hashlib import io import os import struct import sys import time import unittest import uuid sys.path.insert(0, os.path.dirname(__file__)) from test_api import call, register # noqa: E402 from test_attachments import FIX, JPG, PNG, download, upload # noqa: E402 try: from PIL import Image except ImportError: # pragma: no cover Image = None def fixture(name): return open(os.path.join(FIX, name), "rb").read() def jpeg_size(data): i = 2 while i < len(data): while data[i] == 0xFF: i += 1 marker = data[i] i += 1 if marker in (0xD8, 0x01) or 0xD0 <= marker <= 0xD7: continue length = int.from_bytes(data[i:i + 2], "big") if marker in (0xC0, 0xC1, 0xC2): return int.from_bytes(data[i + 5:i + 7], "big"), int.from_bytes(data[i + 3:i + 5], "big") i += length raise AssertionError("JPEG dimensions not found") def webp_size(data): assert data[:4] == b"RIFF" and data[8:12] == b"WEBP", "not WebP" kind = data[12:16] if kind == b"VP8X": return 1 + int.from_bytes(data[24:27], "little"), 1 + int.from_bytes(data[27:30], "little") if kind == b"VP8L": bits = int.from_bytes(data[21:25], "little") return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1 if kind == b"VP8 ": return struct.unpack(" 100x300 -> вписывается в 256: 85x256 (округление вниз) self.assertEqual((v["thumbnail"]["width"], v["thumbnail"]["height"]), (85, 256)) self.assertEqual(jpeg_size(self.fetch(att, "thumbnail")[1]), (85, 256)) def test_small_image_is_not_upscaled_but_crop_is_128(self): att = self.ready(fixture("small.png"), "image/png", "small.png") v = self.variants(att) self.assertEqual((v["thumbnail"]["width"], v["thumbnail"]["height"]), (50, 30)) self.assertEqual((v["crop"]["width"], v["crop"]["height"]), (128, 128)) self.assertEqual((v["optimized"]["width"], v["optimized"]["height"]), (50, 30)) @unittest.skipIf(Image is None, "нужен Pillow") def test_alpha_is_composited_on_white(self): att = self.ready(fixture("alpha.png"), "image/png", "alpha.png") thumb = Image.open(io.BytesIO(self.fetch(att, "thumbnail")[1])).convert("RGB") left, right = thumb.getpixel((10, thumb.height // 2)), thumb.getpixel((thumb.width - 10, thumb.height // 2)) self.assertTrue(all(c > 235 for c in left), "прозрачная область должна стать белой: %s" % (left,)) self.assertTrue(right[0] > 200 and right[1] < 60, "непрозрачная красная область сохранена: %s" % (right,)) def test_message_can_reference_attachment_before_ready_and_failed_cannot(self): status, _, att = upload(self.a["token"], self.chat["id"], PNG) path = "/api/v1/chats/%s/messages" % self.chat["id"] sent = call("POST", path, {"text": "", "attachment_ids": [att["id"]]}, self.a["token"]) self.assertEqual((status, sent[0], sent[2]["attachment_ids"]), (202, 201, [att["id"]])) poison = upload(self.a["token"], self.chat["id"], fixture("poison.png")) self.assertEqual(poison[0], 202, poison[2]) failed = wait_status(self.b["token"], poison[2]["id"], ("failed",)) self.assertEqual((failed["status"], failed["error_code"], failed["variants"]), ("failed", "invalid_image", [])) self.assertEqual(call("POST", path, {"text": "x", "attachment_ids": [failed["id"]]}, self.a["token"])[0], 409) self.assertEqual(download(self.b["token"], failed["id"], "/content")[0], 409) self.assertEqual(download(self.b["token"], failed["id"], "/content?variant=thumbnail")[0], 409) def test_content_is_409_while_not_ready_and_original_is_untouched(self): status, _, att = upload(self.a["token"], self.chat["id"], PNG) code = download(self.b["token"], att["id"], "/content")[0] self.assertIn(code, (200, 409)) # быстрый worker мог успеть: 200 допустим, но не 404/500 done = wait_status(self.b["token"], att["id"]) self.assertEqual(download(self.b["token"], done["id"], "/content")[2], PNG) def test_other_variants_visible_only_to_chat_members(self): att = self.ready(PNG) for variant in ("thumbnail", "crop", "optimized", "original"): self.assertEqual(download(self.eve["token"], att["id"], "/content?variant=" + variant)[0], 404) self.assertEqual(download(self.b["token"], att["id"], "/content?variant=bogus")[0], 400) def test_ready_job_redelivery_does_not_duplicate_variants(self): from test_api import psql att = self.ready(PNG) before = psql("SELECT count(*) FROM attachment_variants WHERE attachment_id = '%s'" % att["id"]) self.assertEqual(before, "3") psql("INSERT INTO outbox (job_id, attachment_id, pipeline_version, attempt) VALUES (gen_random_uuid(), '%s', 1, 2)" % att["id"]) time.sleep(4) self.assertEqual(psql("SELECT count(*) FROM attachment_variants WHERE attachment_id = '%s'" % att["id"]), "3") self.assertEqual(wait_status(self.b["token"], att["id"])["status"], "ready") def test_staging_is_cleaned_after_ready_and_kept_for_failed(self): import subprocess from test_api import ROOT, psql att = self.ready(PNG) poison = upload(self.a["token"], self.chat["id"], fixture("poison.png"))[2] wait_status(self.b["token"], poison["id"], ("failed",)) def exists(att_id): code = "\n".join(["import asyncio", "from app.s3 import S3", "async def m():", " s = S3(); await s.start(); print((await s.head('staging/%s')) is not None); await s.stop()" % att_id, "asyncio.run(m())"]) return subprocess.run(["docker", "compose", "--env-file", ".env", "exec", "-T", "api", "python", "-c", code], cwd=ROOT, capture_output=True, text=True).stdout.strip() self.assertEqual(exists(att["id"]), "False", "staging готового вложения должен быть удалён после COMMIT результата") self.assertEqual(exists(poison["id"]), "True", "staging неудавшегося вложения хранится для разбора/replay (retention)") if __name__ == "__main__": unittest.main()