""" HTTP smoke-тест для Lab1. Проверяет всю цепочку "живьём" по сети: health -> регистрация двух пользователей -> создание чата -> отправка сообщения -> чтение истории -> проверка отказа доступа для постороннего -> проверка формата ошибок. Запуск (сервер должен быть уже поднят, например через docker run): python smoke_test.py http://localhost:8080 """ import sys import uuid import httpx BASE_URL = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080" def check(condition: bool, message: str) -> None: if not condition: raise AssertionError(f"FAILED: {message}") print(f"OK: {message}") def main() -> None: client = httpx.Client(base_url=BASE_URL, timeout=10.0) # 1. Health r = client.get("/health/live") check(r.status_code == 200, "GET /health/live -> 200") check(r.json() == {"status": "ok"}, "health/live body") check(bool(r.headers.get("X-Request-Id")), "health/live has X-Request-Id") r = client.get("/health/ready") check(r.status_code == 200, "GET /health/ready -> 200") # 2. Регистрация двух пользователей uname_a = f"alice_{uuid.uuid4().hex[:8]}" r = client.post("/api/v1/users", json={"username": uname_a, "display_name": "Алиса"}) check(r.status_code == 201, "POST /api/v1/users (alice) -> 201") alice = r.json() check("password" not in alice and "password_hash" not in alice, "no password leaked in User") uname_b = f"bob_{uuid.uuid4().hex[:8]}" r = client.post("/api/v1/users", json={"username": uname_b, "display_name": "Боб"}) check(r.status_code == 201, "POST /api/v1/users (bob) -> 201") bob = r.json() # Повторная регистрация с тем же username -> 409 r = client.post("/api/v1/users", json={"username": uname_a, "display_name": "Дубликат"}) check(r.status_code == 409, "duplicate username -> 409") check(r.json()["error"]["code"] == "conflict", "error.code == conflict") check(r.json()["error"]["request_id"] == r.headers["X-Request-Id"], "error.request_id matches header") # 3. GET /users/me без заголовка -> 401 r = client.get("/api/v1/users/me") check(r.status_code == 401, "GET /users/me without X-User-Id -> 401") r = client.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]}) check(r.status_code == 200, "GET /users/me with valid X-User-Id -> 200") check(r.json()["username"] == uname_a, "me returns correct user") # 4. Создание чата (caller должен быть среди участников) r = client.post( "/api/v1/chats", headers={"X-User-Id": alice["id"]}, json={"title": "Lab1 smoke chat", "member_ids": [alice["id"], bob["id"]]}, ) check(r.status_code == 201, "POST /api/v1/chats -> 201") chat = r.json() # caller не включён в member_ids -> 400 r = client.post( "/api/v1/chats", headers={"X-User-Id": alice["id"]}, json={"title": "Bad chat", "member_ids": [bob["id"]]}, ) check(r.status_code == 400, "chat without caller in member_ids -> 400") # 5. Отправка сообщения r = client.post( f"/api/v1/chats/{chat['id']}/messages", headers={"X-User-Id": alice["id"]}, json={"text": "Привет, Боб!"}, ) check(r.status_code == 201, "POST message -> 201") message = r.json() check(message["sender_id"] == alice["id"], "sender_id inferred from X-User-Id") # Пустой/пробельный текст -> 400 r = client.post( f"/api/v1/chats/{chat['id']}/messages", headers={"X-User-Id": alice["id"]}, json={"text": " "}, ) check(r.status_code == 400, "whitespace-only text -> 400") # 6. Чтение истории r = client.get(f"/api/v1/chats/{chat['id']}/messages", headers={"X-User-Id": bob["id"]}) check(r.status_code == 200, "GET history as bob (member) -> 200") check(len(r.json()["items"]) == 1, "history contains 1 message") # 7. Посторонний не должен видеть чат: 404, не 403 uname_c = f"carol_{uuid.uuid4().hex[:8]}" r = client.post("/api/v1/users", json={"username": uname_c, "display_name": "Кэрол"}) carol = r.json() r = client.get(f"/api/v1/chats/{chat['id']}", headers={"X-User-Id": carol["id"]}) check(r.status_code == 404, "stranger gets 404, not 403, for foreign chat") print("\nALL SMOKE CHECKS PASSED") if __name__ == "__main__": main()