feat: add message history and concurrent writes

This commit is contained in:
Самохвалов Андрей Ремович
2026-10-01 21:27:53 +03:00
parent ac739713b3
commit 55ec45cc3d
4 changed files with 154 additions and 1 deletions
+52
View File
@@ -119,6 +119,58 @@ class APIContractTests(unittest.TestCase):
self.assert_error(*self.call("GET", next_path, actor=bob["id"]), 400)
self.assert_error(*self.call("GET", "/api/v1/chats?limit=0", actor=alice["id"]), 400)
def test_messages_access_validation_and_pages(self):
from urllib.parse import quote
def user(name):
status, _, value = self.call("POST", "/api/v1/users", json.dumps({"username": name, "display_name": name}).encode())
self.assertEqual(status, 201)
return value
alice, bob, eve = (user(name) for name in ("u3_alice", "u3_bob", "u3_eve"))
def chat():
body = json.dumps({"title": "U3 👋", "member_ids": [alice["id"], bob["id"]]}).encode()
status, _, value = self.call("POST", "/api/v1/chats", body, actor=alice["id"])
self.assertEqual(status, 201)
return value
first_chat, second_chat = chat(), chat()
path = f'/api/v1/chats/{first_chat["id"]}/messages'
other_path = f'/api/v1/chats/{second_chat["id"]}/messages'
def send(actor, body, target=path):
return self.call("POST", target, json.dumps(body, ensure_ascii=False).encode(), actor=actor)
for actor, text in ((alice, "Привет 👋"), (bob, "Ответ Боба"), (alice, "Третье сообщение")):
status, _, value = send(actor["id"], {"text": text})
self.assertEqual(status, 201)
self.assertEqual((value["chat_id"], value["sender_id"], value["text"]), (first_chat["id"], actor["id"], text))
seen = []
cursor = None
while True:
suffix = "?limit=1" + ("&cursor=" + quote(cursor, safe="") if cursor else "")
status, _, page = self.call("GET", path + suffix, actor=bob["id"])
self.assertEqual(status, 200)
self.assertEqual(len(page["items"]), 1)
seen.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
break
self.assertEqual([item["text"] for item in seen], ["Привет 👋", "Ответ Боба", "Третье сообщение"])
self.assertEqual(len({item["id"] for item in seen}), 3)
self.assertEqual(seen, sorted(seen, key=lambda item: (item["created_at"], item["id"])))
for body in ({"text": ""}, {"text": " "}, {"text": "a" * 4001}, {"text": "x", "sender_id": eve["id"]}):
self.assert_error(*send(alice["id"], body), 400)
self.assertEqual(send(alice["id"], {"text": "🌟" * 4000})[0], 201)
self.assert_error(*send(eve["id"], {"text": "чужое"}), 404)
self.assert_error(*self.call("GET", path, actor=eve["id"]), 404)
self.assert_error(*self.call("GET", path + "?limit=0", actor=alice["id"]), 400)
self.assert_error(*self.call("GET", path + "?cursor=broken", actor=alice["id"]), 400)
self.assert_error(*self.call("GET", other_path + "?cursor=" + quote(self.call("GET", path + "?limit=1", actor=alice["id"])[2]["next_cursor"], safe=""), actor=alice["id"]), 400)
if __name__ == "__main__":
unittest.main()
+57
View File
@@ -0,0 +1,57 @@
"""One 10-client / 100-message exercise of the in-memory store."""
from concurrent.futures import ThreadPoolExecutor
import json
import unittest
from urllib.parse import quote
import test_api
class ConcurrentMessagesTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
test_api.APIContractTests.setUpClass()
@classmethod
def tearDownClass(cls):
test_api.APIContractTests.tearDownClass()
def test_100_messages_from_10_clients(self):
call = test_api.APIContractTests.call
status, _, actor = call("POST", "/api/v1/users", b'{"username":"u3_concurrent","display_name":"Load"}')
self.assertEqual(status, 201)
body = json.dumps({"title": "Concurrent", "member_ids": [actor["id"]]}).encode()
status, _, chat = call("POST", "/api/v1/chats", body, actor=actor["id"])
self.assertEqual(status, 201)
path = f'/api/v1/chats/{chat["id"]}/messages'
def send(index):
body = json.dumps({"text": f"client-{index // 10}:message-{index}"}).encode()
status, _, result = call("POST", path, body, actor=actor["id"])
return status, result
with ThreadPoolExecutor(max_workers=10) as pool:
responses = list(pool.map(send, range(100)))
self.assertTrue(all(status == 201 for status, _ in responses))
expected = {result["id"]: result["text"] for _, result in responses}
self.assertEqual(len(expected), 100)
seen = {}
cursor = None
while True:
suffix = "?limit=17" + ("&cursor=" + quote(cursor, safe="") if cursor else "")
status, _, page = call("GET", path + suffix, actor=actor["id"])
self.assertEqual(status, 200)
for item in page["items"]:
self.assertNotIn(item["id"], seen)
seen[item["id"]] = item["text"]
cursor = page["next_cursor"]
if cursor is None:
break
self.assertEqual(seen, expected)
print("Concurrency evidence: 10 clients, 100 writes, 100 unique messages read")
if __name__ == "__main__":
unittest.main()