Files
mtusi2026lab4/student-tests/test_attachments.py
T
DaniilKuznetsovandЮгай Артур Рустамович 0c5c19bb09 ЛР4 на 3
Co-authored-by: Югай Артур Рустамович <f1ekserr@yandex.ru>
2026-11-16 22:00:33 +03:00

118 lines
6.4 KiB
Python

from concurrent.futures import ThreadPoolExecutor
import hashlib
from urllib.parse import urlencode
from uuid import uuid4
import unittest
from helpers import Client, ROOT, image_bytes, oversized_pixels, padded_png
class AttachmentTests(unittest.TestCase):
def setUp(self):
self.client = Client(timeout=60)
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
self.path = "/api/v1/chats/" + self.chat["id"]
def upload(self, content=None, media="image/png", name="photo.png", expected=201, actor=None):
return self.client.call(
"POST", self.path + "/attachments?" + urlencode({"filename": name}), expected,
actor=actor or self.alice, raw=image_bytes() if content is None else content,
headers={"Content-Type": media}, schema="Attachment" if expected == 201 else None,
)
def test_original_png_jpeg_and_unicode_filename(self):
for kind, media in (("PNG", "image/png"), ("JPEG", "image/jpeg")):
raw = image_bytes(kind)
att = self.upload(raw, media, "фото 👋." + kind.lower())["json"]
self.assertEqual(att["owner_id"], self.alice["id"])
self.assertEqual(att["sha256"], hashlib.sha256(raw).hexdigest())
self.assertEqual(att["size_bytes"], len(raw))
self.assertEqual((att["status"], att["variants"], att["error_code"]), ("ready", [], None))
path = "/api/v1/attachments/" + att["id"]
metadata = self.client.call("GET", path, actor=self.bob, schema="Attachment")["json"]
self.assertEqual(metadata, att)
downloaded = self.client.call("GET", path + "/content", actor=self.bob)
self.assertEqual(downloaded["bytes"], raw)
self.assertEqual(downloaded["headers"].get_content_type(), media)
self.assertNotIn("object_key", metadata)
self.assertNotIn("Location", downloaded["headers"])
def test_filename_validation(self):
for name in ("", " \t", "../a.png", "a/b.png", "a\\b.png", "a\x00.png", "a\n.png", "a\x7f.png", "я" * 256):
self.upload(name=name, expected=400)
self.assertEqual(self.upload(name="я" * 255)["json"]["filename"], "я" * 255)
def test_corrupt_images_mime_and_multipart(self):
png, jpeg = image_bytes(), image_bytes("JPEG")
for content, media in ((b"", "image/png"), (b"not an image", "image/png"),
(png[:-8], "image/png"), (jpeg[:-8], "image/jpeg"),
(png, "image/jpeg"), (jpeg, "image/png"),
(image_bytes("GIF"), "image/png"), (png, "multipart/form-data")):
self.upload(content, media, expected=415)
def test_byte_limit_and_original_at_exact_boundary(self):
raw = padded_png(10485760)
att = self.upload(raw)["json"]
downloaded = self.client.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=self.bob)
self.assertEqual(downloaded["bytes"], raw)
self.upload(raw + b"x", expected=413)
def test_chunked_body_cannot_bypass_size_limit(self):
def blocks():
for _ in range(161):
yield b"x" * 65536
self.upload(blocks(), expected=413)
def test_pixel_boundary_and_decompression_bomb(self):
self.upload(oversized_pixels(), expected=413)
self.assertEqual(self.upload(image_bytes(size=(8000, 5000)))["json"]["status"], "ready")
def test_attachment_access_and_unknown_ids(self):
att = self.upload()["json"]
for suffix in ("", "/content"):
self.client.call("GET", "/api/v1/attachments/" + att["id"] + suffix, 404, actor=self.eve)
self.client.call("GET", "/api/v1/attachments/" + str(uuid4()) + suffix, 404, actor=self.alice)
self.client.call("GET", "/api/v1/attachments/" + att["id"] + suffix, 401)
self.upload(actor=self.eve, expected=404)
def test_messages_keep_attachment_order_and_allow_empty_text(self):
ids = [self.upload()["json"]["id"] for _ in range(2)]
for text in ("", " \t\n", "с картинками"):
message = self.client.message(self.bob, self.chat, text, attachments=ids[::-1])["json"]
self.assertEqual(message["attachment_ids"], ids[::-1])
self.assertEqual(message["text"], text)
page = self.client.call("GET", self.path + "/messages", actor=self.alice, schema="MessagePage")["json"]
self.assertEqual([m["attachment_ids"] for m in page["items"]], [ids[::-1]] * 3)
def test_bad_attachment_list_and_other_chat_do_not_create_messages(self):
att = self.upload()["json"]["id"]
other = self.client.call("POST", "/api/v1/chats", 201, actor=self.alice,
body={"title": "other", "member_ids": [self.alice["id"]]}, schema="Chat")["json"]
foreign = self.client.attachment(self.alice, other)[0]["id"]
for ids, status in (([att, att], 400), ([str(uuid4()) for _ in range(11)], 400),
(["bad"], 400), ([str(uuid4())], 404), ([foreign], 404)):
self.client.call("POST", self.path + "/messages", status, actor=self.alice,
body={"text": "test", "attachment_ids": ids}, headers={"Idempotency-Key": uuid4().hex})
page = self.client.call("GET", self.path + "/messages", actor=self.alice, schema="MessagePage")["json"]
self.assertEqual(page["items"], [])
def test_idempotency_defaults_and_attachment_replay(self):
key = uuid4().hex
original = self.client.message(self.alice, self.chat, "text", key=key)["json"]
explicit = self.client.message(self.alice, self.chat, "text", key=key, attachments=[])["json"]
self.assertEqual(original, explicit)
att = self.upload()["json"]["id"]
key = uuid4().hex
def send(_):
return Client(timeout=30).message(self.alice, self.chat, "", key=key, attachments=[att])
with ThreadPoolExecutor(max_workers=10) as pool:
responses = list(pool.map(send, range(10)))
self.assertEqual(len({r["json"]["id"] for r in responses}), 1)
self.assertEqual(len({r["headers"]["X-Instance-Id"] for r in responses}), 2)
self.client.call("POST", self.path + "/messages", 409, actor=self.alice,
body={"text": "different", "attachment_ids": [att]}, headers={"Idempotency-Key": key})
if __name__ == "__main__":
unittest.main(verbosity=2)