forked from mtusi2026/mtusi2026lab2
Complete Lab 2 for Grade 5 (Track 2)
This commit is contained in:
@@ -0,0 +1,135 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from src.main import app
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
def create_user(username="test_user"):
|
||||
res = client.post("/api/v1/users", json={"username": username, "display_name": "Test"})
|
||||
assert res.status_code == 201
|
||||
return res.json()
|
||||
|
||||
def test_duplicate_username():
|
||||
create_user("user_dup")
|
||||
res = client.post("/api/v1/users", json={"username": "user_dup", "display_name": "Test"})
|
||||
assert res.status_code == 409
|
||||
assert res.json()["error"]["code"] == "conflict"
|
||||
|
||||
def test_whitespace_validation():
|
||||
# Пробельное имя пользователя
|
||||
res1 = client.post("/api/v1/users", json={"username": "valid_user_ws", "display_name": " "})
|
||||
assert res1.status_code == 400
|
||||
assert res1.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
u = create_user("user_ws")
|
||||
# Пробельный title чата
|
||||
res2 = client.post("/api/v1/chats", json={"title": " ", "member_ids": [u["id"]]}, headers={"X-User-Id": u["id"]})
|
||||
assert res2.status_code == 400
|
||||
|
||||
chat = client.post("/api/v1/chats", json={"title": "Valid Chat", "member_ids": [u["id"]]}, headers={"X-User-Id": u["id"]}).json()
|
||||
# Пробельный текст сообщения
|
||||
res3 = client.post(f"/api/v1/chats/{chat['id']}/messages", json={"text": " "}, headers={"X-User-Id": u["id"]})
|
||||
assert res3.status_code == 400
|
||||
assert res3.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
def test_extra_json_fields_forbidden():
|
||||
u = create_user("user_extra")
|
||||
chat = client.post("/api/v1/chats", json={"title": "Chat", "member_ids": [u["id"]]}, headers={"X-User-Id": u["id"]}).json()
|
||||
# Попытка передать лишнее поле sender_id
|
||||
payload = {"text": "hello", "sender_id": u["id"]}
|
||||
res = client.post(f"/api/v1/chats/{chat['id']}/messages", json=payload, headers={"X-User-Id": u["id"]})
|
||||
assert res.status_code == 400
|
||||
assert res.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
def test_duplicate_members_in_chat():
|
||||
u = create_user("user_dup_mem")
|
||||
payload = {"title": "Dup Chat", "member_ids": [u["id"], u["id"]]}
|
||||
res = client.post("/api/v1/chats", json=payload, headers={"X-User-Id": u["id"]})
|
||||
assert res.status_code == 400
|
||||
assert res.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
def test_invalid_uuid_and_empty_cursor():
|
||||
u = create_user("user_uuid")
|
||||
# Неверный UUID пути должен давать 400, а не 404
|
||||
res = client.get("/api/v1/chats/not-a-valid-uuid", headers={"X-User-Id": u["id"]})
|
||||
assert res.status_code == 400
|
||||
assert res.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
# Пустой cursor должен давать 400
|
||||
res_cur = client.get("/api/v1/chats?cursor=", headers={"X-User-Id": u["id"]})
|
||||
assert res_cur.status_code == 400
|
||||
assert res_cur.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
def test_router_404_format():
|
||||
# Несуществующий эндпоинт маршрутизатора должен возвращать единый формат ошибки
|
||||
res = client.get("/api/v1/non_existent_endpoint_xyz")
|
||||
assert res.status_code == 404
|
||||
data = res.json()
|
||||
assert "error" in data
|
||||
assert data["error"]["code"] == "not_found"
|
||||
assert "request_id" in data["error"]
|
||||
|
||||
def test_malformed_json():
|
||||
# Битый JSON в теле запроса
|
||||
res = client.post(
|
||||
"/api/v1/users",
|
||||
content="{'broken': json,",
|
||||
headers={"Content-Type": "application/json"}
|
||||
)
|
||||
assert res.status_code == 400
|
||||
assert res.json()["error"]["code"] == "invalid_request"
|
||||
|
||||
def test_foreign_chat():
|
||||
u1 = create_user("user_owner")
|
||||
u2 = create_user("user_stranger")
|
||||
chat = client.post("/api/v1/chats", json={"title": "Private Chat", "member_ids": [u1["id"]]}, headers={"X-User-Id": u1["id"]}).json()
|
||||
|
||||
# Попытка чужого пользователя прочитать чат -> 404
|
||||
res_get = client.get(f"/api/v1/chats/{chat['id']}", headers={"X-User-Id": u2["id"]})
|
||||
assert res_get.status_code == 404
|
||||
assert res_get.json()["error"]["code"] == "not_found"
|
||||
|
||||
# Попытка чужого пользователя написать в чат -> 404
|
||||
res_post = client.post(f"/api/v1/chats/{chat['id']}/messages", json={"text": "hack"}, headers={"X-User-Id": u2["id"]})
|
||||
assert res_post.status_code == 404
|
||||
assert res_post.json()["error"]["code"] == "not_found"
|
||||
|
||||
def test_pagination_multi_page():
|
||||
u = create_user("user_paging")
|
||||
chat = client.post("/api/v1/chats", json={"title": "Paging Chat", "member_ids": [u["id"]]}, headers={"X-User-Id": u["id"]}).json()
|
||||
chat_id = chat["id"]
|
||||
|
||||
# Отправляем 5 сообщений
|
||||
sent_texts = [f"Message {i}" for i in range(5)]
|
||||
for text in sent_texts:
|
||||
client.post(f"/api/v1/chats/{chat_id}/messages", json={"text": text}, headers={"X-User-Id": u["id"]})
|
||||
|
||||
# Обходим страницы порциями по 2 сообщения
|
||||
all_received_items = []
|
||||
cursor = None
|
||||
page_count = 0
|
||||
|
||||
while True:
|
||||
url = f"/api/v1/chats/{chat_id}/messages?limit=2"
|
||||
if cursor:
|
||||
url += f"&cursor={cursor}"
|
||||
res = client.get(url, headers={"X-User-Id": u["id"]})
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
all_received_items.extend(data["items"])
|
||||
cursor = data.get("next_cursor")
|
||||
page_count += 1
|
||||
if not cursor:
|
||||
break
|
||||
|
||||
# Проверяем, что разбилось на 3 страницы (2 + 2 + 1)
|
||||
assert page_count == 3
|
||||
# Проверяем, что получены все 5 сообщений без потерь
|
||||
assert len(all_received_items) == 5
|
||||
assert {m["text"] for m in all_received_items} == set(sent_texts)
|
||||
|
||||
# Проверяем строгое соответствие контракту: порядок (created_at, id) строго возрастает
|
||||
for i in range(len(all_received_items) - 1):
|
||||
prev = (all_received_items[i]["created_at"], all_received_items[i]["id"])
|
||||
curr = (all_received_items[i+1]["created_at"], all_received_items[i+1]["id"])
|
||||
assert prev < curr
|
||||
Reference in New Issue
Block a user