#!/usr/bin/env python3 import json import threading import urllib.error import urllib.request import uuid BASE_URL = "http://localhost:8080" def register(username: str, barrier: threading.Barrier) -> tuple[int, dict]: body = json.dumps( { "username": username, "display_name": "Race User", "password": "correct-password-123", } ).encode("utf-8") request = urllib.request.Request( BASE_URL + "/api/v1/users", data=body, headers={"Content-Type": "application/json"}, method="POST", ) # Оба потока доходят сюда и только потом одновременно продолжают. barrier.wait() try: with urllib.request.urlopen(request, timeout=10) as response: return response.status, json.loads(response.read()) except urllib.error.HTTPError as error: return error.code, json.loads(error.read()) def main() -> None: username = "race_" + uuid.uuid4().hex[:16] barrier = threading.Barrier(2) results: list[tuple[int, dict] | None] = [None, None] def worker(index: int) -> None: results[index] = register(username, barrier) threads = [ threading.Thread(target=worker, args=(0,)), threading.Thread(target=worker, args=(1,)), ] for thread in threads: thread.start() for thread in threads: thread.join() statuses = sorted(result[0] for result in results if result is not None) if statuses != [201, 409]: raise AssertionError( f"expected exactly one 201 and one 409, got {statuses}" ) created = [ result for result in results if result is not None and result[0] == 201 ] conflicts = [ result for result in results if result is not None and result[0] == 409 ] if len(created) != 1 or created[0][1]["username"] != username: raise AssertionError("unexpected successful registration response") if ( len(conflicts) != 1 or conflicts[0][1]["error"]["code"] != "conflict" ): raise AssertionError("unexpected conflict response") print( "PASS: concurrent registration produced exactly " "one 201 and one 409." ) if __name__ == "__main__": main()