forked from mtusi2026/mtusi2026lab3
Complete Lab 3 for Grade 5 (Track 1)
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
import base64
|
||||
import time
|
||||
import uuid
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
BASE_URL = "http://localhost:8080"
|
||||
|
||||
def get_client():
|
||||
return httpx.Client(base_url=BASE_URL, trust_env=False, timeout=10.0)
|
||||
|
||||
def get_auth_token(client, username, password):
|
||||
client.post("/users", json={"username": username, "display_name": "User", "password": password})
|
||||
b64 = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8")
|
||||
res = client.post("/auth/sessions", headers={"Authorization": f"Basic {b64}"})
|
||||
return res.json()["token"], res.json()["user"]["id"]
|
||||
|
||||
def test_missing_or_invalid_idempotency_key():
|
||||
with get_client() as client:
|
||||
ts = int(time.time() * 1000)
|
||||
token, uid = get_auth_token(client, f"u_idem_{ts}", "password_12345678")
|
||||
h = {"Authorization": f"Bearer {token}"}
|
||||
|
||||
chat = client.post("/chats", json={"title": "Chat", "member_ids": [uid]}, headers=h).json()
|
||||
cid = chat["id"]
|
||||
|
||||
# Отсутствие ключа -> 400
|
||||
r1 = client.post(f"/chats/{cid}/messages", json={"text": "hello"}, headers=h)
|
||||
assert r1.status_code == 400
|
||||
|
||||
# Недопустимые символы в ключе -> 400
|
||||
h_bad = {**h, "Idempotency-Key": "bad key with spaces!"}
|
||||
r2 = client.post(f"/chats/{cid}/messages", json={"text": "hello"}, headers=h_bad)
|
||||
assert r2.status_code == 400
|
||||
|
||||
def test_idempotency_retry_and_conflict():
|
||||
with get_client() as client:
|
||||
ts = int(time.time() * 1000)
|
||||
token, uid = get_auth_token(client, f"u_retry_{ts}", "password_12345678")
|
||||
h = {"Authorization": f"Bearer {token}"}
|
||||
|
||||
chat = client.post("/chats", json={"title": "Chat", "member_ids": [uid]}, headers=h).json()
|
||||
cid = chat["id"]
|
||||
key = f"key_{uuid.uuid4()}"
|
||||
h_idem = {**h, "Idempotency-Key": key}
|
||||
|
||||
# Первый успешный запрос -> 201
|
||||
r1 = client.post(f"/chats/{cid}/messages", json={"text": "Same text"}, headers=h_idem)
|
||||
assert r1.status_code == 201
|
||||
msg1 = r1.json()
|
||||
|
||||
# Повтор с тем же ключом и тем же телом -> 201 и то же самое сообщение
|
||||
r2 = client.post(f"/chats/{cid}/messages", json={"text": "Same text"}, headers=h_idem)
|
||||
assert r2.status_code == 201
|
||||
msg2 = r2.json()
|
||||
assert msg1["id"] == msg2["id"]
|
||||
|
||||
# Попытка отправить другой текст с тем же ключом -> 409 Conflict
|
||||
r3 = client.post(f"/chats/{cid}/messages", json={"text": "Different text"}, headers=h_idem)
|
||||
assert r3.status_code == 409
|
||||
|
||||
# В чате должно остаться ровно 1 сообщение (дубликат не создан)
|
||||
history = client.get(f"/chats/{cid}/messages", headers=h).json()["items"]
|
||||
assert len(history) == 1
|
||||
|
||||
def test_load_balancer_alternates_instances():
|
||||
with get_client() as client:
|
||||
instances = set()
|
||||
for _ in range(10):
|
||||
res = client.get("/health/live")
|
||||
assert res.status_code == 200
|
||||
inst_id = res.headers.get("X-Instance-Id")
|
||||
if inst_id:
|
||||
instances.add(inst_id)
|
||||
|
||||
assert len(instances) >= 2, f"Ожидалось >= 2 реплик, зафиксировано: {instances}"
|
||||
Reference in New Issue
Block a user