94 lines
3.2 KiB
Python
94 lines
3.2 KiB
Python
"""Adapted from Karpova lab1 archive: password + Basic/Bearer transition only."""
|
|
"""100 concurrent message writes from 10 client identities."""
|
|
import base64
|
|
import json
|
|
import os
|
|
import uuid
|
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
from urllib.error import HTTPError
|
|
from urllib.parse import quote
|
|
from urllib.request import Request, urlopen
|
|
|
|
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
|
|
|
|
|
|
def call(method, path, *, body=None, actor=None):
|
|
headers = {"Accept": "application/json", "Content-Type": "application/json"}
|
|
if actor:
|
|
headers["Authorization"] = "Bearer " + actor["token"]
|
|
raw = json.dumps(body, ensure_ascii=False).encode("utf-8") if body is not None else None
|
|
request = Request(BASE_URL + path, data=raw, headers=headers, method=method)
|
|
try:
|
|
response = urlopen(request, timeout=10)
|
|
status = response.status
|
|
data = response.read()
|
|
except HTTPError as error:
|
|
status = error.code
|
|
data = error.read()
|
|
payload = json.loads(data) if data else None
|
|
return status, payload
|
|
|
|
|
|
def create_user(label):
|
|
status, payload = call(
|
|
"POST",
|
|
"/api/v1/users",
|
|
body={
|
|
"username": "c_" + label + "_" + uuid.uuid4().hex[:8],
|
|
"display_name": "Client " + label, "password": "Synthetic-lab1-port-123",
|
|
},
|
|
)
|
|
assert status == 201, (status, payload)
|
|
basic = base64.b64encode((payload['username']+':Synthetic-lab1-port-123').encode()).decode()
|
|
req = Request(BASE_URL+'/api/v1/auth/sessions', method='POST', headers={'Authorization':'Basic '+basic})
|
|
with urlopen(req, timeout=10) as response:
|
|
payload['token'] = json.load(response)['token']
|
|
return payload
|
|
|
|
|
|
def main():
|
|
clients = [create_user(str(i)) for i in range(10)]
|
|
status, chat = call(
|
|
"POST",
|
|
"/api/v1/chats",
|
|
actor=clients[0],
|
|
body={"title": "Concurrent test", "member_ids": [x["id"] for x in clients]},
|
|
)
|
|
assert status == 201, (status, chat)
|
|
|
|
def send(client_index):
|
|
actor = clients[client_index]
|
|
status, payload = call(
|
|
"POST",
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
actor=actor,
|
|
body={"text": f"concurrent-client-{client_index}-message-{uuid.uuid4().hex}"},
|
|
)
|
|
return status, payload
|
|
|
|
results = []
|
|
with ThreadPoolExecutor(max_workers=10) as pool:
|
|
futures = [pool.submit(send, i % 10) for i in range(100)]
|
|
for future in as_completed(futures):
|
|
results.append(future.result())
|
|
|
|
statuses = [status for status, _ in results]
|
|
assert all(status == 201 for status in statuses), f"unexpected statuses: {statuses}"
|
|
|
|
status, page = call(
|
|
"GET",
|
|
f"/api/v1/chats/{chat['id']}/messages?limit=100",
|
|
actor=clients[0],
|
|
)
|
|
assert status == 200, (status, page)
|
|
ids = [item["id"] for item in page["items"]]
|
|
assert len(ids) == 100, f"expected 100 messages, got {len(ids)}"
|
|
assert len(set(ids)) == 100, "message IDs are not unique"
|
|
assert page["next_cursor"] is None, "100 messages should fit one page"
|
|
|
|
print("PASS: 10 concurrent clients -> 100 successful messages -> 100 unique messages")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|