forked from mtusi2026/mtusi2026lab3
feat-(4 level done, ready to 5)
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
import requests
|
||||
import uuid
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
BASE_URL = "http://localhost:8080"
|
||||
|
||||
def setup_test_data():
|
||||
username = f"idem_test_{uuid.uuid4().hex[:8]}"
|
||||
password = "SecurePassword123!"
|
||||
|
||||
r = requests.post(f"{BASE_URL}/api/v1/users", json={
|
||||
"username": username, "display_name": "Test User", "password": password
|
||||
})
|
||||
r.raise_for_status()
|
||||
|
||||
creds = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
r = requests.post(f"{BASE_URL}/api/v1/auth/sessions", headers={"Authorization": f"Basic {creds}"})
|
||||
r.raise_for_status()
|
||||
token = r.json()["token"]
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
|
||||
r = requests.post(f"{BASE_URL}/api/v1/chats", headers=headers, json={
|
||||
"title": "Idempotency Test Chat",
|
||||
"member_ids": [r.json()["user"]["id"]]
|
||||
})
|
||||
r.raise_for_status()
|
||||
chat_id = r.json()["id"]
|
||||
|
||||
return headers, chat_id
|
||||
|
||||
def send_message(headers, chat_id, idempotency_key, worker_id):
|
||||
r = requests.post(
|
||||
f"{BASE_URL}/api/v1/chats/{chat_id}/messages",
|
||||
headers={**headers, "Idempotency-Key": idempotency_key},
|
||||
json={"text": f"failover test message"}
|
||||
)
|
||||
return r.status_code, r.json().get("id") if r.status_code == 201 else None, r.text
|
||||
|
||||
def main():
|
||||
print("Проверка идемпотентности (параллельные запросы с одним ключом)")
|
||||
headers, chat_id = setup_test_data()
|
||||
idempotency_key = f"failover-test-key-{uuid.uuid4().hex}"
|
||||
|
||||
print(f"Отправка 5 параллельных запросов с ключом: {idempotency_key}")
|
||||
|
||||
results = []
|
||||
with ThreadPoolExecutor(max_workers=5) as executor:
|
||||
futures = [executor.submit(send_message, headers, chat_id, idempotency_key, i) for i in range(5)]
|
||||
for future in as_completed(futures):
|
||||
results.append(future.result())
|
||||
|
||||
status_codes = [r[0] for r in results]
|
||||
message_ids = [r[1] for r in results]
|
||||
|
||||
print(f"Полученные статусы: {status_codes}")
|
||||
print(f"Полученные ID сообщений: {message_ids}")
|
||||
|
||||
if all(code == 201 for code in status_codes) and len(set(message_ids)) == 1:
|
||||
print(f"PASS: Идемпотентность работает! Создано ровно 1 сообщение (ID: {message_ids[0]}).")
|
||||
else:
|
||||
print("FAIL: Ожидалось 5 ответов '201' с одинаковым 'id'.")
|
||||
print("Детали ответов:", results)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user