forked from mtusi2026/mtusi2026lab3
84 lines
2.8 KiB
Python
84 lines
2.8 KiB
Python
import base64
|
|
import uuid
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import httpx
|
|
|
|
BASE = "http://localhost:8080"
|
|
|
|
|
|
def _register_and_login(client: httpx.Client) -> dict:
|
|
username = "u_" + uuid.uuid4().hex[:10]
|
|
password = "Test-password-" + uuid.uuid4().hex[:8]
|
|
r = client.post(
|
|
f"{BASE}/api/v1/users",
|
|
json={
|
|
"username": username,
|
|
"display_name": "Тест",
|
|
"password": password,
|
|
},
|
|
)
|
|
user = r.json()
|
|
credential = base64.b64encode(
|
|
(username + ":" + password).encode("utf-8")
|
|
).decode("ascii")
|
|
r = client.post(
|
|
f"{BASE}/api/v1/auth/sessions",
|
|
headers={"Authorization": "Basic " + credential},
|
|
)
|
|
session = r.json()
|
|
return {"id": user["id"], "token": session["token"]}
|
|
|
|
|
|
def test_concurrent_writes_are_not_lost():
|
|
with httpx.Client() as c:
|
|
alice = _register_and_login(c)
|
|
bob = _register_and_login(c)
|
|
chat = c.post(
|
|
f"{BASE}/api/v1/chats",
|
|
json={"title": "race", "member_ids": [alice["id"], bob["id"]]},
|
|
headers={"Authorization": "Bearer " + alice["token"]},
|
|
).json()
|
|
|
|
def worker(worker_id: int):
|
|
with httpx.Client(timeout=10) as c:
|
|
for i in range(10):
|
|
r = c.post(
|
|
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
|
json={"text": f"w{worker_id}-m{i}"},
|
|
headers={
|
|
"Authorization": "Bearer " + alice["token"],
|
|
"Idempotency-Key": uuid.uuid4().hex,
|
|
},
|
|
)
|
|
if r.status_code != 201:
|
|
print(f"POST FAIL w{worker_id}-m{i}: {r.status_code} {r.text[:200]}")
|
|
|
|
with ThreadPoolExecutor(max_workers=10) as pool:
|
|
list(pool.map(worker, range(10)))
|
|
|
|
with httpx.Client() as c:
|
|
all_ids = []
|
|
cursor = None
|
|
while True:
|
|
params = {"limit": 100}
|
|
if cursor:
|
|
params["cursor"] = cursor
|
|
r = c.get(
|
|
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
|
params=params,
|
|
headers={"Authorization": "Bearer " + alice["token"]},
|
|
)
|
|
page = r.json()
|
|
if r.status_code != 200 or "items" not in page:
|
|
print(f"GET FAIL: {r.status_code} {r.text[:500]}")
|
|
print(f"chat_id: {chat['id']}")
|
|
print(f"alice_token: {alice['token'][:30]}...")
|
|
raise AssertionError(f"GET messages failed: {r.status_code}")
|
|
all_ids.extend(m["id"] for m in page["items"])
|
|
cursor = page["next_cursor"]
|
|
if not cursor:
|
|
break
|
|
|
|
print(f"Got {len(all_ids)} messages, unique: {len(set(all_ids))}")
|
|
assert len(all_ids) == 100
|
|
assert len(set(all_ids)) == 100 |