#!/usr/bin/env python3 """Собственные тесты уровня 4 для вложений. Покрывают: слишком большой файл, повреждённое изображение, подмену MIME, чужой attachment_id, привязку файла другого чата, отсутствие доступа у постороннего, эксперимент с памятью при ≥10 одновременных загрузках. Запуск: python3 tests/test_attachments.py --base-url http://localhost:8080 """ import argparse import base64 import io import json import os import sys import threading import time import unittest import urllib.error import urllib.request import uuid _parser = argparse.ArgumentParser(description="Attachment tests (lab4)") _parser.add_argument("--base-url", default=None) _args, _unknown = _parser.parse_known_args() sys.argv = [sys.argv[0]] + _unknown BASE_URL = (_args.base_url or os.environ.get("BASE_URL") or "http://localhost:8080").rstrip("/") ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) FIXTURE = os.path.join(ROOT, "tests", "fixtures", "sample.png") def request(method, path, body=None, token=None, raw=None, content_type=None, extra_headers=None): headers = {"Accept": "application/json"} if token: headers["Authorization"] = "Bearer " + token if extra_headers: headers.update(extra_headers) data = None if raw is not None: data = raw if content_type: headers["Content-Type"] = content_type elif body is not None: data = json.dumps(body, ensure_ascii=False).encode("utf-8") headers["Content-Type"] = "application/json" req = urllib.request.Request(BASE_URL + path, data=data, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=30) as resp: payload = resp.read() ctype = resp.headers.get_content_type() if ctype == "application/json" and payload: return resp.status, json.loads(payload), resp.headers return resp.status, payload, resp.headers except urllib.error.HTTPError as err: payload = err.read() try: parsed = json.loads(payload) if payload else None except ValueError: parsed = None return err.code, parsed, err.headers def make_user(label): username = "u_" + label + "_" + uuid.uuid4().hex[:10] password = "T3st-" + uuid.uuid4().hex status, user, _ = request( "POST", "/api/v1/users", {"username": username, "display_name": "Att " + label, "password": password}, ) assert status == 201, (status, user) basic = base64.b64encode((username + ":" + password).encode()).decode() # Basic-вход: используем заголовок Authorization напрямую. req = urllib.request.Request( BASE_URL + "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic, "Accept": "application/json"}, method="POST", ) with urllib.request.urlopen(req, timeout=10) as resp: session = json.loads(resp.read()) return {"user": user, "token": session["token"]} def make_chat(owner, members): status, chat, _ = request( "POST", "/api/v1/chats", {"title": "Att chat", "member_ids": [owner["user"]["id"]] + [m["user"]["id"] for m in members]}, token=owner["token"], ) assert status == 201, (status, chat) return chat def upload(token, chat_id, data, filename="sample.png", content_type="image/png"): path = "/api/v1/chats/" + chat_id + "/attachments?filename=" + urllib.request.quote(filename) return request("POST", path, raw=data, token=token, content_type=content_type) class AttachmentTests(unittest.TestCase): @classmethod def setUpClass(cls): with open(FIXTURE, "rb") as fh: cls.png = fh.read() cls.alice = make_user("alice") cls.bob = make_user("bob") cls.eve = make_user("eve") cls.chat = make_chat(cls.alice, [cls.bob]) cls.other_chat = make_chat(cls.alice, [cls.bob]) def test_upload_and_download_roundtrip(self): status, att, _ = upload(self.alice["token"], self.chat["id"], self.png) self.assertEqual(status, 201, att) self.assertEqual(att["status"], "ready") self.assertEqual(att["content_type"], "image/png") self.assertEqual(att["size_bytes"], len(self.png)) status, body, headers = request( "GET", "/api/v1/attachments/" + att["id"] + "/content", token=self.bob["token"] ) self.assertEqual(status, 200) self.assertEqual(body, self.png) self.assertEqual(headers.get_content_type(), "image/png") def test_oversized_rejected(self): big = b"\x89PNG\r\n\x1a\n" + b"\x00" * (10 * 1024 * 1024 + 1) status, body, _ = upload(self.alice["token"], self.chat["id"], big) self.assertEqual(status, 413) self.assertEqual(body["error"]["code"], "payload_too_large") def test_corrupted_image_rejected(self): broken = b"\x89PNG\r\n\x1a\n" + b"garbage" * 100 status, body, _ = upload(self.alice["token"], self.chat["id"], broken) self.assertEqual(status, 415) self.assertEqual(body["error"]["code"], "unsupported_media_type") def test_mime_spoof_rejected(self): # Заявляем image/png, а содержимое — JPEG. jpeg = b"\xff\xd8\xff\xe0" + b"\x00" * 100 status, body, _ = upload(self.alice["token"], self.chat["id"], jpeg, content_type="image/png") self.assertEqual(status, 415) self.assertEqual(body["error"]["code"], "unsupported_media_type") def test_unsupported_content_type(self): status, body, _ = upload(self.alice["token"], self.chat["id"], self.png, content_type="text/plain") self.assertEqual(status, 415) def test_dangerous_filename_rejected(self): status, body, _ = upload(self.alice["token"], self.chat["id"], self.png, filename="../etc/passwd") self.assertEqual(status, 400) self.assertEqual(body["error"]["code"], "invalid_request") def test_outsider_cannot_read(self): status, att, _ = upload(self.alice["token"], self.chat["id"], self.png) self.assertEqual(status, 201) for suffix in ("", "/content"): status, body, _ = request( "GET", "/api/v1/attachments/" + att["id"] + suffix, token=self.eve["token"] ) self.assertEqual(status, 404) self.assertEqual(body["error"]["code"], "not_found") def test_attachment_from_other_chat_rejected(self): status, att, _ = upload(self.alice["token"], self.other_chat["id"], self.png) self.assertEqual(status, 201) status, body, _ = request( "POST", "/api/v1/chats/" + self.chat["id"] + "/messages", {"text": "", "attachment_ids": [att["id"]]}, token=self.alice["token"], extra_headers={"Idempotency-Key": "other-chat-" + uuid.uuid4().hex}, ) self.assertEqual(status, 404) self.assertEqual(body["error"]["code"], "not_found") def test_message_with_attachment(self): status, att, _ = upload(self.alice["token"], self.chat["id"], self.png) self.assertEqual(status, 201) status, msg, _ = request( "POST", "/api/v1/chats/" + self.chat["id"] + "/messages", {"text": "", "attachment_ids": [att["id"]]}, token=self.alice["token"], extra_headers={"Idempotency-Key": "msg-att-" + uuid.uuid4().hex}, ) self.assertEqual(status, 201, msg) self.assertEqual(msg["attachment_ids"], [att["id"]]) self.assertEqual(msg["text"], "") def test_concurrent_uploads_memory(self): """≥10 одновременных загрузок; проверяем, что все успешны и API жив.""" results = [] lock = threading.Lock() def worker(): status, att, _ = upload(self.alice["token"], self.chat["id"], self.png) with lock: results.append((status, att)) threads = [threading.Thread(target=worker) for _ in range(10)] started = time.monotonic() for t in threads: t.start() for t in threads: t.join() elapsed = time.monotonic() - started self.assertEqual(len(results), 10) for status, att in results: self.assertEqual(status, 201, att) # API остаётся живым после нагрузки. status, _, _ = request("GET", "/health/ready") self.assertEqual(status, 200) print("\nconcurrent uploads: 10 in %.2fs" % elapsed) if __name__ == "__main__": unittest.main(verbosity=2)