forked from mtusi2026/mtusi2026lab2
feat: persist messenger data and sessions in PostgreSQL
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from jsonschema import Draft202012Validator, FormatChecker
|
||||
|
||||
CONTRACT = json.loads(
|
||||
(Path(__file__).parents[1] / "contracts/openapi.json").read_text()
|
||||
)
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
|
||||
|
||||
|
||||
def check(result: httpx.Response, status: int, schema: str) -> dict:
|
||||
assert result.status_code == status, result.text
|
||||
assert result.headers["x-request-id"]
|
||||
assert result.headers["content-type"].startswith("application/json")
|
||||
payload = result.json()
|
||||
spec = {"$ref": f"#/components/schemas/{schema}", **CONTRACT}
|
||||
Draft202012Validator(spec, format_checker=FormatChecker()).validate(
|
||||
payload
|
||||
)
|
||||
if schema == "Error":
|
||||
assert payload["error"]["request_id"] == result.headers["x-request-id"]
|
||||
assert (
|
||||
payload["error"]["code"]
|
||||
== {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
500: "internal_error",
|
||||
}[status]
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def register(client: httpx.Client, **overrides) -> dict:
|
||||
data = {"username": "u_" + uuid4().hex[:24], "display_name": "Алиса 🌍"}
|
||||
data.update(overrides)
|
||||
return check(client.post("/api/v1/users", json=data), 201, "User")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
with httpx.Client(
|
||||
base_url=BASE_URL, timeout=15, trust_env=False
|
||||
) as client:
|
||||
yield client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def actors(client):
|
||||
return register(client), register(client), register(client)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def chat(client, actors):
|
||||
alice, bob, _ = actors
|
||||
return check(
|
||||
client.post(
|
||||
"/api/v1/chats",
|
||||
headers={"X-User-Id": alice["id"]},
|
||||
json={"title": "Учёба 🌍", "member_ids": [alice["id"], bob["id"]]},
|
||||
),
|
||||
201,
|
||||
"Chat",
|
||||
)
|
||||
|
||||
|
||||
def headers(actor: dict) -> dict:
|
||||
return {"X-User-Id": actor["id"]}
|
||||
|
||||
|
||||
def history(client, actor, chat_id, limit=7):
|
||||
found, cursor = [], None
|
||||
while True:
|
||||
params = {"limit": limit}
|
||||
if cursor:
|
||||
params["cursor"] = cursor
|
||||
page = check(
|
||||
client.get(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
headers=headers(actor),
|
||||
params=params,
|
||||
),
|
||||
200,
|
||||
"MessagePage",
|
||||
)
|
||||
found.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return found
|
||||
Reference in New Issue
Block a user