Files
mtusi2026lab3/tests/custom_tests.py
T
2026-11-09 11:11:33 +03:00

109 lines
3.9 KiB
Python

import concurrent.futures
import urllib.request
import urllib.error
import json
import unittest
from client import Client
class TestMessengerLab4(unittest.TestCase):
def setUp(self):
self.client = Client()
self.alice = self.client.user("alice")
self.bob = self.client.user("bob")
self.eve = self.client.user("eve")
res = self.client.call(
'POST', '/api/v1/chats', 201,
actor=self.alice,
body={"title": "Test Chat", "member_ids": [self.alice["id"], self.bob["id"]]},
schema='Chat'
)
self.chat = res['json']
def test_unauthorized_access_to_chat(self):
self.client.call('GET', f"/api/v1/chats/{self.chat['id']}", 404, actor=self.eve)
def test_empty_message(self):
self.client.call('POST', f"/api/v1/chats/{self.chat['id']}/messages", 400, actor=self.alice, body={"text": ""})
def test_malformed_json(self):
url = self.client.base + f"/api/v1/chats/{self.chat['id']}/messages"
req = urllib.request.Request(
url,
data=b"{broken json content without quotes",
headers={
"Content-Type": "application/json",
"X-User-Id": self.alice["id"]
},
method="POST"
)
try:
with urllib.request.urlopen(req) as resp:
self.fail("Expected HTTP 400 for malformed JSON")
except urllib.error.HTTPError as e:
self.assertEqual(e.code, 400)
body = json.loads(e.read().decode())
self.assertEqual(body["error"]["code"], "invalid_request")
def test_duplicate_username(self):
self.client.call('POST', '/api/v1/users', 409, body=self.alice["registration"])
def test_pagination_multiple_pages(self):
import time
msg_texts = ["msg-page-1", "msg-page-2", "msg-page-3"]
for txt in msg_texts:
self.client.message(self.alice, self.chat, txt)
time.sleep(0.01)
path = f"/api/v1/chats/{self.chat['id']}/messages"
collected_items = []
cursor = None
for _ in range(5):
url_suffix = "?limit=1"
if cursor:
url_suffix += f"&cursor={cursor}"
page_res = self.client.call('GET', path + url_suffix, actor=self.alice, schema='MessagePage')
page = page_res['json']
for item in page['items']:
self.assertNotIn(item['id'], [x['id'] for x in collected_items])
collected_items.append(item)
cursor = page.get('next_keyword') or page.get('next_cursor')
if not cursor:
break
self.assertEqual(len(collected_items), 3)
self.assertEqual(sorted([x['text'] for x in collected_items]), sorted(msg_texts))
def test_concurrent_messages_strict(self):
def worker_send(worker_idx):
local_client = Client()
ids = []
for i in range(10):
res = local_client.message(self.alice, self.chat, f"w-{worker_idx}-msg-{i}")
ids.append(res['json']['id'])
return ids
all_ids = []
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
futures = [executor.submit(worker_send, w) for w in range(10)]
for f in concurrent.futures.as_completed(futures):
all_ids.extend(f.result())
self.assertEqual(len(all_ids), 100)
self.assertEqual(len(set(all_ids)), 100)
page = self.client.call(
'GET', f"/api/v1/chats/{self.chat['id']}/messages?limit=100",
actor=self.alice,
schema='MessagePage'
)
server_ids = [m['id'] for m in page['json']['items']]
self.assertEqual(len(server_ids), 100)
self.assertEqual(len(set(server_ids)), 100)
if __name__ == '__main__':
unittest.main()