forked from mtusi2026/mtusi2026lab2
64 lines
2.9 KiB
Python
64 lines
2.9 KiB
Python
"""Общие помощники для собственных тестов.
|
||
|
||
Переиспользуем публичный HTTP-клиент курса (tests/client.py), а не пишем свой:
|
||
он уже проверяет X-Request-Id, формат ошибок, WWW-Authenticate и схемы ответов из контракта.
|
||
С lab2 клиент сам регистрирует пользователя с паролем, входит через Basic
|
||
и подставляет Bearer-токен (токен живёт только в памяти теста и не печатается).
|
||
"""
|
||
import base64
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
from pathlib import Path
|
||
from urllib.parse import quote
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
sys.path.insert(0, str(ROOT / "tests"))
|
||
|
||
from client import Client, Failure, check, run # noqa: E402 (импорт после правки sys.path)
|
||
|
||
__all__ = ["Client", "Failure", "check", "run", "read_history", "basic", "login", "compose", "wait_ready", "ROOT"]
|
||
|
||
|
||
def read_history(api, actor, chat_id, limit=100):
|
||
"""Читает всю историю чата по страницам. Возвращает (сообщения, число_страниц)."""
|
||
items, pages, cursor = [], 0, None
|
||
while True:
|
||
query = f"?limit={limit}" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
|
||
page = api.call("GET", f"/api/v1/chats/{chat_id}/messages{query}",
|
||
actor=actor, schema="MessagePage")["json"]
|
||
items += page["items"]
|
||
pages += 1
|
||
cursor = page["next_cursor"]
|
||
if cursor is None:
|
||
return items, pages
|
||
|
||
|
||
def basic(username, password):
|
||
"""Значение заголовка Authorization: Basic base64(username:password), пароль в UTF-8."""
|
||
return "Basic " + base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
|
||
|
||
|
||
def login(api, username, password, expected=201):
|
||
"""POST /auth/sessions; при успехе возвращает тело Session (токен — только в памяти)."""
|
||
schema = "Session" if expected == 201 else None
|
||
return api.call("POST", "/api/v1/auth/sessions", expected,
|
||
headers={"Authorization": basic(username, password)}, schema=schema)["json"]
|
||
|
||
|
||
def compose(*args):
|
||
"""docker compose <args> из корня репозитория; вывод скрыт (там могут быть имена/секреты)."""
|
||
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True,
|
||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||
|
||
|
||
def wait_ready(api, seconds=90):
|
||
deadline = time.monotonic() + seconds
|
||
while True:
|
||
try:
|
||
api.call("GET", "/health/ready", schema="Health")
|
||
return
|
||
except Failure:
|
||
check(time.monotonic() < deadline, f"API не стал готов за {seconds} с")
|
||
time.sleep(0.5)
|