forked from mtusi2026/mtusi2026lab2
ЛР 2: PostgreSQL, сессии Basic/Bearer, Redis-кэш, тесты и отчёт
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
"""Общий HTTP-клиент для собственных тестов (только стандартная библиотека)."""
|
||||
import base64
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
PASSWORD = "Test-password-" + uuid.uuid4().hex[:8]
|
||||
|
||||
|
||||
class Api:
|
||||
def __init__(self, base: str):
|
||||
self.base = base.rstrip("/")
|
||||
|
||||
def raw(self, method, path, data=None, headers=None, timeout=10):
|
||||
req = urllib.request.Request(self.base + path, data=data, headers=headers or {}, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return r.status, r.read(), r.headers
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read(), e.headers
|
||||
|
||||
def call(self, method, path, body=None, token=None, headers=None):
|
||||
h = dict(headers or {})
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
if token:
|
||||
h["Authorization"] = "Bearer " + token
|
||||
st, raw, rh = self.raw(method, path, data, h)
|
||||
try:
|
||||
return st, json.loads(raw or b"null"), rh
|
||||
except ValueError:
|
||||
return st, None, rh
|
||||
|
||||
def register(self, prefix: str, password: str = PASSWORD) -> dict:
|
||||
name = (prefix + "_" + uuid.uuid4().hex[:10])[:32]
|
||||
st, user, _ = self.call("POST", "/api/v1/users",
|
||||
{"username": name, "display_name": prefix, "password": password})
|
||||
assert st == 201, f"register {name}: {st} {user}"
|
||||
user["password"] = password
|
||||
return user
|
||||
|
||||
def login(self, username: str, password: str):
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
st, body, rh = self.call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred})
|
||||
return st, body, rh
|
||||
|
||||
def new_user(self, prefix: str) -> dict:
|
||||
user = self.register(prefix)
|
||||
st, sess, _ = self.login(user["username"], user["password"])
|
||||
assert st == 201, f"login: {st}"
|
||||
user["token"] = sess["token"]
|
||||
return user
|
||||
|
||||
|
||||
class Report:
|
||||
def __init__(self):
|
||||
self.passed = self.failed = 0
|
||||
|
||||
def check(self, cond, name):
|
||||
if cond:
|
||||
self.passed += 1
|
||||
print(f" ok - {name}")
|
||||
else:
|
||||
self.failed += 1
|
||||
print(f" FAIL - {name}")
|
||||
|
||||
def finish(self):
|
||||
print(f"\n{self.passed} passed, {self.failed} failed")
|
||||
raise SystemExit(1 if self.failed else 0)
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Истечение сессии при коротком SESSION_TTL_SECONDS (=2).
|
||||
Запускается против отдельного экземпляра API с коротким TTL:
|
||||
docker compose --env-file .env --profile ttl up -d api-ttl
|
||||
python student-tests/expiry.py --base-url http://localhost:8081
|
||||
"""
|
||||
import argparse
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from common import Api, Report
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8081")
|
||||
ap.add_argument("--ttl", type=float, default=2)
|
||||
args = ap.parse_args()
|
||||
api, r = Api(args.base_url), Report()
|
||||
|
||||
user = api.register("ttl")
|
||||
st, sess, _ = api.login(user["username"], user["password"])
|
||||
r.check(st == 201, "login -> 201")
|
||||
exp = datetime.fromisoformat(sess["expires_at"].replace("Z", "+00:00"))
|
||||
left = (exp - datetime.now(timezone.utc)).total_seconds()
|
||||
r.check(0 < left <= args.ttl + 1, f"expires_at is about {args.ttl}s ahead (got {left:.2f}s)")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token=sess["token"])
|
||||
r.check(st == 200, "token works before expiry") # заодно кладёт сессию в кэш Redis
|
||||
time.sleep(args.ttl + 1.5)
|
||||
st, _, rh = api.call("GET", "/api/v1/users/me", token=sess["token"])
|
||||
r.check(st == 401 and rh.get("WWW-Authenticate", "").startswith("Bearer"),
|
||||
"expired token -> 401 (cache does not extend the session)")
|
||||
r.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,60 @@
|
||||
-- План запроса истории на ≥10 000 сообщениях (уровень «4»).
|
||||
-- Всё внутри транзакции с ROLLBACK: учебные данные не остаются в базе.
|
||||
-- Запуск (одинаково в PowerShell и sh):
|
||||
-- docker compose cp student-tests/explain.sql postgres:/tmp/explain.sql
|
||||
-- docker compose exec postgres psql -U messenger -d messenger -f /tmp/explain.sql
|
||||
BEGIN;
|
||||
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ('00000000-0000-4000-8000-000000000001', 'explain_seed', 'Seed', 'x', now());
|
||||
|
||||
-- Чат, историю которого читаем, и 9 «соседних» чатов, чтобы в таблице были чужие сообщения.
|
||||
INSERT INTO chats (id, title, created_by, created_at)
|
||||
SELECT ('00000000-0000-4000-8000-0000000001' || lpad(g::text, 2, '0'))::uuid, 'seed ' || g,
|
||||
'00000000-0000-4000-8000-000000000001', now()
|
||||
FROM generate_series(0, 9) g;
|
||||
|
||||
INSERT INTO chat_members (chat_id, user_id, position)
|
||||
SELECT ('00000000-0000-4000-8000-0000000001' || lpad(g::text, 2, '0'))::uuid,
|
||||
'00000000-0000-4000-8000-000000000001', 0
|
||||
FROM generate_series(0, 9) g;
|
||||
|
||||
-- 12 000 сообщений в целевом чате + 48 000 в соседних = 60 000 строк.
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(),
|
||||
('00000000-0000-4000-8000-0000000001' || lpad((CASE WHEN g <= 12000 THEN 0 ELSE g % 9 + 1 END)::text, 2, '0'))::uuid,
|
||||
'00000000-0000-4000-8000-000000000001',
|
||||
'msg ' || g,
|
||||
now() - interval '1 day' + g * interval '1 millisecond'
|
||||
FROM generate_series(1, 60000) g;
|
||||
|
||||
ANALYZE messages;
|
||||
|
||||
SELECT count(*) AS messages_in_target_chat
|
||||
FROM messages WHERE chat_id = '00000000-0000-4000-8000-000000000100';
|
||||
|
||||
\echo '=== 1. Первая страница (limit 50 + 1) ==='
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-000000000100'
|
||||
ORDER BY created_at, id LIMIT 51;
|
||||
|
||||
\echo '=== 2. Страница из середины истории (keyset-курсор после ~6000-го сообщения) ==='
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-000000000100'
|
||||
AND (created_at, id) > (now() - interval '1 day' + 6000 * interval '1 millisecond',
|
||||
'00000000-0000-0000-0000-000000000000')
|
||||
ORDER BY created_at, id LIMIT 51;
|
||||
|
||||
\echo '=== 3. Для сравнения: та же страница, если запретить индекс ==='
|
||||
SET LOCAL enable_indexscan = off;
|
||||
SET LOCAL enable_bitmapscan = off;
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-000000000100'
|
||||
AND (created_at, id) > (now() - interval '1 day' + 6000 * interval '1 millisecond',
|
||||
'00000000-0000-0000-0000-000000000000')
|
||||
ORDER BY created_at, id LIMIT 51;
|
||||
|
||||
ROLLBACK;
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Недоступность зависимостей (уровень «4»). Сам останавливает и запускает контейнеры:
|
||||
python student-tests/outage.py --base-url http://localhost:8080
|
||||
|
||||
1. Redis остановлен → API работает в обход кэша (сессии читаются из PostgreSQL).
|
||||
2. PostgreSQL остановлен → защищённые запросы получают ограниченную ошибку 503,
|
||||
неизвестный токен НЕ принимается (никогда 200), /health/ready = 503.
|
||||
3. PostgreSQL запущен снова → тот же токен снова работает, данные на месте.
|
||||
"""
|
||||
import argparse
|
||||
import shlex
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from common import Api, Report
|
||||
|
||||
COMPOSE = "docker compose --env-file .env"
|
||||
|
||||
|
||||
def sh(cmd: str):
|
||||
print(f" $ {cmd}")
|
||||
subprocess.run(shlex.split(cmd), check=True, stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def wait_ready(api: Api, seconds=90):
|
||||
deadline = time.time() + seconds
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
if api.raw("GET", "/health/ready", timeout=3)[0] == 200:
|
||||
return True
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--stop-redis", default=f"{COMPOSE} stop redis")
|
||||
ap.add_argument("--start-redis", default=f"{COMPOSE} start redis")
|
||||
ap.add_argument("--stop-db", default=f"{COMPOSE} stop postgres")
|
||||
ap.add_argument("--start-db", default=f"{COMPOSE} start postgres")
|
||||
args = ap.parse_args()
|
||||
api, r = Api(args.base_url), Report()
|
||||
|
||||
user = api.new_user("outage")
|
||||
st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "outage", "member_ids": [user["id"]]}, token=user["token"])
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
api.call("POST", path, {"text": "before outage"}, token=user["token"])
|
||||
|
||||
print("== 1. Redis недоступен ==")
|
||||
sh(args.stop_redis)
|
||||
try:
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token=user["token"])
|
||||
r.check(st == 200, "valid token still works without Redis (cache bypassed)")
|
||||
st, _, _ = api.call("POST", path, {"text": "without redis"}, token=user["token"])
|
||||
r.check(st == 201, "writes still work without Redis")
|
||||
fresh = api.register("noredis")
|
||||
st, sess, _ = api.login(fresh["username"], fresh["password"])
|
||||
r.check(st == 201, "login works without Redis")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token="forged-" + uuid.uuid4().hex)
|
||||
r.check(st == 401, "forged token still rejected without Redis")
|
||||
finally:
|
||||
sh(args.start_redis)
|
||||
|
||||
print("== 2. PostgreSQL недоступен ==")
|
||||
sh(args.stop_db)
|
||||
try:
|
||||
time.sleep(1)
|
||||
st, _, _ = api.call("GET", path, token=user["token"])
|
||||
r.check(st == 503, f"history without DB -> 503, not a hang (got {st})")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token="forged-" + uuid.uuid4().hex)
|
||||
r.check(st in (401, 503), f"unknown token is never trusted without DB (got {st})")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me")
|
||||
r.check(st == 401, "anonymous request -> 401")
|
||||
st = api.raw("GET", "/health/ready")[0]
|
||||
r.check(st == 503, "/health/ready -> 503")
|
||||
st = api.raw("GET", "/health/live")[0]
|
||||
r.check(st == 200, "/health/live -> 200 (process is alive)")
|
||||
finally:
|
||||
sh(args.start_db)
|
||||
|
||||
print("== 3. восстановление ==")
|
||||
r.check(wait_ready(api), "/health/ready back to 200")
|
||||
st, page, _ = api.call("GET", path, token=user["token"])
|
||||
texts = [m["text"] for m in (page or {}).get("items", [])]
|
||||
r.check(st == 200 and "before outage" in texts and "without redis" in texts,
|
||||
"same token reads the same history after DB is back")
|
||||
r.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Конкурентная запись: 10 клиентов параллельно отправляют по 10 сообщений.
|
||||
Ожидаем ровно 100 уникальных сообщений в истории.
|
||||
python student-tests/race.py --base-url http://localhost:8080
|
||||
"""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from common import Api
|
||||
|
||||
CLIENTS, PER_CLIENT = 10, 10
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
api = Api(ap.parse_args().base_url)
|
||||
user = api.new_user("race")
|
||||
st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "race", "member_ids": [user["id"]]}, token=user["token"])
|
||||
mpath = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
def worker(w):
|
||||
return [api.call("POST", mpath, {"text": f"c{w}-m{i}"}, token=user["token"])[0] for i in range(PER_CLIENT)]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=CLIENTS) as pool:
|
||||
codes = [c for batch in pool.map(worker, range(CLIENTS)) for c in batch]
|
||||
|
||||
ids, texts, cursor = [], [], None
|
||||
while True:
|
||||
st, page, _ = api.call("GET", f"{mpath}?limit=50" + (f"&cursor={cursor}" if cursor else ""), token=user["token"])
|
||||
ids += [m["id"] for m in page["items"]]
|
||||
texts += [m["text"] for m in page["items"]]
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
expected = {f"c{w}-m{i}" for w in range(CLIENTS) for i in range(PER_CLIENT)}
|
||||
ok = codes.count(201) == 100 and len(ids) == 100 and len(set(ids)) == 100 and set(texts) == expected
|
||||
print(f"sent=100 accepted={codes.count(201)} received={len(ids)} unique_ids={len(set(ids))} "
|
||||
f"all_texts_present={set(texts) == expected}")
|
||||
print("PASS" if ok else "FAIL")
|
||||
raise SystemExit(0 if ok else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,52 @@
|
||||
"""
|
||||
Rollback составной операции «создать чат + участников» (уровень «4»).
|
||||
|
||||
Создаём чат, где последний участник — несуществующий пользователь. Проверку
|
||||
приложения нарочно обходим и вызываем запись напрямую: первый INSERT в chats
|
||||
проходит, а вставка участника падает на внешнем ключе. Ожидаем, что транзакция
|
||||
откатилась целиком: ни чата, ни участников в базе нет.
|
||||
|
||||
Запуск внутри контейнера API (у него есть доступ к БД и коду):
|
||||
docker compose cp student-tests/rollback_check.py api:/tmp/rollback_check.py
|
||||
docker compose exec api python /tmp/rollback_check.py
|
||||
Локально без Docker: python student-tests/rollback_check.py
|
||||
"""
|
||||
import asyncio
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path.cwd()))
|
||||
import psycopg # noqa: E402
|
||||
|
||||
from app import repo # noqa: E402
|
||||
from app.config import settings # noqa: E402
|
||||
|
||||
|
||||
async def main() -> int:
|
||||
title = "rollback-" + uuid.uuid4().hex[:8]
|
||||
async with await psycopg.AsyncConnection.connect(settings.database_url) as conn:
|
||||
creator = await repo.create_user(conn, "rb_" + uuid.uuid4().hex[:10], "rb", "x")
|
||||
await conn.commit()
|
||||
ghost = uuid.uuid4() # такого пользователя нет
|
||||
try:
|
||||
async with conn.transaction():
|
||||
await repo.insert_chat(conn, title, [uuid.UUID(creator["id"]), ghost], creator["id"])
|
||||
print("FAIL - insert unexpectedly succeeded")
|
||||
return 1
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
print(" ok - insert of unknown member failed on foreign key")
|
||||
cur = await conn.execute(
|
||||
"SELECT count(*) FROM chats WHERE title = %s", (title,))
|
||||
chats = (await cur.fetchone())[0]
|
||||
cur = await conn.execute(
|
||||
"SELECT count(*) FROM chat_members m JOIN chats c ON c.id = m.chat_id WHERE c.title = %s", (title,))
|
||||
members = (await cur.fetchone())[0]
|
||||
ok = chats == 0 and members == 0
|
||||
print(f" {'ok ' if ok else 'FAIL'} - after rollback: chats={chats}, members={members} (expected 0, 0)")
|
||||
print("PASS" if ok else "FAIL")
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(asyncio.run(main()))
|
||||
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Собственные тесты lab2 (запуск одной командой):
|
||||
python student-tests/run.py --base-url http://localhost:8080
|
||||
|
||||
Негативные сценарии lab1 на новой аутентификации + проверки уровня «4»:
|
||||
неверный пароль, logout, X-User-Id/Basic не дают доступ, гонка регистрации.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from common import PASSWORD, Api, Report
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
api = Api(ap.parse_args().base_url)
|
||||
r = Report()
|
||||
|
||||
alice, bob, eve = api.new_user("alice"), api.new_user("bob"), api.new_user("eve")
|
||||
st, chat, _ = api.call("POST", "/api/v1/chats",
|
||||
{"title": "own tests", "member_ids": [alice["id"], bob["id"]]}, token=alice["token"])
|
||||
assert st == 201, st
|
||||
mpath = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
print("== аутентификация ==")
|
||||
st, _, rh = api.login(alice["username"], "Wrong-password-123")
|
||||
r.check(st == 401 and rh.get("WWW-Authenticate", "").startswith("Basic"), "wrong password -> 401 + Basic challenge")
|
||||
st, _, _ = api.login("no_such_user_" + uuid.uuid4().hex[:8], PASSWORD)
|
||||
r.check(st == 401, "unknown user -> 401 (same as wrong password)")
|
||||
st, _, rh = api.call("GET", "/api/v1/users/me")
|
||||
r.check(st == 401 and rh.get("WWW-Authenticate", "").startswith("Bearer"), "no token -> 401 + Bearer challenge")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", headers={"X-User-Id": alice["id"]})
|
||||
r.check(st == 401, "X-User-Id alone gives no access")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token="forged-" + uuid.uuid4().hex)
|
||||
r.check(st == 401, "unknown/forged token -> 401")
|
||||
basic = base64.b64encode(f"{alice['username']}:{alice['password']}".encode()).decode()
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", headers={"Authorization": "Basic " + basic})
|
||||
r.check(st == 401, "Basic on business endpoint -> 401")
|
||||
st, me, _ = api.call("GET", "/api/v1/users/me", token=alice["token"], headers={"X-User-Id": eve["id"]})
|
||||
r.check(st == 200 and me["id"] == alice["id"], "X-User-Id cannot override bearer identity")
|
||||
st, _, _ = api.call("POST", "/api/v1/users", {"username": "short_pw_" + uuid.uuid4().hex[:6],
|
||||
"display_name": "x", "password": "short"})
|
||||
r.check(st == 400, "password shorter than 12 -> 400")
|
||||
|
||||
print("== logout ==")
|
||||
tmp = api.new_user("logout")
|
||||
st, _, _ = api.call("DELETE", "/api/v1/auth/sessions/current", token=tmp["token"])
|
||||
r.check(st == 204, "logout -> 204")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token=tmp["token"])
|
||||
r.check(st == 401, "token after logout -> 401")
|
||||
st, _, _ = api.call("DELETE", "/api/v1/auth/sessions/current", token=tmp["token"])
|
||||
r.check(st == 401, "second logout -> 401")
|
||||
|
||||
print("== гонка регистрации одного username ==")
|
||||
name = "race_" + uuid.uuid4().hex[:10]
|
||||
|
||||
def reg(_):
|
||||
st, _, _ = api.call("POST", "/api/v1/users", {"username": name, "display_name": "r", "password": PASSWORD})
|
||||
return st
|
||||
|
||||
with ThreadPoolExecutor(max_workers=20) as pool:
|
||||
codes = list(pool.map(reg, range(20)))
|
||||
r.check(codes.count(201) == 1 and codes.count(409) == 19,
|
||||
f"20 parallel registrations -> one 201, nineteen 409 (got {sorted(codes)})")
|
||||
|
||||
print("== ошибки и доступ (из lab1) ==")
|
||||
st, _, _ = api.raw("POST", "/api/v1/users", b"{not json", {"Content-Type": "application/json"})
|
||||
r.check(st == 400, "malformed JSON -> 400")
|
||||
st, _, _ = api.call("POST", "/api/v1/users", {"username": alice["username"], "display_name": "d", "password": PASSWORD})
|
||||
r.check(st == 409, "duplicate username -> 409")
|
||||
st, _, _ = api.call("POST", mpath, {"text": " "}, token=alice["token"])
|
||||
r.check(st == 400, "blank message -> 400")
|
||||
st, _, _ = api.call("POST", mpath, {"text": "x", "sender_id": eve["id"]}, token=alice["token"])
|
||||
r.check(st == 400, "sender_id in body is rejected")
|
||||
st, _, _ = api.call("POST", mpath, {"text": "чужое"}, token=eve["token"])
|
||||
r.check(st == 404, "outsider POST to foreign chat -> 404")
|
||||
st, _, _ = api.call("GET", mpath, token=eve["token"])
|
||||
r.check(st == 404, "outsider GET foreign history -> 404")
|
||||
st, _, _ = api.call("GET", "/api/v1/chats/not-a-uuid", token=alice["token"])
|
||||
r.check(st == 400, "invalid chat uuid -> 400")
|
||||
|
||||
print("== пагинация ==")
|
||||
for i in range(5):
|
||||
api.call("POST", mpath, {"text": f"m{i}"}, token=bob["token"])
|
||||
seen, cursor, pages = [], None, 0
|
||||
while pages < 10:
|
||||
st, page, _ = api.call("GET", f"{mpath}?limit=2" + (f"&cursor={cursor}" if cursor else ""), token=alice["token"])
|
||||
pages += 1
|
||||
seen += [m["id"] for m in page["items"]]
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
r.check(len(seen) == 5 and len(set(seen)) == 5 and pages == 3, "5 messages / limit 2 -> 3 pages, no duplicates")
|
||||
st, other, _ = api.call("POST", "/api/v1/chats", {"title": "other", "member_ids": [alice["id"]]}, token=alice["token"])
|
||||
st, p, _ = api.call("GET", f"{mpath}?limit=1", token=alice["token"])
|
||||
st, _, _ = api.call("GET", f"/api/v1/chats/{other['id']}/messages?cursor={p['next_cursor']}", token=alice["token"])
|
||||
r.check(st == 400, "cursor from another chat -> 400")
|
||||
|
||||
r.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user