forked from mtusi2026/mtusi2026lab4
Co-authored-by: Югай Артур Рустамович <f1ekserr@yandex.ru>
183 lines
9.7 KiB
Python
183 lines
9.7 KiB
Python
from concurrent.futures import ThreadPoolExecutor
|
|
import os
|
|
from pathlib import Path
|
|
import sys
|
|
import unittest
|
|
from urllib.parse import urlencode
|
|
from uuid import uuid4
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
|
from helpers import Client
|
|
from client import timestamp
|
|
|
|
|
|
class ApiTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.client = Client(os.environ.get("BASE_URL", "http://127.0.0.1:18104"))
|
|
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
|
|
self.path = "/api/v1/chats/" + self.chat["id"]
|
|
|
|
def error(self, method, path, status=400, **kwargs):
|
|
if method == "POST" and path.endswith("/messages"):
|
|
kwargs.setdefault("headers", {}).setdefault("Idempotency-Key", uuid4().hex)
|
|
response = self.client.call(method, path, status, **kwargs)
|
|
code = {400: "invalid_request", 401: "unauthorized", 404: "not_found", 409: "conflict", 415: "unsupported_media_type"}[status]
|
|
self.assertEqual(response["json"]["error"]["code"], code)
|
|
|
|
def get_page(self, path, actor=None, **query):
|
|
schema = "MessagePage" if path.endswith("/messages") else "ChatPage"
|
|
return self.client.call("GET", path + "?" + urlencode(query), actor=actor or self.alice, schema=schema)["json"]
|
|
|
|
def new_chat(self):
|
|
return self.client.call("POST", "/api/v1/chats", 201, actor=self.alice,
|
|
body={"title": "Ещё чат", "member_ids": [self.alice["id"], self.bob["id"]]}, schema="Chat")["json"]
|
|
|
|
def test_user_fields(self):
|
|
name = "u_" + uuid4().hex[:20]
|
|
bodies = [
|
|
{"username": "ab", "display_name": "Имя"},
|
|
{"username": "ABC", "display_name": "Имя"},
|
|
{"username": "valid\n", "display_name": "Имя"},
|
|
{"username": 123, "display_name": "Имя"},
|
|
{"username": name, "display_name": " \t\n"},
|
|
{"username": name, "display_name": 123},
|
|
{"username": name, "display_name": None},
|
|
{"username": name, "display_name": "я" * 101},
|
|
{"username": name, "display_name": "Имя", "password": "extra"},
|
|
{"username": name},
|
|
]
|
|
for body in bodies:
|
|
body.setdefault("password", "T3st-password-123")
|
|
with self.subTest(fields=sorted(body)):
|
|
self.error("POST", "/api/v1/users", body=body)
|
|
user = self.client.call("POST", "/api/v1/users", 201,
|
|
body={"username": name, "display_name": "👋" * 100, "password": "T3st-password-123"}, schema="User")["json"]
|
|
self.assertEqual(user["display_name"], "👋" * 100)
|
|
self.error("POST", "/api/v1/users", 409, body={"username": name, "display_name": "Повтор", "password": "T3st-password-123"})
|
|
|
|
def test_invalid_json_and_content_type(self):
|
|
for raw in (b'{"username":', b"null", b"[]", b"true", b"\xff", '{}'.encode('utf-16')):
|
|
with self.subTest(raw=raw):
|
|
self.error("POST", "/api/v1/users", raw=raw, headers={"Content-Type": "application/json"})
|
|
self.error("POST", "/api/v1/users", 415, raw=b"text", headers={"Content-Type": "text/plain"})
|
|
self.error("POST", "/api/v1/users", 415, raw=b"{}")
|
|
|
|
def test_auth_and_access(self):
|
|
self.error("GET", "/api/v1/users/me", 401)
|
|
for value in (str(uuid4()), "bad-id"):
|
|
self.error("GET", "/api/v1/users/me", 401, headers={"X-User-Id": value})
|
|
self.error("GET", "/api/v1/chats/bad-id", 401)
|
|
self.error("GET", "/api/v1/chats/bad-id", actor=self.alice)
|
|
self.error("GET", "/api/v1/chats/" + str(uuid4()), 404, actor=self.alice)
|
|
self.error("GET", self.path, 404, actor=self.eve)
|
|
self.error("GET", self.path + "/messages", 404, actor=self.eve)
|
|
self.error("POST", self.path + "/messages", 404, actor=self.eve, body={"text": "Чужое"})
|
|
self.assertEqual(self.get_page("/api/v1/chats", self.eve)["items"], [])
|
|
|
|
def test_chat_validation_is_atomic(self):
|
|
before = self.get_page("/api/v1/chats")["items"]
|
|
valid = [self.alice["id"], self.bob["id"]]
|
|
for members in ([], [self.bob["id"]], [self.alice["id"], str(uuid4())],
|
|
[self.alice["id"], self.alice["id"].upper()], ["bad-id"], valid * 51):
|
|
self.error("POST", "/api/v1/chats", actor=self.alice, body={"title": "Чат", "member_ids": members})
|
|
for title in ("", " \t", "я" * 101, 123):
|
|
self.error("POST", "/api/v1/chats", actor=self.alice, body={"title": title, "member_ids": valid})
|
|
self.error("POST", "/api/v1/chats", actor=self.alice, body={"title": "Чат", "member_ids": valid, "extra": 1})
|
|
self.assertEqual(before, self.get_page("/api/v1/chats")["items"])
|
|
|
|
def test_message_fields_and_unicode(self):
|
|
bodies = [{"text": value} for value in ("", " \t\n", "я" * 4001, None, 123, True, [])]
|
|
bodies += [{}, {"text": "Hi", "sender_id": self.bob["id"]}, {"text": "Hi", "unexpected": []}]
|
|
for body in bodies:
|
|
self.error("POST", self.path + "/messages", actor=self.alice, body=body)
|
|
for text in (" Привет, мир 👋\n", "👋" * 4000):
|
|
message = self.client.message(self.alice, self.chat, text)["json"]
|
|
self.assertEqual(message["text"], text)
|
|
self.assertEqual(message["sender_id"], self.alice["id"])
|
|
|
|
def test_message_pagination(self):
|
|
self.assertEqual(self.get_page(self.path + "/messages"), {"items": [], "next_cursor": None})
|
|
self.assertEqual(self.get_page(self.path + "/messages", limit="0000000001")["items"], [])
|
|
sent = [self.client.message(self.alice if i % 2 else self.bob, self.chat, str(i))["json"] for i in range(6)]
|
|
received, cursor = [], None
|
|
for limit in (2, 3, 1):
|
|
query = {"limit": limit}
|
|
if cursor:
|
|
query["cursor"] = cursor
|
|
page = self.get_page(self.path + "/messages", self.bob, **query)
|
|
received.extend(page["items"])
|
|
cursor = page["next_cursor"]
|
|
self.assertIsNone(cursor)
|
|
self.assertEqual(received, sorted(sent, key=lambda item: (timestamp(item["created_at"]), item["id"])))
|
|
|
|
def test_chat_pagination(self):
|
|
chats = [self.chat] + [self.new_chat() for _ in range(4)]
|
|
received, cursor = [], None
|
|
while True:
|
|
query = {"limit": 2}
|
|
if cursor:
|
|
query["cursor"] = cursor
|
|
page = self.get_page("/api/v1/chats", **query)
|
|
received += page["items"]
|
|
cursor = page["next_cursor"]
|
|
if cursor is None:
|
|
break
|
|
self.assertEqual(received, sorted(chats, key=lambda item: (timestamp(item["created_at"]), item["id"])))
|
|
cursor = self.get_page("/api/v1/chats", limit=1)["next_cursor"]
|
|
self.error("GET", "/api/v1/chats?" + urlencode({"cursor": cursor}), actor=self.bob)
|
|
|
|
def test_bad_cursors_and_limits(self):
|
|
for i in range(2):
|
|
self.client.message(self.alice, self.chat, str(i))
|
|
cursor = self.get_page(self.path + "/messages", limit=1)["next_cursor"]
|
|
for value in ("", "bad", cursor[:-1] + ("0" if cursor[-1] != "0" else "1")):
|
|
self.error("GET", self.path + "/messages?" + urlencode({"cursor": value}), actor=self.alice)
|
|
other = self.new_chat()
|
|
self.error("GET", "/api/v1/chats/" + other["id"] + "/messages?" + urlencode({"cursor": cursor}), actor=self.alice)
|
|
self.error("GET", "/api/v1/chats?" + urlencode({"cursor": cursor}), actor=self.alice)
|
|
for path in ("/api/v1/chats", self.path + "/messages"):
|
|
for value in ("", "0", "-1", "101", "1.5", "true", "9" * 500):
|
|
self.error("GET", path + "?" + urlencode({"limit": value}), actor=self.alice)
|
|
|
|
def test_read_after_write(self):
|
|
first = self.client.message(self.alice, self.chat, "Первое")["json"]
|
|
second = self.client.message(self.bob, self.chat, "Второе")["json"]
|
|
page = self.get_page(self.path + "/messages", limit=1)
|
|
third = self.client.message(self.bob, self.chat, "Новое")["json"]
|
|
rest = self.get_page(self.path + "/messages", self.bob, cursor=page["next_cursor"])
|
|
self.assertEqual(page["items"] + rest["items"], [first, second, third])
|
|
self.assertIsNone(rest["next_cursor"])
|
|
|
|
def test_parallel_messages(self):
|
|
def send(worker):
|
|
client = Client(self.client.base)
|
|
return [client.message(self.alice, self.chat, f"{worker}:{i}")["json"]["id"] for i in range(10)]
|
|
with ThreadPoolExecutor(max_workers=10) as pool:
|
|
sent = [item for group in pool.map(send, range(10)) for item in group]
|
|
received, cursor = [], None
|
|
while True:
|
|
query = {"limit": 17}
|
|
if cursor:
|
|
query["cursor"] = cursor
|
|
page = self.get_page(self.path + "/messages", self.bob, **query)
|
|
received += page["items"]
|
|
cursor = page["next_cursor"]
|
|
if cursor is None:
|
|
break
|
|
self.assertEqual(len(received), 100)
|
|
self.assertEqual(len({item["text"] for item in received}), 100)
|
|
self.assertEqual({item["id"] for item in received}, set(sent))
|
|
|
|
def test_parallel_username(self):
|
|
body = {"username": "u_" + uuid4().hex[:20], "display_name": "Один", "password": "T3st-password-123"}
|
|
def create(_):
|
|
return Client(self.client.base).call("POST", "/api/v1/users", [201, 409], body=body, schema="User")["status"]
|
|
with ThreadPoolExecutor(max_workers=10) as pool:
|
|
statuses = list(pool.map(create, range(10)))
|
|
self.assertEqual(statuses.count(201), 1)
|
|
self.assertEqual(statuses.count(409), 9)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main(verbosity=2)
|