forked from mtusi2026/mtusi2026lab3
90 lines
3.0 KiB
Python
90 lines
3.0 KiB
Python
#!/usr/bin/env python3
|
|
import asyncio
|
|
import base64
|
|
import json
|
|
import urllib.request
|
|
import urllib.error
|
|
import uuid
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
BASE = "http://127.0.0.1:8080"
|
|
PASSWORD = "Example-only-not-a-real-secret-123"
|
|
|
|
def call(method, path, body=None, token=None):
|
|
h = {"Accept": "application/json"}
|
|
if token:
|
|
h["Authorization"] = f"Bearer {token}"
|
|
# ДОБАВЛЯЕМ IDEMPOTENCY-KEY ДЛЯ POST
|
|
if method == "POST" and "/messages" in path:
|
|
h["Idempotency-Key"] = uuid.uuid4().hex
|
|
|
|
data = None
|
|
if body is not None:
|
|
data = json.dumps(body).encode("utf-8")
|
|
h["Content-Type"] = "application/json"
|
|
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=30) as r:
|
|
payload = r.read()
|
|
return r.status, (json.loads(payload) if payload else None)
|
|
except urllib.error.HTTPError as e:
|
|
payload = e.read()
|
|
return e.code, (json.loads(payload) if payload else None)
|
|
|
|
def create_user_and_login(name):
|
|
s, u = call("POST", "/api/v1/users",
|
|
{"username": name, "display_name": name, "password": PASSWORD})
|
|
assert s == 201, f"create_user {name}: {s} {u}"
|
|
cred = base64.b64encode(f"{name}:{PASSWORD}".encode()).decode()
|
|
req = urllib.request.Request(
|
|
BASE + "/api/v1/auth/sessions",
|
|
headers={"Authorization": f"Basic {cred}"},
|
|
method="POST",
|
|
)
|
|
with urllib.request.urlopen(req, timeout=30) as r:
|
|
session = json.loads(r.read())
|
|
return u, session["token"]
|
|
|
|
def main():
|
|
users = [create_user_and_login(f"conc_{i}_{uuid.uuid4().hex[:6]}") for i in range(10)]
|
|
owner, owner_token = users[0]
|
|
chat = call("POST", "/api/v1/chats",
|
|
{"title": "concurrent", "member_ids": [u["id"] for u, _ in users]},
|
|
token=owner_token)[1]
|
|
cid = chat["id"]
|
|
|
|
def post_10(user_and_token):
|
|
_, token = user_and_token
|
|
results = []
|
|
for k in range(10):
|
|
s, m = call("POST", f"/api/v1/chats/{cid}/messages",
|
|
{"text": f"m{k}"}, token=token)
|
|
results.append((s, m))
|
|
return results
|
|
|
|
with ThreadPoolExecutor(max_workers=10) as ex:
|
|
results = []
|
|
for fut in [ex.submit(post_10, u) for u in users]:
|
|
results.extend(fut.result())
|
|
|
|
failures = [r for r in results if r[0] != 201]
|
|
assert not failures, f"{len(failures)} failed posts"
|
|
|
|
seen, cursor = set(), None
|
|
while True:
|
|
path = f"/api/v1/chats/{cid}/messages?limit=100"
|
|
if cursor:
|
|
path += f"&cursor={cursor}"
|
|
s, page = call("GET", path, token=owner_token)
|
|
for m in page["items"]:
|
|
seen.add(m["id"])
|
|
cursor = page["next_cursor"]
|
|
if not cursor:
|
|
break
|
|
|
|
print(f"unique messages: {len(seen)} / 100")
|
|
assert len(seen) == 100, f"expected 100, got {len(seen)}"
|
|
print("PASS: no lost or duplicated messages")
|
|
|
|
if __name__ == "__main__":
|
|
main() |