"""Concurrent registration race and parallel messages.""" from __future__ import annotations import concurrent.futures import uuid from helpers import BASE_URL, call, register def test_parallel_messages_unique(): a = register("par") b = register("parb") chat = call( "POST", "/api/v1/chats", 201, token=a["token"], body={"title": "parallel", "member_ids": [a["id"], b["id"]]}, )["json"] def send(i: int): return call( "POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=a["token"], body={"text": f"msg-{i}"}, )["json"]["id"] with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool: ids = list(pool.map(send, range(100))) assert len(ids) == len(set(ids)) == 100 def test_username_race_one_winner(): username = "race_" + uuid.uuid4().hex[:12] password = "T3st-" + uuid.uuid4().hex body = { "username": username, "display_name": "Race", "password": password, } def attempt(_): import json import urllib.error import urllib.request raw = json.dumps(body).encode("utf-8") req = urllib.request.Request( BASE_URL + "/api/v1/users", data=raw, headers={"Content-Type": "application/json", "Accept": "application/json"}, method="POST", ) try: resp = urllib.request.urlopen(req, timeout=30) except urllib.error.HTTPError as err: resp = err return resp.code with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: codes = list(pool.map(attempt, range(8))) assert codes.count(201) == 1, codes assert codes.count(409) == 7, codes