Files
mtusi2026lab3/student-tests/test_chats_api.py
vest1ter cde3374d8a ЛР3: балансировка HAProxy, 2 реплики API, идемпотентность, отказоустойчивость (на 4)
- X-Instance-Id в каждом ответе; обязательный Idempotency-Key, таблица idempotency_keys
  (миграция 0002, одна транзакция, конкурентные повторы через уникальный индекс)
- graceful shutdown: SIGTERM -> ready=503 -> drain 3 с -> закрытие порта
- compose: lb (HAProxy) + api x2 без портов + разовый migrate + postgres, лимиты CPU/RAM
- хуки stop-one/restart/restore-replicas, scripts/experiments.py (failover, idempotency, rolling)
- свои тесты: 44 (13 новых); evidence: smoke, pytest, persistence, failover, эксперименты
2026-10-29 10:58:17 +03:00

55 lines
2.1 KiB
Python

import uuid
from sqlalchemy import text
from conftest import assert_error, with_key
from core.db import engine
def count_rows(table):
with engine.connect() as connection:
return connection.scalar(text(f"SELECT count(*) FROM {table}"))
def test_unknown_member_returns_400_and_nothing_is_saved(client, alice):
response = client.post("/api/v1/chats", headers=alice["auth"],
json={"title": "С призраком", "member_ids": [alice["id"], str(uuid.uuid4())]})
assert_error(response, 400, "invalid_request")
assert count_rows("chats") == 0
assert count_rows("chat_members") == 0
def test_created_chat_is_stored_with_members(client, chat, alice, bob):
assert sorted(chat["member_ids"]) == sorted([alice["id"], bob["id"]])
assert count_rows("chats") == 1
assert count_rows("chat_members") == 2
again = client.get("/api/v1/chats/" + chat["id"], headers=bob["auth"]).json()
assert again == chat
def test_foreign_chat_returns_404(client, chat, eve):
headers = eve["auth"]
path = "/api/v1/chats/" + chat["id"]
assert_error(client.get(path, headers=headers), 404, "not_found")
assert_error(client.get(path + "/messages", headers=headers), 404, "not_found")
assert_error(client.post(path + "/messages", headers=with_key(headers), json={"text": "чужое"}), 404, "not_found")
assert client.get("/api/v1/chats", headers=headers).json()["items"] == []
def test_member_sees_chat(client, chat, bob):
response = client.get("/api/v1/chats", headers=bob["auth"])
assert [c["id"] for c in response.json()["items"]] == [chat["id"]]
def test_creator_must_be_member(client, alice, bob):
response = client.post("/api/v1/chats", headers=alice["auth"],
json={"title": "Без меня", "member_ids": [bob["id"]]})
assert_error(response, 400, "invalid_request")
def test_duplicate_members_return_400(client, alice):
response = client.post("/api/v1/chats", headers=alice["auth"],
json={"title": "Дубли", "member_ids": [alice["id"], alice["id"]]})
assert_error(response, 400, "invalid_request")