58 lines
2.1 KiB
Python
58 lines
2.1 KiB
Python
"""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()
|