321 lines
12 KiB
Python
321 lines
12 KiB
Python
import asyncio
|
||
import uuid
|
||
|
||
import pytest
|
||
from httpx import AsyncClient
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_invalid_json_and_extra_fields(client: AsyncClient):
|
||
"""Проверка невалидного JSON и запрета лишних полей (400 invalid_request)."""
|
||
# 1. Невалидный синтаксис JSON
|
||
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)
|
||
res_extra = await client.post(
|
||
"/api/v1/users",
|
||
json={
|
||
"username": f"u_{uuid.uuid4().hex[:8]}",
|
||
"display_name": "test_user",
|
||
"unexpected_field": "hacker_payload",
|
||
},
|
||
)
|
||
assert res_extra.status_code == 400
|
||
err_extra = res_extra.json()
|
||
assert err_extra["error"]["code"] == "invalid_request"
|
||
|
||
# 3. Запрет завершающего перевода строки в username ("abc\n")
|
||
res_newline = await client.post(
|
||
"/api/v1/users",
|
||
json={"username": "abc\n", "display_name": "test_newline"},
|
||
)
|
||
assert res_newline.status_code == 400
|
||
assert res_newline.json()["error"]["code"] == "invalid_request"
|
||
|
||
# 4. Валидация курсора: не-dict JSON (W10= -> []) и пустой cursor=
|
||
user_res = (
|
||
await client.post(
|
||
"/api/v1/users",
|
||
json={"username": f"u_{uuid.uuid4().hex[:8]}", "display_name": "test_cursor_val"},
|
||
)
|
||
).json()
|
||
headers = {"X-User-Id": user_res["id"]}
|
||
|
||
# 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)."""
|
||
# Создаём двух участников чата
|
||
test_user1 = (
|
||
await client.post(
|
||
"/api/v1/users",
|
||
json={"username": f"u1_{uuid.uuid4().hex[:8]}", "display_name": "test_user1"},
|
||
)
|
||
).json()
|
||
test_user2 = (
|
||
await client.post(
|
||
"/api/v1/users",
|
||
json={"username": f"u2_{uuid.uuid4().hex[:8]}", "display_name": "test_user2"},
|
||
)
|
||
).json()
|
||
# Создаём стороннего пользователя
|
||
test_user3 = (
|
||
await client.post(
|
||
"/api/v1/users",
|
||
json={"username": f"u3_{uuid.uuid4().hex[:8]}", "display_name": "test_user3"},
|
||
)
|
||
).json()
|
||
|
||
# Первый пользователь создаёт чат со вторым
|
||
chat = (
|
||
await client.post(
|
||
"/api/v1/chats",
|
||
headers={"X-User-Id": test_user1["id"]},
|
||
json={"title": "Private Chat", "member_ids": [test_user1["id"], test_user2["id"]]},
|
||
)
|
||
).json()
|
||
|
||
chat_id = chat["id"]
|
||
|
||
# Сторонний пользователь пытается получить чат по ID -> 404
|
||
res_chat = await client.get(
|
||
f"/api/v1/chats/{chat_id}", headers={"X-User-Id": test_user3["id"]}
|
||
)
|
||
assert res_chat.status_code == 404
|
||
assert res_chat.json()["error"]["code"] == "not_found"
|
||
|
||
# Сторонний пользователь пытается отправить сообщение в чужой чат -> 404
|
||
res_post = await client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={"X-User-Id": test_user3["id"]},
|
||
json={"text": "Привет извне"},
|
||
)
|
||
assert res_post.status_code == 404
|
||
assert res_post.json()["error"]["code"] == "not_found"
|
||
|
||
# Сторонний пользователь пытается прочитать сообщения чужого чата -> 404
|
||
res_msgs = await client.get(
|
||
f"/api/v1/chats/{chat_id}/messages", headers={"X-User-Id": test_user3["id"]}
|
||
)
|
||
assert res_msgs.status_code == 404
|
||
assert res_msgs.json()["error"]["code"] == "not_found"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_empty_and_whitespace_message(client: AsyncClient):
|
||
"""Проверка отправки пустого сообщения или сообщения только из пробелов (400)."""
|
||
user = (
|
||
await client.post(
|
||
"/api/v1/users",
|
||
json={"username": f"u_{uuid.uuid4().hex[:8]}", "display_name": "test_user"},
|
||
)
|
||
).json()
|
||
chat = (
|
||
await client.post(
|
||
"/api/v1/chats",
|
||
headers={"X-User-Id": user["id"]},
|
||
json={"title": "Chat", "member_ids": [user["id"]]},
|
||
)
|
||
).json()
|
||
|
||
# Пустая строка
|
||
res_empty = await client.post(
|
||
f"/api/v1/chats/{chat['id']}/messages",
|
||
headers={"X-User-Id": user["id"]},
|
||
json={"text": ""},
|
||
)
|
||
assert res_empty.status_code == 400
|
||
assert res_empty.json()["error"]["code"] == "invalid_request"
|
||
|
||
# Только пробелы и переводы строк
|
||
res_spaces = await client.post(
|
||
f"/api/v1/chats/{chat['id']}/messages",
|
||
headers={"X-User-Id": user["id"]},
|
||
json={"text": " \t \n "},
|
||
)
|
||
assert res_spaces.status_code == 400
|
||
assert res_spaces.json()["error"]["code"] == "invalid_request"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_duplicate_username_conflict(client: AsyncClient):
|
||
"""Проверка регистрации пользователя с уже занятым username (409)."""
|
||
uname = f"unique_{uuid.uuid4().hex[:8]}"
|
||
res1 = await client.post(
|
||
"/api/v1/users", json={"username": uname, "display_name": "test_user1"}
|
||
)
|
||
assert res1.status_code == 201
|
||
|
||
res2 = await client.post(
|
||
"/api/v1/users", json={"username": uname, "display_name": "test_user2"}
|
||
)
|
||
assert res2.status_code == 409
|
||
err = res2.json()
|
||
assert err["error"]["code"] == "conflict"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_multi_page_cursor_pagination(client: AsyncClient):
|
||
"""Проверка обхода нескольких страниц по keyset-курсору."""
|
||
user = (
|
||
await client.post(
|
||
"/api/v1/users",
|
||
json={"username": f"pag_{uuid.uuid4().hex[:8]}", "display_name": "test_user"},
|
||
)
|
||
).json()
|
||
chat = (
|
||
await client.post(
|
||
"/api/v1/chats",
|
||
headers={"X-User-Id": user["id"]},
|
||
json={"title": "Pagination Chat", "member_ids": [user["id"]]},
|
||
)
|
||
).json()
|
||
chat_id = chat["id"]
|
||
|
||
# Отправляем 5 сообщений
|
||
sent_texts = [f"Message #{i}" for i in range(1, 6)]
|
||
created_messages = []
|
||
for txt in sent_texts:
|
||
res = await client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={"X-User-Id": user["id"]},
|
||
json={"text": txt},
|
||
)
|
||
assert res.status_code == 201
|
||
created_messages.append(res.json())
|
||
|
||
# Страница 1: limit=2
|
||
p1 = (
|
||
await client.get(
|
||
f"/api/v1/chats/{chat_id}/messages?limit=2",
|
||
headers={"X-User-Id": user["id"]},
|
||
)
|
||
).json()
|
||
assert len(p1["items"]) == 2
|
||
assert p1["next_cursor"] is not None
|
||
|
||
# Страница 2: limit=2 с курсором со страницы 1
|
||
p2 = (
|
||
await client.get(
|
||
f"/api/v1/chats/{chat_id}/messages?limit=2&cursor={p1['next_cursor']}",
|
||
headers={"X-User-Id": user["id"]},
|
||
)
|
||
).json()
|
||
assert len(p2["items"]) == 2
|
||
assert p2["next_cursor"] is not None
|
||
|
||
# Страница 3: limit=2 с курсором со страницы 2 -> остался 1 элемент, next_cursor == None
|
||
p3 = (
|
||
await client.get(
|
||
f"/api/v1/chats/{chat_id}/messages?limit=2&cursor={p2['next_cursor']}",
|
||
headers={"X-User-Id": user["id"]},
|
||
)
|
||
).json()
|
||
assert len(p3["items"]) == 1
|
||
assert p3["next_cursor"] is None
|
||
|
||
# Проверяем, что все 5 сообщений собраны без повторов и потерь
|
||
all_retrieved = p1["items"] + p2["items"] + p3["items"]
|
||
assert len(all_retrieved) == 5
|
||
assert [m["id"] for m in all_retrieved] == [m["id"] for m in created_messages]
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_concurrency_race_condition(client: AsyncClient):
|
||
"""
|
||
Защита состояния от гонок:
|
||
Параллельно отправляем 100 сообщений от 10 клиентов,
|
||
затем получаем ровно 100 уникальных сообщений без повреждений.
|
||
"""
|
||
# 1. Создаём 10 клиентов
|
||
users = []
|
||
for i in range(10):
|
||
u = (
|
||
await client.post(
|
||
"/api/v1/users",
|
||
json={
|
||
"username": f"conc_{i}_{uuid.uuid4().hex[:6]}",
|
||
"display_name": f"test_user_{i}",
|
||
},
|
||
)
|
||
).json()
|
||
users.append(u)
|
||
|
||
user_ids = [u["id"] for u in users]
|
||
|
||
# 2. Создаём чат со всеми 10 участниками
|
||
chat = (
|
||
await client.post(
|
||
"/api/v1/chats",
|
||
headers={"X-User-Id": user_ids[0]},
|
||
json={"title": "Highload Concurrency Chat", "member_ids": user_ids},
|
||
)
|
||
).json()
|
||
chat_id = chat["id"]
|
||
|
||
# 3. Каждый из 10 клиентов отправляет по 10 сообщений параллельно (итого 100 сообщений)
|
||
async def send_batch(user, client_idx):
|
||
tasks = []
|
||
for msg_idx in range(10):
|
||
text = f"client-{client_idx}-msg-{msg_idx}"
|
||
tasks.append(
|
||
client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={"X-User-Id": user["id"]},
|
||
json={"text": text},
|
||
)
|
||
)
|
||
return await asyncio.gather(*tasks)
|
||
|
||
# Запускаем отправку от всех 10 клиентов одновременно
|
||
batch_results = await asyncio.gather(*[send_batch(users[i], i) for i in range(10)])
|
||
|
||
# Проверяем, что все 100 запросов завершились со статусом 201 Created
|
||
all_responses = [resp for batch in batch_results for resp in batch]
|
||
assert len(all_responses) == 100
|
||
for resp in all_responses:
|
||
assert resp.status_code == 201
|
||
|
||
# 4. Читаем все сообщения из чата (limit=100)
|
||
history_res = await client.get(
|
||
f"/api/v1/chats/{chat_id}/messages?limit=100",
|
||
headers={"X-User-Id": user_ids[0]},
|
||
)
|
||
assert history_res.status_code == 200
|
||
history = history_res.json()
|
||
items = history["items"]
|
||
|
||
# параллельно отправим 100 сообщений от 10 клиентов, затем получаем ровно 100 уникальных сообщений
|
||
assert len(items) == 100, f"Expected 100 messages, received {len(items)}"
|
||
unique_ids = {m["id"] for m in items}
|
||
assert len(unique_ids) == 100, "Found duplicate message IDs"
|
||
|
||
# Проверяем монотонную сортировку (created_at, id)
|
||
for idx in range(len(items) - 1):
|
||
assert (items[idx]["created_at"], items[idx]["id"]) <= (
|
||
items[idx + 1]["created_at"],
|
||
items[idx + 1]["id"],
|
||
)
|