Files
mtusi2026lab6-fork/student-tests/lab5_probe.py
T
2026-11-19 18:40:32 +03:00

147 lines
5.7 KiB
Python

#!/usr/bin/env python3
"""Синтетические проверки lab5. Токен хранится во временном файле и не печатается."""
import argparse, base64, hashlib, json, os, sys, time, uuid
import requests
BASE = os.environ.get("BASE_URL", "http://localhost:8080")
SESS = "/tmp/lab5_session.json"
FIXTURE = "tests/fixtures/sample.png"
def save(d):
with open(SESS, "w") as f:
json.dump(d, f)
def load():
with open(SESS) as f:
return json.load(f)
def hdr(s):
return {"Authorization": "Bearer " + s["token"]}
def cmd_new(_):
u = "p" + uuid.uuid4().hex[:12]
p = "CorrectHorseBattery1"
r = requests.post(BASE + "/api/v1/users",
json={"username": u, "display_name": "Probe", "password": p}, timeout=15)
r.raise_for_status()
uid = r.json()["id"]
basic = base64.b64encode(f"{u}:{p}".encode()).decode()
r = requests.post(BASE + "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + basic}, timeout=15)
r.raise_for_status()
token = r.json()["token"]
r = requests.post(BASE + "/api/v1/chats", headers=hdr({"token": token}),
json={"title": "probe", "member_ids": [uid]}, timeout=15)
r.raise_for_status()
save({"token": token, "user_id": uid, "chat_id": r.json()["id"]})
print(json.dumps({"user_id": uid, "chat_id": r.json()["id"]}, indent=2))
def cmd_upload(a):
s = load()
data = open(a.file or FIXTURE, "rb").read()
r = requests.post(f"{BASE}/api/v1/chats/{s['chat_id']}/attachments",
params={"filename": os.path.basename(a.file or FIXTURE)},
headers={**hdr(s), "Content-Type": "image/png"}, data=data, timeout=60)
out = {"http_status": r.status_code, "attachment": r.json(),
"original_sha256": hashlib.sha256(data).hexdigest()}
if r.status_code == 202:
s["attachment_id"] = r.json()["id"]
s["original_sha256"] = out["original_sha256"]
save(s)
print(json.dumps(out, indent=2))
def cmd_wait(a):
s = load()
aid = a.id or s["attachment_id"]
deadline = time.time() + a.timeout
last = None
while time.time() < deadline:
r = requests.get(f"{BASE}/api/v1/attachments/{aid}", headers=hdr(s), timeout=15)
r.raise_for_status()
last = r.json()
if last["status"] in ("ready", "failed"):
print(json.dumps({"elapsed_note": "terminal", "attachment": last}, indent=2))
return 0 if last["status"] == "ready" else 1
time.sleep(1)
print(json.dumps({"elapsed_note": "timeout", "attachment": last}, indent=2))
return 1
def cmd_fetch(a):
s = load()
aid = a.id or s["attachment_id"]
params = {"variant": a.variant} if a.variant else {}
r = requests.get(f"{BASE}/api/v1/attachments/{aid}/content",
headers=hdr(s), params=params, timeout=60)
print(json.dumps({
"http_status": r.status_code,
"content_type": r.headers.get("Content-Type"),
"content_length_header": r.headers.get("Content-Length"),
"bytes": len(r.content),
"sha256": hashlib.sha256(r.content).hexdigest(),
}, indent=2))
return 0 if r.status_code == 200 else 1
def cmd_send(a):
s = load()
aid = a.id or s["attachment_id"]
r = requests.post(f"{BASE}/api/v1/chats/{s['chat_id']}/messages",
headers={**hdr(s), "Content-Type": "application/json",
"Idempotency-Key": uuid.uuid4().hex},
json={"text": a.text, "attachment_ids": [aid]}, timeout=30)
print(json.dumps({"http_status": r.status_code, "message": r.json()}, indent=2))
return 0 if r.status_code == 201 else 1
def cmd_parallel(a):
import concurrent.futures as cf
s = load()
data = open(FIXTURE, "rb").read()
def one(i):
r = requests.post(f"{BASE}/api/v1/chats/{s['chat_id']}/attachments",
params={"filename": f"par{i}.png"},
headers={**hdr(s), "Content-Type": "image/png"}, data=data, timeout=60)
return r.status_code, r.json().get("id")
t0 = time.time()
with cf.ThreadPoolExecutor(max_workers=a.n) as ex:
res = list(ex.map(one, range(a.n)))
ids = [x[1] for x in res if x[0] == 202]
ready = 0
deadline = time.time() + a.timeout
while time.time() < deadline and ready < len(ids):
ready = 0
for aid in ids:
rr = requests.get(f"{BASE}/api/v1/attachments/{aid}", headers=hdr(s), timeout=15)
if rr.json().get("status") == "ready":
ready += 1
if ready < len(ids):
time.sleep(2)
print(json.dumps({"submitted": a.n, "accepted_202": len(ids),
"ready": ready, "wall_seconds": round(time.time() - t0, 2)}, indent=2))
return 0 if ready == len(ids) else 1
def main():
ap = argparse.ArgumentParser()
sub = ap.add_subparsers(dest="cmd", required=True)
sub.add_parser("new").set_defaults(fn=cmd_new)
p = sub.add_parser("upload"); p.add_argument("--file"); p.set_defaults(fn=cmd_upload)
p = sub.add_parser("wait"); p.add_argument("--id"); p.add_argument("--timeout", type=int, default=90); p.set_defaults(fn=cmd_wait)
p = sub.add_parser("fetch"); p.add_argument("--id"); p.add_argument("--variant"); p.set_defaults(fn=cmd_fetch)
p = sub.add_parser("send"); p.add_argument("--id"); p.add_argument("--text", default=""); p.set_defaults(fn=cmd_send)
p = sub.add_parser("parallel"); p.add_argument("-n", type=int, default=10); p.add_argument("--timeout", type=int, default=180); p.set_defaults(fn=cmd_parallel)
a = ap.parse_args()
sys.exit(a.fn(a) or 0)
if __name__ == "__main__":
main()