Lab 2: PostgreSQL storage and Redis sessions
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,122 @@
|
||||
import sys
|
||||
import unittest
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, timestamp
|
||||
|
||||
|
||||
class ApiTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.c = Client()
|
||||
self.alice, self.bob, self.eve, self.chat = self.c.bootstrap()
|
||||
self.path = "/api/v1/chats/" + self.chat["id"]
|
||||
|
||||
def read_all(self, client, actor, path, limit=17):
|
||||
items = []
|
||||
cursor = None
|
||||
seen = set()
|
||||
for _ in range(1000):
|
||||
url = path + "?limit=" + str(limit)
|
||||
if cursor is not None:
|
||||
url += "&cursor=" + quote(cursor, safe="")
|
||||
page = client.call("GET", url, actor=actor, schema="MessagePage")["json"]
|
||||
items.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return items
|
||||
self.assertNotIn(cursor, seen, "cursor зациклился")
|
||||
seen.add(cursor)
|
||||
self.fail("Слишком много страниц")
|
||||
|
||||
def test_malformed_json(self):
|
||||
result = self.c.call("POST", "/api/v1/users", 400,
|
||||
raw=b'{"username":',
|
||||
headers={"Content-Type": "application/json"})
|
||||
self.assertEqual(result["json"]["error"]["code"], "invalid_request")
|
||||
|
||||
def test_foreign_chat(self):
|
||||
self.c.call("GET", self.path, 404, actor=self.eve)
|
||||
self.c.call("GET", self.path + "/messages", 404, actor=self.eve)
|
||||
self.c.call("POST", self.path + "/messages", 404,
|
||||
actor=self.eve, body={"text": "Чужой чат"})
|
||||
page = self.c.call("GET", "/api/v1/chats", actor=self.eve,
|
||||
schema="ChatPage")["json"]
|
||||
self.assertNotIn(self.chat["id"], [item["id"] for item in page["items"]])
|
||||
|
||||
def test_empty_message(self):
|
||||
for value in ("", " ", "\n\t"):
|
||||
with self.subTest(text=repr(value)):
|
||||
self.c.call("POST", self.path + "/messages", 400,
|
||||
actor=self.alice, body={"text": value})
|
||||
|
||||
def test_duplicate_username(self):
|
||||
self.c.call("POST", "/api/v1/users", 409,
|
||||
body=self.alice["registration"])
|
||||
|
||||
def test_multiple_pages_and_cursor_scope(self):
|
||||
expected = [self.c.message(self.alice, self.chat, "Страница " + str(i))["json"]
|
||||
for i in range(7)]
|
||||
actual = self.read_all(self.c, self.bob, self.path + "/messages", limit=2)
|
||||
self.assertEqual(actual, sorted(expected, key=lambda x:
|
||||
(timestamp(x["created_at"]), uuid.UUID(x["id"]).int)))
|
||||
self.assertEqual(len({item["id"] for item in actual}), 7)
|
||||
page = self.c.call("GET", self.path + "/messages?limit=1",
|
||||
actor=self.alice, schema="MessagePage")["json"]
|
||||
other = self.c.call("POST", "/api/v1/chats", 201, actor=self.alice,
|
||||
body={"title": "Другой", "member_ids": [self.alice["id"]]},
|
||||
schema="Chat")["json"]
|
||||
self.c.call("GET", "/api/v1/chats/" + other["id"] + "/messages?cursor="
|
||||
+ quote(page["next_cursor"], safe=""), 400, actor=self.alice)
|
||||
|
||||
def test_validation_and_auth(self):
|
||||
for body in ({"text": 123}, {"text": "ok", "sender_id": self.bob["id"]},
|
||||
{"text": "x" * 4001}):
|
||||
self.c.call("POST", self.path + "/messages", 400,
|
||||
actor=self.alice, body=body)
|
||||
for limit in ("0", "101", "abc", "1.5"):
|
||||
self.c.call("GET", self.path + "/messages?limit=" + limit,
|
||||
400, actor=self.alice)
|
||||
self.c.call("GET", self.path + "/messages?cursor=garbage", 400,
|
||||
actor=self.alice)
|
||||
self.c.call("GET", "/api/v1/users/me", 401)
|
||||
self.c.call("GET", "/api/v1/users/me", 401,
|
||||
headers={"X-User-Id": str(uuid.uuid4())})
|
||||
self.c.call("POST", self.path + "/messages", 401, raw=b'{',
|
||||
headers={"Content-Type": "application/json"})
|
||||
self.c.call("POST", self.path + "/messages", 415, actor=self.alice,
|
||||
raw=b'plain', headers={"Content-Type": "text/plain"})
|
||||
for members in ([self.alice["id"], self.alice["id"]],
|
||||
[self.bob["id"]], [self.alice["id"], str(uuid.uuid4())]):
|
||||
self.c.call("POST", "/api/v1/chats", 400, actor=self.alice,
|
||||
body={"title": "Неверный чат", "member_ids": members})
|
||||
|
||||
def test_concurrency_100_messages_10_clients(self):
|
||||
# У каждого из 10 потоков свой HTTP-клиент и 10 последовательных POST.
|
||||
def send_batch(worker):
|
||||
client = Client()
|
||||
sent = []
|
||||
for i in range(10):
|
||||
text = "worker=" + str(worker) + ";message=" + str(i)
|
||||
sent.append(client.message(self.alice, self.chat, text)["json"])
|
||||
return sent
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
batches = list(pool.map(send_batch, range(10)))
|
||||
sent = [item for batch in batches for item in batch]
|
||||
actual = self.read_all(self.c, self.bob, self.path + "/messages")
|
||||
self.assertEqual(len(sent), 100)
|
||||
self.assertEqual(len(actual), 100)
|
||||
self.assertEqual(len({item["id"] for item in actual}), 100)
|
||||
self.assertEqual({item["id"] for item in actual}, {item["id"] for item in sent})
|
||||
self.assertEqual({item["text"] for item in actual}, {item["text"] for item in sent})
|
||||
self.assertTrue(all(item["sender_id"] == self.alice["id"] for item in actual))
|
||||
print("PASS: 10 clients; 100 POST; 100 unique messages; IDs/text match")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
Reference in New Issue
Block a user