Files
mtusi2026lab2/tests_student/tests.py
T

472 lines
18 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"],
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"],
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"],
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"],
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"],
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):
"""Символ \\u0000 в строках не должен вызывать 500/503 и должен корректно обрабатываться."""
u = f"nul_user_{uuid.uuid4().hex[:6]}"
res = await client.post(
"/api/v1/users",
json={"username": u, "display_name": "Hello\u0000World", "password": "Password123456!"},
)
assert res.status_code == 201
data = res.json()
assert data["username"] == u
assert data["display_name"] == "HelloWorld"
@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"], json={"text": "m1"})
await client.post(f"/api/v1/chats/{chat1['id']}/messages", headers=u["headers"], 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"