Files
2026-10-30 12:32:42 +03:00

197 lines
6.5 KiB
Python

from uuid import uuid4
import pytest
from httpx import AsyncClient
from conftest import PASSWORD, actor, make_chat, register
ERROR_CODES = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
409: "conflict",
}
def assert_error(response, expected_status: int) -> None:
assert response.status_code == expected_status, response.text
assert response.headers.get("content-type", "").startswith("application/json")
body = response.json()
assert set(body) == {"error"}
assert set(body["error"]) == {"code", "message", "request_id"}
assert body["error"]["code"] == ERROR_CODES[expected_status]
assert body["error"]["message"]
assert body["error"]["request_id"] == response.headers["X-Request-Id"]
async def test_malformed_json(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/users",
content=b'{"username": ',
headers={"Content-Type": "application/json"},
)
assert_error(response, 400)
async def test_unexpected_field(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/users",
json={"username": "abc_def", "display_name": "X", "password": PASSWORD, "role": "admin"},
)
assert_error(response, 400)
async def test_wrong_types(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/users", json={"username": 1, "display_name": True, "password": 12345678901234}
)
assert_error(response, 400)
@pytest.mark.parametrize(
"body",
[
{"username": "Alice", "display_name": "X", "password": PASSWORD},
{"username": "ab", "display_name": "X", "password": PASSWORD},
{"username": "alice_01\n", "display_name": "X", "password": PASSWORD},
{"username": "abc_def", "display_name": "", "password": PASSWORD},
{"username": "abc_def", "display_name": " ", "password": PASSWORD},
{"username": "abc_def", "display_name": "x" * 101, "password": PASSWORD},
{"username": "abc_def", "display_name": "X", "password": "short"},
{"username": "abc_def", "display_name": "X", "password": "x" * 129},
{"username": "abc_def", "display_name": "X", "password": " " * 20},
{"username": "abc_def", "display_name": "X"},
{"username": "abc_def", "password": PASSWORD},
],
)
async def test_invalid_registration(client: AsyncClient, body: dict) -> None:
assert_error(await client.post("/api/v1/users", json=body), 400)
async def test_duplicate_username(client: AsyncClient) -> None:
alice = await register(client, "alice")
repeat = await client.post(
"/api/v1/users",
json={"username": alice["username"], "display_name": "Другая", "password": PASSWORD},
)
assert_error(repeat, 409)
async def test_missing_identity(client: AsyncClient) -> None:
assert_error(await client.get("/api/v1/users/me"), 401)
BAD_AUTHORIZATIONS = [
"",
"Bearer",
"Bearer ",
"Bearer not a token",
"Bearer " + "x" * 43,
"Token abcdef",
"11111111-1111-4111-8111-111111111111",
]
@pytest.mark.parametrize("raw", BAD_AUTHORIZATIONS)
async def test_invalid_bearer(client: AsyncClient, raw: str) -> None:
response = await client.get("/api/v1/users/me", headers={"Authorization": raw})
assert_error(response, 401)
assert response.headers["WWW-Authenticate"] == 'Bearer realm="messenger"'
async def test_user_id_header_alone_is_ignored(client: AsyncClient) -> None:
alice = await register(client, "alice")
response = await client.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]})
assert_error(response, 401)
async def test_identity_checked_before_body(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/chats",
content=b"{broken",
headers={"Content-Type": "application/json"},
)
assert_error(response, 401)
async def test_empty_message_rejected(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
for text in ("", " ", "\n\t"):
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": text},
headers=actor(alice),
)
assert_error(response, 400)
async def test_long_message_rejected(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "я" * 4001},
headers=actor(alice),
)
assert_error(response, 400)
async def test_sender_id_not_accepted(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "подмена", "sender_id": bob["id"]},
headers=actor(alice),
)
assert_error(response, 400)
@pytest.mark.parametrize(
"body",
[
{"title": "Чат", "member_ids": []},
{"title": "", "member_ids": None},
{"title": " ", "member_ids": None},
{"title": "Чат", "member_ids": ["не-uuid"]},
{"title": "Чат", "member_ids": [1]},
{"title": "Чат", "member_ids": "не-список"},
],
)
async def test_invalid_chat_creation(client: AsyncClient, body: dict) -> None:
alice = await register(client, "alice")
payload = dict(body)
if payload["member_ids"] is None:
payload["member_ids"] = [alice["id"]]
response = await client.post("/api/v1/chats", json=payload, headers=actor(alice))
assert_error(response, 400)
async def test_creator_must_be_member(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
response = await client.post(
"/api/v1/chats",
json={"title": "Чат", "member_ids": [bob["id"]]},
headers=actor(alice),
)
assert_error(response, 400)
async def test_unknown_member_rejected(client: AsyncClient) -> None:
alice = await register(client, "alice")
response = await client.post(
"/api/v1/chats",
json={"title": "Чат", "member_ids": [alice["id"], str(uuid4())]},
headers=actor(alice),
)
assert_error(response, 400)
async def test_bad_chat_id_in_path(client: AsyncClient) -> None:
alice = await register(client, "alice")
assert_error(await client.get("/api/v1/chats/не-uuid", headers=actor(alice)), 400)