78 lines
2.5 KiB
Python
78 lines
2.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Заполняет чат 10 000 сообщениями через urllib (httpx не работает через docker-proxy на Windows)."""
|
|
import json
|
|
import base64
|
|
import uuid
|
|
import urllib.request
|
|
import urllib.error
|
|
|
|
BASE = "http://127.0.0.1:8080"
|
|
PASSWORD = "Example-only-not-a-real-secret-123"
|
|
|
|
|
|
def call(method, path, body=None, token=None, raw_body=None, content_type=None):
|
|
h = {"Accept": "application/json"}
|
|
if token:
|
|
h["Authorization"] = f"Bearer {token}"
|
|
data = None
|
|
if raw_body is not None:
|
|
data = raw_body
|
|
h["Content-Type"] = content_type or "application/json"
|
|
elif body is not None:
|
|
data = json.dumps(body).encode("utf-8")
|
|
h["Content-Type"] = "application/json"
|
|
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=60) as r:
|
|
payload = r.read()
|
|
return r.status, (json.loads(payload) if payload else None)
|
|
except urllib.error.HTTPError as e:
|
|
payload = e.read()
|
|
try:
|
|
return e.code, (json.loads(payload) if payload else None)
|
|
except ValueError:
|
|
return e.code, None
|
|
|
|
|
|
def main():
|
|
name = f"seeder_{uuid.uuid4().hex[:6]}"
|
|
|
|
# 1) пользователь
|
|
s, u = call("POST", "/api/v1/users",
|
|
{"username": name, "display_name": name, "password": PASSWORD})
|
|
assert s == 201, f"create user: {s} {u}"
|
|
|
|
# 2) сессия через Basic
|
|
cred = base64.b64encode(f"{name}:{PASSWORD}".encode()).decode()
|
|
req = urllib.request.Request(
|
|
BASE + "/api/v1/auth/sessions",
|
|
method="POST",
|
|
headers={"Authorization": f"Basic {cred}", "Accept": "application/json"},
|
|
)
|
|
with urllib.request.urlopen(req, timeout=30) as r:
|
|
session = json.loads(r.read())
|
|
token = session["token"]
|
|
|
|
# 3) чат
|
|
s, chat = call("POST", "/api/v1/chats",
|
|
{"title": "seed", "member_ids": [u["id"]]}, token=token)
|
|
assert s == 201, f"create chat: {s} {chat}"
|
|
cid = chat["id"]
|
|
print("chat_id =", cid, flush=True)
|
|
|
|
# 4) 10 000 сообщений
|
|
for i in range(10000):
|
|
s, _ = call("POST", f"/api/v1/chats/{cid}/messages",
|
|
{"text": f"m{i}"}, token=token)
|
|
if s != 201:
|
|
print(f"failed at {i}: {s}")
|
|
break
|
|
if (i + 1) % 1000 == 0:
|
|
print(f" {i + 1}/10000", flush=True)
|
|
|
|
print("DONE")
|
|
print("chat_id =", cid)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |