Добавить PostgreSQL, постоянные сессии, кэш и проверки ЛР2

This commit is contained in:
2026-10-30 17:24:20 +03:00
parent 65003b6119
commit a39b4fea27
29 changed files with 2776 additions and 20 deletions
+187
View File
@@ -0,0 +1,187 @@
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)
+99
View File
@@ -0,0 +1,99 @@
import base64
import json
import os
import uuid
from urllib.parse import quote
import pytest
from client import LAB, Client
@pytest.fixture
def edge_scenario():
client = Client(os.environ.get("BASE_URL", "http://127.0.0.1:8081"))
return client, *client.bootstrap()
def encoded_cursor(value):
return base64.urlsafe_b64encode(json.dumps(value).encode()).decode().rstrip("=")
@pytest.mark.parametrize("identity", ["missing", "malformed", "unknown"])
def test_invalid_identity(edge_scenario, identity):
client, _, _, _, chat = edge_scenario
headers = {}
if identity == "malformed":
headers["X-User-Id"] = "not-a-uuid"
elif identity == "unknown":
headers["X-User-Id"] = str(uuid.uuid4())
for path in ["/api/v1/users/me", "/api/v1/chats", f"/api/v1/chats/{chat['id']}/messages"]:
client.call("GET", path, 401, headers=headers)
@pytest.mark.parametrize("uid", [None, [], {}, 123, True, "not-a-uuid"])
def test_cursor_rejects_non_uuid_boundary(edge_scenario, uid):
client, alice, _, _, chat = edge_scenario
payload = [1, "messages:" + chat["id"], "2026-10-30T12:00:00.000000Z", uid]
cursor = quote(encoded_cursor(payload), safe="")
client.call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor={cursor}", 400, actor=alice)
@pytest.mark.parametrize(
"payload", [None, {}, [], [1], [1, "wrong-scope", "2026-10-30T12:00:00Z", str(uuid.uuid4())]]
)
def test_cursor_rejects_wrong_shape(edge_scenario, payload):
client, alice, _, _, chat = edge_scenario
cursor = quote(encoded_cursor(payload), safe="")
client.call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor={cursor}", 400, actor=alice)
def test_request_id_is_present_and_not_reused(edge_scenario):
client, alice, _, _, _ = edge_scenario
first = client.call("GET", "/health/live", schema="Health")
second = client.call("GET", "/health/ready", schema="Health")
error = client.call("GET", "/api/v1/chats/malformed", 400, actor=alice)
values = [r["headers"]["X-Request-Id"] for r in [first, second, error]]
assert len(set(values)) == 3
assert error["json"]["error"]["request_id"] == values[-1]
def test_unicode_codepoint_boundaries(edge_scenario):
client, alice, _, _, chat = edge_scenario
username = "unicode_" + uuid.uuid4().hex[:12]
registration = {"username": username, "display_name": "😀" * 100}
if LAB >= 2:
registration["password"] = "unicode-test-" + uuid.uuid4().hex
user = client.call(
"POST",
"/api/v1/users",
201,
body=registration,
schema="User",
)["json"]
assert user["display_name"] == "😀" * 100
client.call(
"POST", "/api/v1/users", 400, body={"username": username + "x", "display_name": "😀" * 101}
)
message = client.message(alice, chat, "😀" * 4000)["json"]
assert message["text"] == "😀" * 4000
client.call(
"POST", f"/api/v1/chats/{chat['id']}/messages", 400, actor=alice, body={"text": "😀" * 4001}
)
def test_empty_history_and_cursor_exhaustion(edge_scenario):
client, alice, _, _, chat = edge_scenario
path = f"/api/v1/chats/{chat['id']}/messages"
empty = client.call("GET", path, actor=alice, schema="MessagePage")["json"]
assert empty == {"items": [], "next_cursor": None}
message = client.message(alice, chat, "одна запись")["json"]
data = client.call("GET", path + "?limit=1", actor=alice, schema="MessagePage")["json"]
assert data == {"items": [message], "next_cursor": None}
def test_missing_chat_is_hidden_like_foreign_chat(edge_scenario):
client, _, _, eve, chat = edge_scenario
foreign = client.call("GET", f"/api/v1/chats/{chat['id']}", 404, actor=eve)["json"]
missing = client.call("GET", f"/api/v1/chats/{uuid.uuid4()}", 404, actor=eve)["json"]
assert foreign["error"]["code"] == missing["error"]["code"] == "not_found"
assert foreign["error"]["message"] == missing["error"]["message"]
+63
View File
@@ -0,0 +1,63 @@
import base64
import uuid
import pytest
from client import Client
@pytest.mark.parametrize("password", ["x" * 11, "x" * 129, "😀" * 129, 123, None, True])
def test_password_contract(password):
import os
c = Client(os.environ["BASE_URL"])
c.call(
"POST",
"/api/v1/users",
400,
body={
"username": "pwd_" + uuid.uuid4().hex[:12],
"display_name": "Тест",
"password": password,
},
)
def test_full_unicode_password_and_colon():
import os
c = Client(os.environ["BASE_URL"])
username = "pwd_" + uuid.uuid4().hex[:12]
password = "😀" * 126 + ":Я"
user = c.call(
"POST",
"/api/v1/users",
201,
body={"username": username, "display_name": "Пароль128", "password": password},
schema="User",
)["json"]
good = base64.b64encode((username + ":" + password).encode()).decode()
session = c.call(
"POST",
"/api/v1/auth/sessions",
201,
headers={"Authorization": "bAsIc " + good},
raw=b"this body must be ignored",
schema="Session",
)["json"]
actor = {"id": user["id"], "token": session["token"]}
assert session["user"] == user
bad = base64.b64encode((username + ":" + password[:-1] + "Б").encode()).decode()
c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": "Basic " + bad})
c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Basic " + good})
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=actor)
c.call("GET", "/api/v1/users/me", 401, actor=actor)
@pytest.mark.parametrize("credential", ["Basic !invalid", "Basic", "Bearer abc", "", "Basic YTpi"])
def test_invalid_basic(credential):
import os
Client(os.environ["BASE_URL"]).call(
"POST", "/api/v1/auth/sessions", 401, headers={"Authorization": credential}
)