forked from mtusi2026/mtusi2026lab2
73 lines
2.2 KiB
Python
73 lines
2.2 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):
|
|
c.post(
|
|
f"{BASE}/api/v1/chats/{chat['id']}/messages",
|
|
json={"text": f"w{worker_id}-m{i}"},
|
|
headers={"Authorization": "Bearer " + alice["token"]},
|
|
)
|
|
|
|
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()
|
|
all_ids.extend(m["id"] for m in page["items"])
|
|
cursor = page["next_cursor"]
|
|
if not cursor:
|
|
break
|
|
|
|
assert len(all_ids) == 100
|
|
assert len(set(all_ids)) == 100 |