Files
mtusi2026lab4/tests_student/tests.py
T

773 lines
31 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
import asyncio
import base64
import uuid
import httpx
import pytest
from httpx import AsyncClient
async def register_and_login(client: AsyncClient, prefix: str = "u") -> dict:
username = f"{prefix}_{uuid.uuid4().hex[:12]}"
password = f"P@ssword_{uuid.uuid4().hex[:8]}"
body = {
"username": username,
"display_name": f"User {prefix}",
"password": password,
}
u_res = await client.post("/api/v1/users", json=body)
assert u_res.status_code == 201, u_res.text
user = u_res.json()
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
s_res = await client.post(
"/api/v1/auth/sessions", headers={"Authorization": f"Basic {cred}"}
)
assert s_res.status_code == 201, s_res.text
session = s_res.json()
return {
"user": user,
"username": username,
"password": password,
"token": session["token"],
"headers": {"Authorization": f"Bearer {session['token']}"},
}
@pytest.mark.asyncio
async def test_invalid_json_and_extra_fields(client: AsyncClient):
"""Проверка невалидного JSON, лишних полей, перевода строки и валидации курсора."""
# 1. Невалидный синтаксис JSON -> 400
res_malformed = await client.post(
"/api/v1/users",
content="not a valid json {",
headers={"Content-Type": "application/json"},
)
assert res_malformed.status_code == 400
err_malformed = res_malformed.json()
assert err_malformed["error"]["code"] == "invalid_request"
assert "request_id" in err_malformed["error"]
assert (
res_malformed.headers.get("X-Request-Id")
== err_malformed["error"]["request_id"]
)
# 2. Лишние поля (additionalProperties: false) -> 400
res_extra = await client.post(
"/api/v1/users",
json={
"username": f"u_{uuid.uuid4().hex[:8]}",
"display_name": "test_user",
"password": "ValidPassword123!",
"unexpected_field": "hacker_payload",
},
)
assert res_extra.status_code == 400
assert res_extra.json()["error"]["code"] == "invalid_request"
# 3. Запрет завершающего перевода строки в username ("abc\n") -> 400
res_newline = await client.post(
"/api/v1/users",
json={
"username": "abc\n",
"display_name": "test_newline",
"password": "ValidPassword123!",
},
)
assert res_newline.status_code == 400
assert res_newline.json()["error"]["code"] == "invalid_request"
# 4. Валидация курсора: не-dict JSON (W10= -> []) и пустой cursor= -> 400
actor = await register_and_login(client, "cur_val")
headers = actor["headers"]
# cursor=W10= (декодируется в list [], а не dict)
res_w10 = await client.get("/api/v1/chats?cursor=W10=", headers=headers)
assert res_w10.status_code == 400
assert res_w10.json()["error"]["code"] == "invalid_request"
# пустой cursor=
res_empty_cursor = await client.get("/api/v1/chats?cursor=", headers=headers)
assert res_empty_cursor.status_code == 400
assert res_empty_cursor.json()["error"]["code"] == "invalid_request"
@pytest.mark.asyncio
async def test_outsider_chat_access_is_404(client: AsyncClient):
"""Проверка того, что доступ к чужому чату возвращает строго 404 (а не 403)."""
alice = await register_and_login(client, "alice")
bob = await register_and_login(client, "bob")
eve = await register_and_login(client, "eve")
chat_res = await client.post(
"/api/v1/chats",
headers=alice["headers"],
json={
"title": "Private Chat",
"member_ids": [alice["user"]["id"], bob["user"]["id"]],
},
)
assert chat_res.status_code == 201
chat_id = chat_res.json()["id"]
# Ева пытается получить чужой чат -> 404
res_get = await client.get(f"/api/v1/chats/{chat_id}", headers=eve["headers"])
assert res_get.status_code == 404
assert res_get.json()["error"]["code"] == "not_found"
# Ева пытается отправить сообщение в чужой чат -> 404
res_send = await client.post(
f"/api/v1/chats/{chat_id}/messages",
headers={**eve["headers"], "Idempotency-Key": uuid.uuid4().hex},
json={"text": "Шпионское сообщение"},
)
assert res_send.status_code == 404
assert res_send.json()["error"]["code"] == "not_found"
# Ева пытается прочитать сообщения чужого чата -> 404
res_list = await client.get(
f"/api/v1/chats/{chat_id}/messages", headers=eve["headers"]
)
assert res_list.status_code == 404
assert res_list.json()["error"]["code"] == "not_found"
@pytest.mark.asyncio
async def test_empty_and_whitespace_message(client: AsyncClient):
"""Проверка запрета отправки пустого текста или текста из одних пробелов (400)."""
alice = await register_and_login(client, "msg_user")
chat = (
await client.post(
"/api/v1/chats",
headers=alice["headers"],
json={"title": "Chat", "member_ids": [alice["user"]["id"]]},
)
).json()
# Пустая строка -> 400
res_empty = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex},
json={"text": ""},
)
assert res_empty.status_code == 400
assert res_empty.json()["error"]["code"] == "invalid_request"
# Одни пробелы и переводы строк -> 400
res_whitespace = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex},
json={"text": " \n\t "},
)
assert res_whitespace.status_code == 400
assert res_whitespace.json()["error"]["code"] == "invalid_request"
@pytest.mark.asyncio
async def test_duplicate_username_conflict(client: AsyncClient):
"""Проверка запрета дублирования username (409 conflict)."""
uname = f"uniq_{uuid.uuid4().hex[:10]}"
body = {
"username": uname,
"display_name": "Первый",
"password": "ValidPassword123!",
}
res1 = await client.post("/api/v1/users", json=body)
assert res1.status_code == 201
res2 = await client.post(
"/api/v1/users",
json={
"username": uname,
"display_name": "Второй с тем же ником",
"password": "AnotherPassword123!",
},
)
assert res2.status_code == 409
assert res2.json()["error"]["code"] == "conflict"
@pytest.mark.asyncio
async def test_wrong_password_and_bad_basic_auth(client: AsyncClient):
"""Проверка ошибки авторизации 401 и корректного заголовка WWW-Authenticate."""
alice = await register_and_login(client, "auth_test")
# Неверный пароль -> 401
bad_cred = base64.b64encode(f"{alice['username']}:WrongPassword123!".encode()).decode()
res_bad = await client.post(
"/api/v1/auth/sessions", headers={"Authorization": f"Basic {bad_cred}"}
)
assert res_bad.status_code == 401
assert res_bad.json()["error"]["code"] == "unauthorized"
assert "basic" in res_bad.headers.get("WWW-Authenticate", "").lower()
# Несуществующий юзер -> 401
ghost_cred = base64.b64encode(b"ghost_user_123:WrongPassword123!").decode()
res_ghost = await client.post(
"/api/v1/auth/sessions", headers={"Authorization": f"Basic {ghost_cred}"}
)
assert res_ghost.status_code == 401
assert "basic" in res_ghost.headers.get("WWW-Authenticate", "").lower()
@pytest.mark.asyncio
async def test_logout_and_revocation(client: AsyncClient):
"""Проверка отзыва сессии (logout 204) и 401 при обращении с отозванным токеном."""
alice = await register_and_login(client, "logout_test")
# Проверяем, что токен работает
me_res = await client.get("/api/v1/users/me", headers=alice["headers"])
assert me_res.status_code == 200
# Делаем logout -> 204
logout_res = await client.delete(
"/api/v1/auth/sessions/current", headers=alice["headers"]
)
assert logout_res.status_code == 204
# Теперь тот же токен должен возвращать 401
me_after = await client.get("/api/v1/users/me", headers=alice["headers"])
assert me_after.status_code == 401
assert me_after.json()["error"]["code"] == "unauthorized"
assert "bearer" in me_after.headers.get("WWW-Authenticate", "").lower()
# Повторный logout с тем же отозванным токеном -> 401
logout_repeat = await client.delete(
"/api/v1/auth/sessions/current", headers=alice["headers"]
)
assert logout_repeat.status_code == 401
@pytest.mark.asyncio
async def test_multi_page_cursor_pagination(client: AsyncClient):
"""Проверка обхода истории сообщений через keyset-курсор на нескольких страницах."""
alice = await register_and_login(client, "pager")
chat = (
await client.post(
"/api/v1/chats",
headers=alice["headers"],
json={"title": "Pagination Chat", "member_ids": [alice["user"]["id"]]},
)
).json()
# Отправляем 15 сообщений
sent_ids = []
for i in range(15):
msg = (
await client.post(
f"/api/v1/chats/{chat['id']}/messages",
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex},
json={"text": f"Сообщение {i:02d}"},
)
).json()
sent_ids.append(msg["id"])
# Читаем страницами по 4 сообщения
gathered_ids = []
cursor = None
pages_count = 0
while True:
url = f"/api/v1/chats/{chat['id']}/messages?limit=4"
if cursor:
url += f"&cursor={cursor}"
res = await client.get(url, headers=alice["headers"])
assert res.status_code == 200
data = res.json()
pages_count += 1
items = data["items"]
for item in items:
gathered_ids.append(item["id"])
cursor = data.get("next_cursor")
if not cursor:
break
# Должны быть ровно 15 сообщений в строго том же порядке, без дублей и пропусков
assert len(gathered_ids) == 15
assert gathered_ids == sent_ids
assert pages_count == 4
@pytest.mark.asyncio
async def test_concurrency_race_condition(client: AsyncClient):
"""Проверка устойчивости к параллельным гонкам: 10 клиентов одновременно шлют 100 сообщений."""
# Создаём 10 пользователей
users = await asyncio.gather(
*(register_and_login(client, f"u{i}") for i in range(10))
)
all_user_ids = [u["user"]["id"] for u in users]
# Первый пользователь создаёт общий чат со всеми 10 участниками
chat = (
await client.post(
"/api/v1/chats",
headers=users[0]["headers"],
json={"title": "Massive Concurrent Chat", "member_ids": all_user_ids},
)
).json()
chat_id = chat["id"]
# Отправляем по 10 сообщений от каждого пользователя параллельно (всего 100)
async def sender(user_dict: dict, count: int):
for i in range(count):
await client.post(
f"/api/v1/chats/{chat_id}/messages",
headers={**user_dict["headers"], "Idempotency-Key": uuid.uuid4().hex},
json={"text": f"Msg {i} from {user_dict['username']}"},
)
await asyncio.gather(*(sender(u, 10) for u in users))
# Считываем все сообщения из чата
all_msgs = []
cursor = None
while True:
url = f"/api/v1/chats/{chat_id}/messages?limit=50"
if cursor:
url += f"&cursor={cursor}"
res = await client.get(url, headers=users[0]["headers"])
assert res.status_code == 200
data = res.json()
all_msgs.extend(data["items"])
cursor = data.get("next_cursor")
if not cursor:
break
assert len(all_msgs) == 100
ids = [m["id"] for m in all_msgs]
# Все ID должны быть уникальными
assert len(ids) == len(set(ids))
@pytest.mark.asyncio
async def test_password_whitespace_rejected(client: httpx.AsyncClient):
"""Пароль из одних пробелов должен строго отклоняться с 400 Invalid Request."""
u = f"space_user_{uuid.uuid4().hex[:6]}"
res = await client.post(
"/api/v1/users",
json={"username": u, "display_name": "Test User", "password": " " * 12},
)
assert res.status_code == 400
data = res.json()
assert data["error"]["code"] == "invalid_request"
@pytest.mark.asyncio
async def test_auth_sessions_with_body_rejected(client: httpx.AsyncClient):
"""POST /api/v1/auth/sessions с телом запроса должен отклоняться с 400 Invalid Request."""
u = f"body_user_{uuid.uuid4().hex[:6]}"
p = "StrongPassword123!"
await client.post(
"/api/v1/users",
json={"username": u, "display_name": "Body Test", "password": p},
)
cred = base64.b64encode(f"{u}:{p}".encode()).decode()
res = await client.post(
"/api/v1/auth/sessions",
headers={"Authorization": f"Basic {cred}"},
json={"extra": "forbidden"},
)
assert res.status_code == 400
data = res.json()
assert data["error"]["code"] == "invalid_request"
@pytest.mark.asyncio
async def test_unsupported_media_type_415(client: httpx.AsyncClient):
"""Запрос с неподдерживаемым Content-Type (text/plain) должен возвращать 415 Unsupported Media Type."""
res = await client.post(
"/api/v1/users",
content='{"username":"ct_test","display_name":"d","password":"Password123456!"}',
headers={"Content-Type": "text/plain"},
)
assert res.status_code == 415
data = res.json()
assert data["error"]["code"] == "unsupported_media_type"
@pytest.mark.asyncio
async def test_nul_byte_in_strings_handled(client: httpx.AsyncClient):
usr = await register_and_login(client, f"nul_msg_{uuid.uuid4().hex[:4]}")
chat = (await client.post("/api/v1/chats", headers=usr["headers"], json={"title": "NulChat", "member_ids": [usr["user"]["id"]]})).json()
test_text = "left\u0000right"
msg_res = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
headers={**usr["headers"], "Idempotency-Key": uuid.uuid4().hex},
json={"text": test_text},
)
assert msg_res.status_code == 201
assert msg_res.json()["text"] == test_text
list_res = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=usr["headers"])
assert list_res.status_code == 200
assert any(m["text"] == test_text for m in list_res.json()["items"])
@pytest.mark.asyncio
async def test_basic_auth_invalid_base64_returns_401(client: httpx.AsyncClient):
"""Authorization: Basic с битым base64 или не-ASCII символами возвращает 401, а не 500."""
res = await client.post(
"/api/v1/auth/sessions",
headers={"Authorization": b"Basic \xe9"},
)
assert res.status_code == 401
assert "Basic" in res.headers.get("www-authenticate", "")
@pytest.mark.asyncio
async def test_cross_chat_cursor_rejected_400(client: httpx.AsyncClient):
"""Курсор от одного чата при попытке использовать в другом чате должен возвращать 400."""
u = await register_and_login(client, f"cc_{uuid.uuid4().hex[:4]}")
chat1 = (await client.post("/api/v1/chats", headers=u["headers"], json={"title": "C1", "member_ids": [u["user"]["id"]]})).json()
chat2 = (await client.post("/api/v1/chats", headers=u["headers"], json={"title": "C2", "member_ids": [u["user"]["id"]]})).json()
# Отправляем 2 сообщения в чат 1
await client.post(f"/api/v1/chats/{chat1['id']}/messages", headers={**u["headers"], "Idempotency-Key": uuid.uuid4().hex}, json={"text": "m1"})
await client.post(f"/api/v1/chats/{chat1['id']}/messages", headers={**u["headers"], "Idempotency-Key": uuid.uuid4().hex}, json={"text": "m2"})
# Получаем страницу с курсором из чата 1
p1 = (await client.get(f"/api/v1/chats/{chat1['id']}/messages?limit=1", headers=u["headers"])).json()
cursor1 = p1.get("next_cursor")
assert cursor1 is not None
# Пытаемся применить курсор чата 1 к чату 2 -> 400!
res = await client.get(f"/api/v1/chats/{chat2['id']}/messages?cursor={cursor1}", headers=u["headers"])
assert res.status_code == 400
assert res.json()["error"]["code"] == "invalid_request"
@pytest.mark.asyncio
async def test_utf8_password_support(client: httpx.AsyncClient):
"""Пароли с символами UTF-8 и emoji корректно регистрируются и аутентифицируются."""
u = f"utf_{uuid.uuid4().hex[:6]}"
p = "СложныйПароль123!🔒"
res1 = await client.post(
"/api/v1/users",
json={"username": u, "display_name": "UTF User", "password": p},
)
assert res1.status_code == 201
cred = base64.b64encode(f"{u}:{p}".encode("utf-8")).decode("utf-8")
res2 = await client.post(
"/api/v1/auth/sessions",
headers={"Authorization": f"Basic {cred}"},
)
assert res2.status_code == 201
assert "token" in res2.json()
@pytest.mark.asyncio
async def test_health_readiness_and_liveness(client: httpx.AsyncClient):
"""Проверка доступности /health/live и готовности хранилищ /health/ready."""
r_live = await client.get("/health/live")
assert r_live.status_code == 200
assert r_live.json()["status"] == "ok"
r_ready = await client.get("/health/ready")
assert r_ready.status_code == 200
assert r_ready.json()["status"] == "ok"
@pytest.mark.asyncio
async def test_instance_id_header_present(client: httpx.AsyncClient):
"""Каждый ответ обязан содержать непустой заголовок X-Instance-Id."""
res = await client.get("/health/live")
assert res.status_code == 200
assert "x-instance-id" in res.headers
assert len(res.headers["x-instance-id"]) > 0
res_err = await client.get("/api/v1/users/me")
assert res_err.status_code == 401
assert "x-instance-id" in res_err.headers
assert len(res_err.headers["x-instance-id"]) > 0
@pytest.mark.asyncio
async def test_idempotency_key_validation(client: httpx.AsyncClient):
"""POST /messages без Idempotency-Key или с некорректным форматом возвращает 400."""
alice = await register_and_login(client, f"idem_{uuid.uuid4().hex[:6]}")
chat = (await client.post("/api/v1/chats", headers=alice["headers"], json={"title": "IdemChat", "member_ids": [alice["user"]["id"]]})).json()
chat_id = chat["id"]
# Без заголовка
res1 = await client.post(f"/api/v1/chats/{chat_id}/messages", headers=alice["headers"], json={"text": "Тест"})
assert res1.status_code == 400
assert res1.json()["error"]["code"] == "invalid_request"
# С некорректным форматом
res2 = await client.post(f"/api/v1/chats/{chat_id}/messages", headers={**alice["headers"], "Idempotency-Key": "invalid key with spaces"}, json={"text": "Тест"})
assert res2.status_code == 400
assert res2.json()["error"]["code"] == "invalid_request"
@pytest.mark.asyncio
async def test_idempotency_replay_and_conflict(client: httpx.AsyncClient):
"""Повтор с тем же телом возвращает исходный 201; с другим телом возвращает 409."""
alice = await register_and_login(client, f"idem2_{uuid.uuid4().hex[:6]}")
chat = (await client.post("/api/v1/chats", headers=alice["headers"], json={"title": "IdemChat2", "member_ids": [alice["user"]["id"]]})).json()
chat_id = chat["id"]
key = uuid.uuid4().hex
# Первый запрос -> 201
res1 = await client.post(
f"/api/v1/chats/{chat_id}/messages",
headers={**alice["headers"], "Idempotency-Key": key},
json={"text": "Первое сообщение"},
)
assert res1.status_code == 201
msg1 = res1.json()
# Повтор с тем же телом -> 201 и то же сообщение
res2 = await client.post(
f"/api/v1/chats/{chat_id}/messages",
headers={**alice["headers"], "Idempotency-Key": key},
json={"text": "Первое сообщение"},
)
assert res2.status_code == 201
assert res2.json() == msg1
# Повтор с тем же ключом, но другим телом -> 409 Conflict
res3 = await client.post(
f"/api/v1/chats/{chat_id}/messages",
headers={**alice["headers"], "Idempotency-Key": key},
json={"text": "Другое сообщение с тем же ключом"},
)
assert res3.status_code == 409
assert res3.json()["error"]["code"] == "conflict"
@pytest.mark.asyncio
async def test_idempotency_acl_check_on_replay(client: httpx.AsyncClient):
"""
Проверка ACL перед возвратом сохранённого результата идемпотентности.
Если пользователь удалён из участников чата, повторный POST с тем же Idempotency-Key
и тем же телом обязан вернуть 404 (а не 201).
"""
import subprocess
alice = await register_and_login(client, f"acl_{uuid.uuid4().hex[:6]}")
chat = (
await client.post(
"/api/v1/chats",
headers=alice["headers"],
json={"title": "ACL Test Chat", "member_ids": [alice["user"]["id"]]},
)
).json()
chat_id = chat["id"]
user_id = alice["user"]["id"]
key = f"acl_key_{uuid.uuid4().hex[:12]}"
# 1. Отправляем сообщение первый раз -> 201
res1 = await client.post(
f"/api/v1/chats/{chat_id}/messages",
headers={**alice["headers"], "Idempotency-Key": key},
json={"text": "Тест проверки ACL"},
)
assert res1.status_code == 201
# 2. Удаляем членство отправителя напрямую в БД (изолированная инъекция проверки ACL)
cmd = [
"docker",
"compose",
"exec",
"-T",
"postgres",
"psql",
"-U",
"postgres",
"-d",
"messenger",
"-c",
f"DELETE FROM chat_members WHERE chat_id = '{chat_id}' AND user_id = '{user_id}';",
]
sub_res = subprocess.run(cmd, capture_output=True, text=True)
assert sub_res.returncode == 0, f"Ошибка удаления членства: {sub_res.stderr}"
# 3. GET истории уже обязан возвращать 404
res_get = await client.get(f"/api/v1/chats/{chat_id}/messages", headers=alice["headers"])
assert res_get.status_code == 404
# 4. Повтор POST с тем же телом и тем же ключом ОБЯЗАН вернуть 404 (ACL проверяется до возврата из idempotency_keys)
res_repeat = await client.post(
f"/api/v1/chats/{chat_id}/messages",
headers={**alice["headers"], "Idempotency-Key": key},
json={"text": "Тест проверки ACL"},
)
assert res_repeat.status_code == 404, f"Ожидался 404, получен {res_repeat.status_code}: {res_repeat.text}"
assert res_repeat.json()["error"]["code"] == "not_found"
# 5. Повтор POST с тем же ключом и ДРУГИМ телом: ACL проверяется до сравнения тела -> обязан вернуть 404 (а не 409)
res_repeat_diff = await client.post(
f"/api/v1/chats/{chat_id}/messages",
headers={**alice["headers"], "Idempotency-Key": key},
json={"text": "Другой текст сообщения"},
)
assert res_repeat_diff.status_code == 404, f"Ожидался 404, получен {res_repeat_diff.status_code}: {res_repeat_diff.text}"
assert res_repeat_diff.json()["error"]["code"] == "not_found"
@pytest.mark.asyncio
async def test_invalid_cursor_date_returns_400(client: httpx.AsyncClient):
"""
Некорректная дата курсора (например, 13-й месяц 2026-13-01T00:00:00.000000Z)
обязана возвращать 400 invalid_request (а не 500 internal_error).
"""
from app.storage import encode_cursor
alice = await register_and_login(client, f"bad_cur_{uuid.uuid4().hex[:6]}")
chat = (
await client.post(
"/api/v1/chats",
headers=alice["headers"],
json={"title": "CurChat", "member_ids": [alice["user"]["id"]]},
)
).json()
chat_id = chat["id"]
# 1. Курсор сообщений с невалидной датой (месяц 13)
bad_cur_msg = encode_cursor(
{
"type": "messages",
"chat_id": chat_id,
"created_at": "2026-13-01T00:00:00.000000Z",
"id": str(uuid.uuid4()),
}
)
res_m = await client.get(
f"/api/v1/chats/{chat_id}/messages?cursor={bad_cur_msg}",
headers=alice["headers"],
)
assert res_m.status_code == 400
assert res_m.json()["error"]["code"] == "invalid_request"
# 2. Невалидная строка формата m|chat_id|... в base64
raw_str = f"m|{chat_id}|2026-13-01T00:00:00.000000Z|"
raw_cur = base64.urlsafe_b64encode(raw_str.encode()).decode()
res_raw = await client.get(
f"/api/v1/chats/{chat_id}/messages?cursor={raw_cur}",
headers=alice["headers"],
)
assert res_raw.status_code == 400
assert res_raw.json()["error"]["code"] == "invalid_request"
@pytest.mark.asyncio
async def test_strict_types_and_json_parsing(client: httpx.AsyncClient):
"""
Запрет преобразования неверных типов ({"text": 123} -> 400)
и требование полного разбора JSON ({"text":"x"}garbage -> 400).
"""
alice = await register_and_login(client, f"strict_{uuid.uuid4().hex[:6]}")
chat = (
await client.post(
"/api/v1/chats",
headers=alice["headers"],
json={"title": "StrictChat", "member_ids": [alice["user"]["id"]]},
)
).json()
chat_id = chat["id"]
# 1. {"text": 123} вместо строки -> 400
res_num = await client.post(
f"/api/v1/chats/{chat_id}/messages",
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex, "Content-Type": "application/json"},
content='{"text": 123}',
)
assert res_num.status_code == 400
assert res_num.json()["error"]["code"] == "invalid_request"
# 2. {"text": "x"}garbage -> 400
res_garbage = await client.post(
f"/api/v1/chats/{chat_id}/messages",
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex, "Content-Type": "application/json"},
content='{"text": "x"}garbage',
)
assert res_garbage.status_code == 400
assert res_garbage.json()["error"]["code"] == "invalid_request"
@pytest.mark.asyncio
async def test_session_create_rejects_non_empty_body(client: httpx.AsyncClient):
"""POST /api/v1/auth/sessions с непустым телом {"unexpected":true} отклоняется с 400."""
alice = await register_and_login(client, f"no_body_{uuid.uuid4().hex[:6]}")
cred = base64.b64encode(f"{alice['username']}:{alice['password']}".encode()).decode()
res = await client.post(
"/api/v1/auth/sessions",
headers={"Authorization": f"Basic {cred}", "Content-Type": "application/json"},
content='{"unexpected": true}',
)
assert res.status_code == 400
assert res.json()["error"]["code"] == "invalid_request"
@pytest.mark.asyncio
async def test_chat_creation_with_unknown_participant_is_400(client: httpx.AsyncClient):
"""Неизвестный участник при создании чата обязан возвращать 400 (не 404)."""
alice = await register_and_login(client, f"unk_{uuid.uuid4().hex[:6]}")
non_existent_uuid = str(uuid.uuid4())
res = await client.post(
"/api/v1/chats",
headers=alice["headers"],
json={"title": "Chat With Ghost", "member_ids": [alice["user"]["id"], non_existent_uuid]},
)
assert res.status_code == 400
assert res.json()["error"]["code"] == "invalid_request"
@pytest.mark.asyncio
async def test_password_with_colons_and_utf8(client: httpx.AsyncClient):
"""Пароль с двоеточиями и UTF-8 символами работает при регистрации и входе."""
username = f"col_{uuid.uuid4().hex[:8]}"
password = "Пример:пароля-12345:секрет:🔒"
res_reg = await client.post(
"/api/v1/users",
json={"username": username, "display_name": "Colon User", "password": password},
)
assert res_reg.status_code == 201
cred = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8")
res_login = await client.post(
"/api/v1/auth/sessions",
headers={"Authorization": f"Basic {cred}"},
)
assert res_login.status_code == 201
assert "token" in res_login.json()
@pytest.mark.asyncio
async def test_keyset_pagination_returns_next_cursor(client: httpx.AsyncClient):
"""
При наличии записей за пределами limit возвращается next_cursor.
Повторный запрос с cursor возвращает следующие элементы.
"""
alice = await register_and_login(client, f"page_{uuid.uuid4().hex[:6]}")
c1 = (await client.post("/api/v1/chats", headers=alice["headers"], json={"title": "Chat1", "member_ids": [alice["user"]["id"]]})).json()
c2 = (await client.post("/api/v1/chats", headers=alice["headers"], json={"title": "Chat2", "member_ids": [alice["user"]["id"]]})).json()
# Запрос с limit=1 обязан вернуть первый чат и НЕПУСТОЙ next_cursor
res_p1 = await client.get("/api/v1/chats?limit=1", headers=alice["headers"])
assert res_p1.status_code == 200
data_p1 = res_p1.json()
assert len(data_p1["items"]) == 1
cursor = data_p1["next_cursor"]
assert cursor is not None and len(cursor) > 0
# Запрос со вторым курсором обязан вернуть второй чат
res_p2 = await client.get(f"/api/v1/chats?limit=1&cursor={cursor}", headers=alice["headers"])
assert res_p2.status_code == 200
data_p2 = res_p2.json()
assert len(data_p2["items"]) == 1
assert data_p2["items"][0]["id"] != data_p1["items"][0]["id"]