"""Общие свойства API: заголовки, формат ошибок, health и логи.""" import re from conftest import assert_error def test_health_endpoints(client): assert client.get("/health/live").json() == {"status": "ok"} assert client.get("/health/ready").json() == {"status": "ok"} def test_every_response_has_unique_request_id(client, alice): seen = set() for reply in [ client.get("/health/live"), client.get("/health/ready"), client.get("/api/v1/users/me", headers=alice.headers), client.get("/api/v1/users/me"), client.get("/no/such/page"), client.delete("/api/v1/chats"), ]: assert reply.headers.get("X-Request-Id") seen.add(reply.headers["X-Request-Id"]) assert len(seen) == 6 def test_unknown_path_is_404_in_common_format(client): assert_error(client.get("/api/v1/nothing"), 404, "not_found") def test_trailing_slash_is_not_redirected(client, alice): assert_error( client.get("/api/v1/chats/", headers=alice.headers, follow_redirects=False), 404, "not_found", ) def test_wrong_method_is_405_in_common_format(client): assert_error(client.delete("/api/v1/users"), 405, "invalid_request") def test_two_users_one_chat_two_messages(client, alice, bob, eve, chat): """Двое переписываются, посторонний получает 404.""" url = "/api/v1/chats/" + chat["id"] + "/messages" assert ( client.post( url, json={"text": "Привет, Боб!"}, headers=alice.headers ).status_code == 201 ) assert ( client.post( url, json={"text": "Привет, Алиса!"}, headers=bob.headers ).status_code == 201 ) history = client.get(url, headers=alice.headers).json()["items"] assert [m["text"] for m in history] == ["Привет, Боб!", "Привет, Алиса!"] assert [m["sender_id"] for m in history] == [alice.id, bob.id] assert client.get(url, headers=eve.headers).status_code == 404 def test_chat_response_shape(client, alice, bob, chat): assert set(chat) == {"id", "title", "member_ids", "created_at"} assert set(chat["member_ids"]) == {alice.id, bob.id} assert re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{6}Z", chat["created_at"]) assert client.get("/api/v1/chats/" + chat["id"], headers=bob.headers).json() == chat def test_unexpected_exception_gives_500_without_details(client, log_lines): async def boom(): raise RuntimeError("ТАЙНЫЙ-ТЕКСТ-ИЗ-ОШИБКИ") client.app.add_api_route("/boom", boom) reply = client.get("/boom") assert_error(reply, 500, "internal_error") assert "ТАЙНЫЙ" not in reply.text assert not any("ТАЙНЫЙ" in line for line in log_lines) assert any("unhandled_error" in line for line in log_lines) def test_logs_have_requests_but_no_secrets(client, alice, chat, log_lines): """В логе есть запросы, но нет текста сообщений, паролей и токенов.""" secret = "ОЧЕНЬ-СЕКРЕТНОЕ-СООБЩЕНИЕ-12345" url = "/api/v1/chats/" + chat["id"] + "/messages" client.post(url, json={"text": secret}, headers=alice.headers) client.get(url, headers=alice.headers) joined = "\n".join(log_lines) assert ( "method=POST" in joined and "status=201" in joined and "request_id=" in joined ) for hidden in (secret, alice.token, alice.password): assert hidden not in joined