forked from mtusi2026/mtusi2026lab3
413 lines
10 KiB
Python
413 lines
10 KiB
Python
import base64
|
|
import json
|
|
import threading
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from uuid import UUID, uuid4
|
|
|
|
import httpx
|
|
import pytest
|
|
from conftest import BASE_URL, PASSWORD, check, headers, history, register
|
|
|
|
|
|
@pytest.mark.parametrize("path", ["/health/live", "/health/ready"])
|
|
def test_health(client, path):
|
|
assert check(client.get(path), 200, "Health") == {"status": "ok"}
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"value", [None, "not-a-uuid", str(uuid4()), uuid4().hex]
|
|
)
|
|
def test_identification(client, value):
|
|
check(
|
|
client.get(
|
|
"/api/v1/users/me", headers={"X-User-Id": value} if value else {}
|
|
),
|
|
401,
|
|
"Error",
|
|
)
|
|
|
|
|
|
def test_identity(client, actors):
|
|
assert (
|
|
check(
|
|
client.get("/api/v1/users/me", headers=headers(actors[0])),
|
|
200,
|
|
"User",
|
|
)
|
|
== actors[0]
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"data",
|
|
[
|
|
{},
|
|
[],
|
|
None,
|
|
{"username": "ABC", "display_name": "A"},
|
|
{"username": "abc\n", "display_name": "A"},
|
|
{"username": 123, "display_name": "A"},
|
|
{"username": "abc", "display_name": " "},
|
|
{"username": "abc", "display_name": "x" * 101},
|
|
{"username": "abc", "display_name": "A", "extra": True},
|
|
{"username": "abc", "display_name": "\ud800"},
|
|
],
|
|
)
|
|
def test_invalid_user(client, data):
|
|
if isinstance(data, dict):
|
|
data = {"password": PASSWORD, **data}
|
|
check(client.post("/api/v1/users", content=json.dumps(data)), 400, "Error")
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"raw", [b"{", b"NaN", b'{"username":"abc", "display_name":NaN}', b"\xff"]
|
|
)
|
|
def test_malformed_json(client, raw):
|
|
check(client.post("/api/v1/users", content=raw), 400, "Error")
|
|
|
|
|
|
def test_auth_before_json(client):
|
|
check(client.post("/api/v1/chats", content=b"{"), 401, "Error")
|
|
|
|
|
|
def test_duplicate_username(client, actors):
|
|
check(
|
|
client.post(
|
|
"/api/v1/users",
|
|
json={
|
|
"username": actors[0]["username"],
|
|
"display_name": "B",
|
|
"password": PASSWORD,
|
|
},
|
|
),
|
|
409,
|
|
"Error",
|
|
)
|
|
|
|
|
|
def test_unicode_codepoints(client, actors, chat):
|
|
user = register(client, display_name="🌍" * 100)
|
|
assert user["display_name"] == "🌍" * 100
|
|
text = "🌍" * 4000
|
|
result = check(
|
|
client.post(
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
headers=headers(actors[0]),
|
|
json={"text": text},
|
|
),
|
|
201,
|
|
"Message",
|
|
)
|
|
assert result["text"] == text
|
|
assert result["sender_id"] == actors[0]["id"]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"method,suffix,body",
|
|
[
|
|
("GET", "", None),
|
|
("GET", "/messages", None),
|
|
("POST", "/messages", {"text": "hello"}),
|
|
],
|
|
)
|
|
def test_acl(client, actors, chat, method, suffix, body):
|
|
outsider = headers(actors[2])
|
|
actual = check(
|
|
client.request(
|
|
method,
|
|
f"/api/v1/chats/{chat['id']}{suffix}",
|
|
headers=outsider,
|
|
json=body,
|
|
),
|
|
404,
|
|
"Error",
|
|
)
|
|
missing = check(
|
|
client.request(
|
|
method,
|
|
f"/api/v1/chats/{uuid4()}{suffix}",
|
|
headers=outsider,
|
|
json=body,
|
|
),
|
|
404,
|
|
"Error",
|
|
)
|
|
assert actual["error"]["message"] == missing["error"]["message"]
|
|
|
|
|
|
@pytest.mark.parametrize("value", ["", " \t\n", 42, True, None, "a" * 4001])
|
|
def test_bad_message(client, actors, chat, value):
|
|
check(
|
|
client.post(
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
headers=headers(actors[0]),
|
|
json={"text": value},
|
|
),
|
|
400,
|
|
"Error",
|
|
)
|
|
|
|
|
|
def test_sender_not_client_controlled(client, actors, chat):
|
|
check(
|
|
client.post(
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
headers=headers(actors[0]),
|
|
json={"text": "Hi", "sender_id": actors[1]["id"]},
|
|
),
|
|
400,
|
|
"Error",
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"case",
|
|
[
|
|
"duplicate",
|
|
"unknown",
|
|
"no_caller",
|
|
"empty",
|
|
"wrong_type",
|
|
"bad_uuid",
|
|
"too_many",
|
|
"blank_title",
|
|
],
|
|
)
|
|
def test_invalid_chat(client, actors, case):
|
|
a, b, _ = actors
|
|
members = {
|
|
"duplicate": [a["id"], a["id"]],
|
|
"unknown": [a["id"], str(uuid4())],
|
|
"no_caller": [b["id"]],
|
|
"empty": [],
|
|
"wrong_type": a["id"],
|
|
"bad_uuid": ["broken"],
|
|
"too_many": [str(uuid4()) for _ in range(101)],
|
|
"blank_title": [a["id"]],
|
|
}[case]
|
|
check(
|
|
client.post(
|
|
"/api/v1/chats",
|
|
headers=headers(a),
|
|
json={
|
|
"title": " " if case == "blank_title" else "Title",
|
|
"member_ids": members,
|
|
},
|
|
),
|
|
400,
|
|
"Error",
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"limit", ["0", "101", "-1", "1.5", "true", "1e1", "", "12"]
|
|
)
|
|
def test_bad_limit(client, actors, chat, limit):
|
|
check(
|
|
client.get(
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
headers=headers(actors[0]),
|
|
params={"limit": limit},
|
|
),
|
|
400,
|
|
"Error",
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"cursor", ["", "broken", "W10", "e30", "*", "x" * 2049]
|
|
)
|
|
def test_bad_cursor(client, actors, chat, cursor):
|
|
check(
|
|
client.get(
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
headers=headers(actors[0]),
|
|
params={"cursor": cursor},
|
|
),
|
|
400,
|
|
"Error",
|
|
)
|
|
|
|
|
|
def test_pagination(client, actors, chat):
|
|
a, b, outsider = actors
|
|
sent = []
|
|
path = f"/api/v1/chats/{chat['id']}/messages"
|
|
for i in range(23):
|
|
sent.append(
|
|
check(
|
|
client.post(
|
|
path,
|
|
headers=headers(a if i % 2 else b),
|
|
json={"text": f"Msg {i}"},
|
|
),
|
|
201,
|
|
"Message",
|
|
)
|
|
)
|
|
got = history(client, a, chat["id"])
|
|
assert got == sorted(
|
|
sent, key=lambda m: (m["created_at"], UUID(m["id"]).int)
|
|
)
|
|
first = check(
|
|
client.get(path, headers=headers(a), params={"limit": 1}),
|
|
200,
|
|
"MessagePage",
|
|
)
|
|
second = check(
|
|
client.get(
|
|
path,
|
|
headers=headers(b),
|
|
params={"limit": 22, "cursor": first["next_cursor"]},
|
|
),
|
|
200,
|
|
"MessagePage",
|
|
)
|
|
assert second["items"] == got[1:]
|
|
assert second["next_cursor"] is None
|
|
chats = check(
|
|
client.get("/api/v1/chats", headers=headers(outsider)), 200, "ChatPage"
|
|
)
|
|
assert chats["items"] == []
|
|
other = check(
|
|
client.post(
|
|
"/api/v1/chats",
|
|
headers=headers(a),
|
|
json={"title": "Other", "member_ids": [a["id"]]},
|
|
),
|
|
201,
|
|
"Chat",
|
|
)
|
|
check(
|
|
client.get(
|
|
f"/api/v1/chats/{other['id']}/messages",
|
|
headers=headers(a),
|
|
params={"cursor": first["next_cursor"]},
|
|
),
|
|
400,
|
|
"Error",
|
|
)
|
|
# Валидный base64/JSON с неверным типом ключа тоже даёт 400.
|
|
data = json.loads(
|
|
base64.urlsafe_b64decode(
|
|
first["next_cursor"] + "=" * (-len(first["next_cursor"]) % 4)
|
|
)
|
|
)
|
|
data["at"] = 17
|
|
forged = (
|
|
base64.urlsafe_b64encode(json.dumps(data).encode())
|
|
.decode()
|
|
.rstrip("=")
|
|
)
|
|
check(
|
|
client.get(path, headers=headers(a), params={"cursor": forged}),
|
|
400,
|
|
"Error",
|
|
)
|
|
|
|
|
|
def test_chat_pagination_scope(client, actors):
|
|
a, b, _ = actors
|
|
created = []
|
|
for i in range(4):
|
|
created.append(
|
|
check(
|
|
client.post(
|
|
"/api/v1/chats",
|
|
headers=headers(a),
|
|
json={"title": str(i), "member_ids": [a["id"], b["id"]]},
|
|
),
|
|
201,
|
|
"Chat",
|
|
)
|
|
)
|
|
page = check(
|
|
client.get("/api/v1/chats", headers=headers(a), params={"limit": 2}),
|
|
200,
|
|
"ChatPage",
|
|
)
|
|
assert page["items"] == created[:2]
|
|
last = check(
|
|
client.get(
|
|
"/api/v1/chats",
|
|
headers=headers(a),
|
|
params={"limit": 2, "cursor": page["next_cursor"]},
|
|
),
|
|
200,
|
|
"ChatPage",
|
|
)
|
|
assert last["items"] == created[2:]
|
|
assert last["next_cursor"] is None
|
|
check(
|
|
client.get(
|
|
"/api/v1/chats",
|
|
headers=headers(b),
|
|
params={"cursor": page["next_cursor"]},
|
|
),
|
|
400,
|
|
"Error",
|
|
)
|
|
|
|
|
|
def test_concurrent_messages(client, actors, chat):
|
|
barrier = threading.Barrier(10)
|
|
a = actors[0]
|
|
path = f"/api/v1/chats/{chat['id']}/messages"
|
|
|
|
def worker(i):
|
|
with httpx.Client(
|
|
base_url=BASE_URL, timeout=15, trust_env=False
|
|
) as conn:
|
|
barrier.wait(timeout=15)
|
|
return [
|
|
check(
|
|
conn.post(
|
|
path, headers=headers(a), json={"text": f"{i}:{j}"}
|
|
),
|
|
201,
|
|
"Message",
|
|
)["id"]
|
|
for j in range(10)
|
|
]
|
|
|
|
with ThreadPoolExecutor(max_workers=10) as pool:
|
|
ids = [item for batch in pool.map(worker, range(10)) for item in batch]
|
|
rows = history(client, a, chat["id"])
|
|
assert len(rows) == len(ids) == len(set(ids)) == 100
|
|
assert set(ids) == {row["id"] for row in rows}
|
|
assert len({row["text"] for row in rows}) == 100
|
|
|
|
|
|
def test_registration_race(client):
|
|
username = "race_" + uuid4().hex[:20]
|
|
barrier = threading.Barrier(10)
|
|
|
|
def worker(_):
|
|
with httpx.Client(
|
|
base_url=BASE_URL, timeout=15, trust_env=False
|
|
) as conn:
|
|
barrier.wait(timeout=15)
|
|
result = conn.post(
|
|
"/api/v1/users",
|
|
json={
|
|
"username": username,
|
|
"display_name": "Test",
|
|
"password": PASSWORD,
|
|
},
|
|
)
|
|
check(
|
|
result,
|
|
result.status_code,
|
|
"User" if result.status_code == 201 else "Error",
|
|
)
|
|
return result.status_code
|
|
|
|
with ThreadPoolExecutor(max_workers=10) as pool:
|
|
statuses = list(pool.map(worker, range(10)))
|
|
assert statuses.count(201) == 1
|
|
assert statuses.count(409) == 9
|
|
|
|
|
|
def test_unknown_path(client):
|
|
check(client.get("/does-not-exist"), 404, "Error")
|