forked from mtusi2026/mtusi2026lab4
Реализация лабораторной работы 4 на 4
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
"""Общие проверки для собственных black-box тестов"""
|
||||
|
||||
import base64
|
||||
import subprocess
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
USER_FIELDS = ("id", "username", "display_name", "created_at")
|
||||
|
||||
|
||||
def unique_username(label: str) -> str:
|
||||
return f"st_{label}_{uuid.uuid4().hex[:12]}"
|
||||
|
||||
|
||||
def unique_password() -> str:
|
||||
return f"Pw-{uuid.uuid4().hex}"
|
||||
|
||||
|
||||
def basic(username: str, password: str) -> dict[str, str]:
|
||||
"""Authorization: Basic; пароль кодируется в UTF-8"""
|
||||
raw = f"{username}:{password}".encode()
|
||||
return {"Authorization": "Basic " + base64.b64encode(raw).decode()}
|
||||
|
||||
|
||||
def auth(user: dict) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {user['token']}"}
|
||||
|
||||
|
||||
def message_headers(user: dict, key: str | None = None) -> dict[str, str]:
|
||||
"""Bearer и Idempotency-Key (новый, если не задан)"""
|
||||
return {**auth(user), "Idempotency-Key": key or uuid.uuid4().hex}
|
||||
|
||||
|
||||
def public_user(user: dict) -> dict:
|
||||
"""User из ответа API без тестовых полей token/password"""
|
||||
return {field: user[field] for field in USER_FIELDS}
|
||||
|
||||
|
||||
def assert_error(response: httpx.Response, status: int, code: str) -> None:
|
||||
"""Код ответа и единый формат ошибки: request_id совпадает с заголовком"""
|
||||
assert response.status_code == status, response.text
|
||||
assert response.headers["content-type"].startswith("application/json")
|
||||
error = response.json()["error"]
|
||||
assert error["code"] == code
|
||||
assert error["message"]
|
||||
assert error["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
def assert_unauthorized(response: httpx.Response, scheme: str = "Bearer") -> None:
|
||||
"""401 с challenge нужной схемы"""
|
||||
assert_error(response, 401, "unauthorized")
|
||||
assert response.headers["WWW-Authenticate"].startswith(scheme)
|
||||
|
||||
|
||||
def read_all_messages(
|
||||
api: httpx.Client, user: dict, chat_id: str, limit: int
|
||||
) -> tuple[list[dict], int]:
|
||||
"""Обход истории по next_cursor; возвращает сообщения и число страниц"""
|
||||
items: list[dict] = []
|
||||
pages = 0
|
||||
params: dict[str, str | int] = {"limit": limit}
|
||||
while True:
|
||||
response = api.get(
|
||||
f"/api/v1/chats/{chat_id}/messages", params=params, headers=auth(user)
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
page = response.json()
|
||||
items.extend(page["items"])
|
||||
pages += 1
|
||||
if page["next_cursor"] is None:
|
||||
return items, pages
|
||||
params = {"limit": limit, "cursor": page["next_cursor"]}
|
||||
|
||||
|
||||
def compose(*args: str, stdin: str | None = None) -> str:
|
||||
"""docker compose из корня репозитория; вывод не печатается (может быть секретен)"""
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=ROOT,
|
||||
input=stdin,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=120,
|
||||
check=True,
|
||||
)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def psql(sql: str) -> str:
|
||||
"""Запрос в PostgreSQL стенда изнутри контейнера; порт БД наружу не открыт"""
|
||||
return compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"sh",
|
||||
"-c",
|
||||
'psql -X -q -tA -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
|
||||
stdin=sql,
|
||||
).strip()
|
||||
Reference in New Issue
Block a user