88 lines
3.7 KiB
Python
88 lines
3.7 KiB
Python
"""Маленький HTTP-клиент для собственных тестов. Только стандартная библиотека."""
|
|
import base64
|
|
import json
|
|
import os
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
import uuid
|
|
|
|
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
|
|
|
|
|
|
def call(method, path, body=None, user=None, raw=None, headers=None, base_url=None, timeout=15):
|
|
"""Возвращает (код ответа, разобранный JSON или None, заголовки)."""
|
|
request_headers = {"Accept": "application/json"}
|
|
if body is not None:
|
|
raw = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
|
if raw is not None:
|
|
request_headers["Content-Type"] = "application/json"
|
|
if user is not None:
|
|
request_headers["Authorization"] = "Bearer " + user["token"]
|
|
request_headers.update(headers or {})
|
|
request = urllib.request.Request((base_url or BASE_URL) + path, data=raw, headers=request_headers, method=method)
|
|
try:
|
|
response = urllib.request.urlopen(request, timeout=timeout)
|
|
except urllib.error.HTTPError as error:
|
|
response = error
|
|
with response:
|
|
data = response.read()
|
|
return response.status, json.loads(data) if data else None, response.headers
|
|
|
|
|
|
def basic(username, password):
|
|
return {"Authorization": "Basic " + base64.b64encode((username + ":" + password).encode("utf-8")).decode()}
|
|
|
|
|
|
def login(username, password, base_url=None):
|
|
return call("POST", "/api/v1/auth/sessions", headers=basic(username, password), base_url=base_url)
|
|
|
|
|
|
def user_body(**fields):
|
|
"""Корректное тело регистрации со случайным username; поля можно переопределить."""
|
|
body = {"username": "u_" + uuid.uuid4().hex[:12], "display_name": "Тест", "password": "Pw-" + uuid.uuid4().hex}
|
|
body.update(fields)
|
|
return body
|
|
|
|
|
|
def new_user(prefix="t", base_url=None):
|
|
"""Регистрирует синтетического пользователя и сразу входит. В словаре id, username, password и token."""
|
|
body = user_body(username=prefix + "_" + uuid.uuid4().hex[:12], display_name="Тест " + prefix)
|
|
status, user, _ = call("POST", "/api/v1/users", body, base_url=base_url)
|
|
assert status == 201, status
|
|
status, session, _ = login(body["username"], body["password"], base_url=base_url)
|
|
assert status == 201, status
|
|
return {**user, "password": body["password"], "token": session["token"], "user": user}
|
|
|
|
|
|
def new_chat(owner, *others, title="Тестовый чат"):
|
|
member_ids = [owner["id"]] + [other["id"] for other in others]
|
|
status, chat, _ = call("POST", "/api/v1/chats", {"title": title, "member_ids": member_ids}, user=owner)
|
|
assert status == 201, status
|
|
return chat
|
|
|
|
|
|
def new_key():
|
|
return uuid.uuid4().hex
|
|
|
|
|
|
def send(user, chat, text, key=None, **options):
|
|
headers = {"Idempotency-Key": key or new_key()}
|
|
return call("POST", "/api/v1/chats/" + chat["id"] + "/messages", {"text": text}, user=user, headers=headers, **options)
|
|
|
|
|
|
def history(user, chat, limit):
|
|
"""Обходит всю историю чата страницами по limit, возвращает сообщения и размеры страниц."""
|
|
items, sizes, cursor = [], [], None
|
|
while True:
|
|
path = "/api/v1/chats/%s/messages?limit=%d" % (chat["id"], limit)
|
|
if cursor:
|
|
path += "&cursor=" + urllib.parse.quote(cursor, safe="")
|
|
status, page, _ = call("GET", path, user=user)
|
|
assert status == 200, status
|
|
items += page["items"]
|
|
sizes.append(len(page["items"]))
|
|
cursor = page["next_cursor"]
|
|
if cursor is None:
|
|
return items, sizes
|