forked from mtusi2026/mtusi2026lab7
grade3
This commit is contained in:
+42
-104
@@ -1,109 +1,47 @@
|
||||
import concurrent.futures
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import json
|
||||
import unittest
|
||||
from client import Client
|
||||
import base64
|
||||
import uuid
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
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'
|
||||
|
||||
def main():
|
||||
args = arguments("Lab7 grade 3 negative checks")
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
|
||||
c.call("GET", f"/api/v1/chats/{chat['id']}", 404, actor=eve)
|
||||
c.call("GET", f"/api/v1/chats/{chat['id']}/messages", 404, actor=eve)
|
||||
|
||||
oversized = b"\x89PNG\r\n\x1a\n" + (b"0" * (10 * 1024 * 1024 + 100))
|
||||
c.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=big.png",
|
||||
413,
|
||||
actor=alice,
|
||||
raw=oversized,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
|
||||
bad_cred = base64.b64encode(f"{alice['registration']['username']}:wrong-pass-12345".encode()).decode()
|
||||
got_429 = False
|
||||
for _ in range(10):
|
||||
res = c.call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
[401, 429],
|
||||
headers={"Authorization": f"Basic {bad_cred}"},
|
||||
)
|
||||
self.chat = res['json']
|
||||
if res["status"] == 429:
|
||||
retry_after = res["headers"].get("Retry-After")
|
||||
check(retry_after is not None and int(retry_after) >= 1, "429 must include positive Retry-After")
|
||||
got_429 = True
|
||||
break
|
||||
check(got_429, "expected 429 after repeated failed login attempts")
|
||||
|
||||
def test_unauthorized_access_to_chat(self):
|
||||
self.client.call('GET', f"/api/v1/chats/{self.chat['id']}", 404, actor=self.eve)
|
||||
temp_user = c.user("logout_check")
|
||||
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=temp_user)
|
||||
c.call("GET", "/api/v1/users/me", 401, actor=temp_user)
|
||||
|
||||
def test_empty_message(self):
|
||||
self.client.call('POST', f"/api/v1/chats/{self.chat['id']}/messages", 400, actor=self.alice, body={"text": ""})
|
||||
print("PASS: grade 3 negative checks (ACL 404, upload 413, login 429+Retry-After, logout 401)")
|
||||
|
||||
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()
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user