#!/usr/bin/env python3 """10 клиентов × 10 сообщений = 100 уникальных. Запуск: python tests/concurrent_test.py""" import json import urllib.error import urllib.request import uuid from concurrent.futures import ThreadPoolExecutor BASE = "http://localhost:8080" def call(method, path, body=None, actor=None): h = {"Accept": "application/json"} if actor: h["X-User-Id"] = actor 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(name): s, u = call("POST", "/api/v1/users", {"username": name, "display_name": name}) assert s == 201, f"create_user {name}: {s} {u}" return u def main(): users = [create_user(f"conc_{i}_{uuid.uuid4().hex[:6]}") for i in range(10)] s, chat = call( "POST", "/api/v1/chats", {"title": "concurrent", "member_ids": [u["id"] for u in users]}, actor=users[0]["id"], ) assert s == 201, f"chat: {s} {chat}" cid = chat["id"] def post_10(user): results = [] for k in range(10): s, m = call( "POST", f"/api/v1/chats/{cid}/messages", {"text": f"{user['username']}-{k}"}, actor=user["id"], ) 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, actor=users[0]["id"]) assert s == 200 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()