forked from mtusi2026/mtusi2026lab2
188 lines
6.0 KiB
Python
188 lines
6.0 KiB
Python
import base64
|
|
import os
|
|
import threading
|
|
import uuid
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from urllib.parse import quote
|
|
|
|
import pytest
|
|
from client import LAB, Client
|
|
|
|
|
|
@pytest.fixture
|
|
def scenario():
|
|
c = Client(os.environ.get("BASE_URL", "http://127.0.0.1:8081"))
|
|
return c, *c.bootstrap()
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"body",
|
|
[
|
|
{"text": ""},
|
|
{"text": " \n\t"},
|
|
{"text": 1},
|
|
{"text": True},
|
|
{"text": None},
|
|
{"text": "x", "sender_id": str(uuid.uuid4())},
|
|
{"text": "x", "unknown": 1},
|
|
{"text": "x" * 4001},
|
|
{},
|
|
[],
|
|
],
|
|
)
|
|
def test_invalid_message(scenario, body):
|
|
c, alice, _, _, chat = scenario
|
|
c.call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, actor=alice, body=body)
|
|
|
|
|
|
def test_malformed_json(scenario):
|
|
c, alice, _, _, chat = scenario
|
|
c.call(
|
|
"POST",
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
400,
|
|
actor=alice,
|
|
raw=b'{"text":',
|
|
headers={"Content-Type": "application/json"},
|
|
)
|
|
|
|
|
|
def test_acl_and_unknown_chat(scenario):
|
|
c, alice, _, eve, chat = scenario
|
|
for cid in [chat["id"], str(uuid.uuid4())]:
|
|
for suffix in ["", "/messages"]:
|
|
c.call("GET", f"/api/v1/chats/{cid}{suffix}", 404, actor=eve)
|
|
c.call("POST", f"/api/v1/chats/{cid}/messages", 404, actor=eve, body={"text": "x"})
|
|
c.call("GET", "/api/v1/chats/not-a-uuid", 400, actor=alice)
|
|
|
|
|
|
@pytest.mark.parametrize("name", ["ab", "UPPER", "a-b", "a" * 33, "имя", "abc\n"])
|
|
def test_username_validation(scenario, name):
|
|
c, alice, *_ = scenario
|
|
body = {**alice["registration"], "username": name}
|
|
c.call("POST", "/api/v1/users", 400, body=body)
|
|
|
|
|
|
def test_unicode_and_limits(scenario):
|
|
c, alice, _, _, chat = scenario
|
|
text = "Ё👩💻漢字" * 500
|
|
assert c.message(alice, chat, text)["json"]["text"] == text
|
|
c.call(
|
|
"POST",
|
|
"/api/v1/users",
|
|
400,
|
|
body={
|
|
**alice["registration"],
|
|
"username": "u_" + uuid.uuid4().hex[:12],
|
|
"display_name": " ",
|
|
},
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("value", ["0", "101", "1.5", "true", "-1", "", "1&limit=2"])
|
|
def test_invalid_limit(scenario, value):
|
|
c, alice, _, _, chat = scenario
|
|
c.call("GET", f"/api/v1/chats/{chat['id']}/messages?limit={value}", 400, actor=alice)
|
|
|
|
|
|
def test_pagination_and_cursor_scope(scenario):
|
|
c, alice, bob, _, chat = scenario
|
|
expected = [c.message(alice, chat, str(i))["json"] for i in range(13)]
|
|
path = f"/api/v1/chats/{chat['id']}/messages"
|
|
result, cursor, first = [], None, None
|
|
for i in range(20):
|
|
url = path + f"?limit={2 if i == 0 else 3}"
|
|
if cursor:
|
|
url += "&cursor=" + quote(cursor, safe="")
|
|
data = c.call("GET", url, actor=bob, schema="MessagePage")["json"]
|
|
result += data["items"]
|
|
cursor = data["next_cursor"]
|
|
first = first or cursor
|
|
if cursor is None:
|
|
break
|
|
assert result == sorted(expected, key=lambda m: (m["created_at"], m["id"]))
|
|
other = c.call(
|
|
"POST",
|
|
"/api/v1/chats",
|
|
201,
|
|
actor=alice,
|
|
body={"title": "другой", "member_ids": [alice["id"]]},
|
|
schema="Chat",
|
|
)["json"]
|
|
c.call("GET", f"/api/v1/chats/{other['id']}/messages?cursor={first}", 400, actor=alice)
|
|
c.call("GET", path + "?cursor=broken", 400, actor=alice)
|
|
|
|
|
|
def test_chat_validation_and_atomicity(scenario):
|
|
c, alice, bob, _, _ = scenario
|
|
before = c.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]
|
|
for members in [
|
|
[bob["id"]],
|
|
[alice["id"], alice["id"]],
|
|
[alice["id"], str(uuid.uuid4())],
|
|
[],
|
|
[123],
|
|
]:
|
|
c.call(
|
|
"POST",
|
|
"/api/v1/chats",
|
|
400,
|
|
actor=alice,
|
|
body={"title": "не должен появиться", "member_ids": members},
|
|
)
|
|
after = c.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"]
|
|
assert before == after
|
|
|
|
|
|
def test_concurrent_messages(scenario):
|
|
c, alice, bob, _, chat = scenario
|
|
barrier = threading.Barrier(10)
|
|
|
|
def sender(i):
|
|
local = Client(c.base)
|
|
barrier.wait()
|
|
return [local.message(alice, chat, f"{i}:{j}")["json"] for j in range(10)]
|
|
|
|
with ThreadPoolExecutor(max_workers=10) as pool:
|
|
sent = [m for batch in pool.map(sender, range(10)) for m in batch]
|
|
data = c.call(
|
|
"GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", actor=bob, schema="MessagePage"
|
|
)["json"]
|
|
assert len(sent) == len({m["id"] for m in sent}) == len(data["items"]) == 100
|
|
assert {m["id"] for m in sent} == {m["id"] for m in data["items"]}
|
|
assert data["next_cursor"] is None
|
|
|
|
|
|
def test_registration_race(scenario):
|
|
c, alice, *_ = scenario
|
|
body = {**alice["registration"], "username": "race_" + uuid.uuid4().hex[:12]}
|
|
barrier = threading.Barrier(10)
|
|
|
|
def register(_):
|
|
local = Client(c.base)
|
|
barrier.wait()
|
|
return local.call("POST", "/api/v1/users", [201, 409], body=body)["status"]
|
|
|
|
with ThreadPoolExecutor(max_workers=10) as pool:
|
|
statuses = list(pool.map(register, range(10)))
|
|
assert statuses.count(201) == 1
|
|
assert statuses.count(409) == 9
|
|
|
|
|
|
@pytest.mark.skipif(LAB < 2, reason="Сессии появляются в ЛР2")
|
|
def test_sessions(scenario):
|
|
c, alice, _, eve, _ = scenario
|
|
credential = base64.b64encode(
|
|
(alice["registration"]["username"] + ":wrong-password").encode()
|
|
).decode()
|
|
c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": "Basic " + credential})
|
|
c.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": alice["id"]})
|
|
assert (
|
|
c.call(
|
|
"GET", "/api/v1/users/me", actor=alice, headers={"X-User-Id": eve["id"]}, schema="User"
|
|
)["json"]
|
|
== alice["user"]
|
|
)
|
|
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
|
c.call("GET", "/api/v1/users/me", 401, actor=alice)
|