forked from mtusi2026/mtusi2026lab2
lab2
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
import json, time, math, sys, threading, os
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, Failure
|
||||
|
||||
def pct(xs, p):
|
||||
if not xs:
|
||||
return None
|
||||
xs = sorted(xs)
|
||||
return round(1000 * xs[max(0, math.ceil(p * len(xs)) - 1)], 3)
|
||||
|
||||
def main():
|
||||
warmup = int(sys.argv[1])
|
||||
conc = int(sys.argv[2])
|
||||
duration = float(sys.argv[3])
|
||||
mode = sys.argv[4] if len(sys.argv) > 4 else "post"
|
||||
base = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
|
||||
c = Client(base)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
for i in range(warmup):
|
||||
c.message(alice, chat, "w-%d" % i)
|
||||
barrier = threading.Barrier(conc)
|
||||
def worker(wid):
|
||||
local = Client(base, timeout=5)
|
||||
barrier.wait()
|
||||
deadline = time.monotonic() + duration
|
||||
lat, err, n = [], 0, 0
|
||||
while time.monotonic() < deadline:
|
||||
t0 = time.monotonic()
|
||||
try:
|
||||
if mode == "get":
|
||||
local.call(
|
||||
"GET",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages?limit=50",
|
||||
actor=alice,
|
||||
schema="MessagePage",
|
||||
)
|
||||
else:
|
||||
local.message(alice, chat, "b-%s-%s" % (wid, n))
|
||||
lat.append(time.monotonic() - t0)
|
||||
except Failure:
|
||||
err += 1
|
||||
n += 1
|
||||
return lat, err
|
||||
t0 = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=conc) as pool:
|
||||
parts = list(pool.map(worker, range(conc)))
|
||||
elapsed = time.monotonic() - t0
|
||||
lat = [x for a, _ in parts for x in a]
|
||||
err = sum(e for _, e in parts)
|
||||
out = {
|
||||
"warmup_messages": warmup,
|
||||
"concurrency": conc,
|
||||
"duration_s": duration,
|
||||
"elapsed_s": round(elapsed, 3),
|
||||
"ok": len(lat),
|
||||
"err": err,
|
||||
"rps": round(len(lat) / elapsed, 3) if elapsed else None,
|
||||
"p50_ms": pct(lat, 0.50),
|
||||
"p95_ms": pct(lat, 0.95),
|
||||
"p99_ms": pct(lat, 0.99),
|
||||
"mode": mode,
|
||||
}
|
||||
import subprocess
|
||||
|
||||
def rss_from_proc():
|
||||
for ent in os.listdir("/proc"):
|
||||
if not ent.isdigit():
|
||||
continue
|
||||
try:
|
||||
with open("/proc/%s/cmdline" % ent, "rb") as f:
|
||||
cmd = f.read()
|
||||
except OSError:
|
||||
continue
|
||||
if b"messenger" not in cmd:
|
||||
continue
|
||||
try:
|
||||
with open("/proc/%s/status" % ent) as f:
|
||||
for line in f:
|
||||
if line.startswith("VmRSS:"):
|
||||
kb = int(line.split()[1])
|
||||
return "%.2fMiB" % (kb / 1024.0)
|
||||
except (OSError, ValueError, IndexError):
|
||||
continue
|
||||
return None
|
||||
|
||||
mem = rss_from_proc()
|
||||
if not mem:
|
||||
name = os.environ.get("DOCKER_NAME", "mtusi-lab1")
|
||||
for cmd in (
|
||||
["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", name],
|
||||
["sudo", "-n", "docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", name],
|
||||
):
|
||||
try:
|
||||
mem = subprocess.check_output(cmd, text=True).split("/")[0].strip()
|
||||
if mem:
|
||||
break
|
||||
except Exception:
|
||||
mem = None
|
||||
out["mem"] = mem
|
||||
print(json.dumps(out, ensure_ascii=False))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,170 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Собственные проверки контракта lab2 (дополняют публичный tests/smoke.py).
|
||||
|
||||
BASE_URL=http://127.0.0.1:8080 python3 student-tests/test_api.py
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
|
||||
PASSWORD = "Student-test-password-1"
|
||||
|
||||
|
||||
def call(method, path, expected, body=None, token=None, raw=None,
|
||||
content_type="auto", headers=None):
|
||||
h = {"Accept": "application/json"}
|
||||
data = raw
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
elif data is not None and content_type == "auto":
|
||||
h["Content-Type"] = "application/json"
|
||||
elif data is not None and content_type:
|
||||
h["Content-Type"] = content_type
|
||||
if token:
|
||||
h["Authorization"] = "Bearer " + token
|
||||
h.update(headers or {})
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=15)
|
||||
except urllib.error.HTTPError as e:
|
||||
resp = e
|
||||
raw_b = resp.read()
|
||||
assert resp.status == expected, (method, path, resp.status, raw_b[:300])
|
||||
rid = resp.headers.get("X-Request-Id")
|
||||
assert rid, "missing X-Request-Id"
|
||||
payload = json.loads(raw_b) if raw_b else None
|
||||
if resp.status >= 400:
|
||||
assert payload["error"]["request_id"] == rid
|
||||
if resp.status == 401:
|
||||
assert resp.headers.get("WWW-Authenticate"), "401 without WWW-Authenticate"
|
||||
return payload
|
||||
|
||||
|
||||
def unique(prefix):
|
||||
return prefix + "_" + uuid.uuid4().hex[:12]
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
return {"Authorization": "Basic " + base64.b64encode(
|
||||
f"{username}:{password}".encode()).decode()}
|
||||
|
||||
|
||||
def register(prefix, display_name="U"):
|
||||
user = call("POST", "/api/v1/users", 201, {
|
||||
"username": unique(prefix), "display_name": display_name, "password": PASSWORD})
|
||||
user["token"] = call("POST", "/api/v1/auth/sessions", 201,
|
||||
headers=basic(user["username"], PASSWORD))["token"]
|
||||
return user
|
||||
|
||||
|
||||
def test_registration_validation():
|
||||
call("POST", "/api/v1/users", 400, raw=b"{not json")
|
||||
call("POST", "/api/v1/users", 400, raw=b'{"username":"x"')
|
||||
call("POST", "/api/v1/users", 415, raw=b'{"username":"aa1"}', content_type="text/plain")
|
||||
call("POST", "/api/v1/users", 400,
|
||||
{"username": unique("n"), "display_name": 1, "password": PASSWORD})
|
||||
call("POST", "/api/v1/users", 400,
|
||||
{"username": unique("n"), "display_name": "я" * 101, "password": PASSWORD})
|
||||
call("POST", "/api/v1/users", 400,
|
||||
{"username": unique("n"), "display_name": "N", "password": "short"})
|
||||
call("POST", "/api/v1/users", 400,
|
||||
{"username": unique("n"), "display_name": "N"})
|
||||
call("POST", "/api/v1/users", 400,
|
||||
{"username": unique("n"), "display_name": "N", "password": PASSWORD, "extra": 1})
|
||||
name = unique("dup")
|
||||
body = {"username": name, "display_name": "Same", "password": PASSWORD}
|
||||
user = call("POST", "/api/v1/users", 201, body)
|
||||
assert "password" not in user and "password_hash" not in user
|
||||
call("POST", "/api/v1/users", 409, body)
|
||||
|
||||
|
||||
def test_auth_transitions():
|
||||
a = register("a", 'Alice "цитата"')
|
||||
assert a["display_name"] == 'Alice "цитата"'
|
||||
call("GET", "/api/v1/users/me", 401)
|
||||
call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": a["id"]})
|
||||
call("GET", "/api/v1/users/me", 401, headers=basic(a["username"], PASSWORD))
|
||||
call("GET", "/api/v1/users/me", 401, token="not-a-real-token")
|
||||
call("POST", "/api/v1/auth/sessions", 401)
|
||||
call("POST", "/api/v1/auth/sessions", 401, headers=basic(a["username"], "wrong-password-1"))
|
||||
me = call("GET", "/api/v1/users/me", 200, token=a["token"])
|
||||
assert me["id"] == a["id"]
|
||||
|
||||
|
||||
def test_messages_and_access():
|
||||
a, b, eve = register("a"), register("b"), register("e")
|
||||
chat = call("POST", "/api/v1/chats", 201,
|
||||
{"title": "t", "member_ids": [a["id"], b["id"]]}, token=a["token"])
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
call("POST", path, 400, {"text": ""}, token=a["token"])
|
||||
call("POST", path, 400, {"text": " "}, token=a["token"])
|
||||
call("POST", path, 400, {"text": "x" * 4001}, token=a["token"])
|
||||
call("POST", path, 400, {"text": "hi", "sender_id": eve["id"]}, token=a["token"])
|
||||
msg = call("POST", path, 201, {"text": 'раз "два" три'}, token=a["token"])
|
||||
assert msg["text"] == 'раз "два" три' and msg["sender_id"] == a["id"]
|
||||
|
||||
call("GET", "/api/v1/chats/" + chat["id"], 404, token=eve["token"])
|
||||
call("GET", path, 404, token=eve["token"])
|
||||
call("POST", path, 404, {"text": "nope"}, token=eve["token"])
|
||||
call("GET", "/api/v1/chats/not-a-uuid", 400, token=a["token"])
|
||||
|
||||
|
||||
def test_chat_validation():
|
||||
a, b = register("a"), register("b")
|
||||
call("POST", "/api/v1/chats", 400,
|
||||
{"title": "т" * 101, "member_ids": [a["id"], b["id"]]}, token=a["token"])
|
||||
call("POST", "/api/v1/chats", 400,
|
||||
{"title": "no caller", "member_ids": [b["id"]]}, token=a["token"])
|
||||
call("POST", "/api/v1/chats", 400,
|
||||
{"title": "dup", "member_ids": [a["id"], b["id"], b["id"]]}, token=a["token"])
|
||||
call("POST", "/api/v1/chats", 400,
|
||||
{"title": "unknown", "member_ids": [a["id"], str(uuid.uuid4())]}, token=a["token"])
|
||||
|
||||
|
||||
def test_pagination():
|
||||
a, b = register("a"), register("b")
|
||||
chats = [call("POST", "/api/v1/chats", 201,
|
||||
{"title": "chat-%d" % i, "member_ids": [a["id"], b["id"]]}, token=a["token"])
|
||||
for i in range(3)]
|
||||
p1 = call("GET", "/api/v1/chats?limit=1", 200, token=a["token"])
|
||||
assert len(p1["items"]) == 1 and p1["next_cursor"]
|
||||
p2 = call("GET", "/api/v1/chats?limit=1&cursor=" + quote(p1["next_cursor"], safe=""),
|
||||
200, token=a["token"])
|
||||
assert p1["items"][0]["id"] != p2["items"][0]["id"]
|
||||
call("GET", "/api/v1/chats?limit=0", 400, token=a["token"])
|
||||
call("GET", "/api/v1/chats?limit=101", 400, token=a["token"])
|
||||
call("GET", "/api/v1/chats?limit=1&cursor=bad|cursor", 400, token=a["token"])
|
||||
|
||||
path = "/api/v1/chats/" + chats[0]["id"] + "/messages"
|
||||
m1 = call("POST", path, 201, {"text": "one"}, token=a["token"])
|
||||
m2 = call("POST", path, 201, {"text": "two"}, token=b["token"])
|
||||
q1 = call("GET", path + "?limit=1", 200, token=a["token"])
|
||||
assert len(q1["items"]) == 1 and q1["next_cursor"]
|
||||
q2 = call("GET", path + "?limit=1&cursor=" + quote(q1["next_cursor"], safe=""),
|
||||
200, token=a["token"])
|
||||
assert len(q2["items"]) == 1 and q2["next_cursor"] is None
|
||||
assert {q1["items"][0]["id"], q2["items"][0]["id"]} == {m1["id"], m2["id"]}
|
||||
call("GET", path + "?limit=0", 400, token=a["token"])
|
||||
other = "/api/v1/chats/" + chats[1]["id"] + "/messages"
|
||||
call("GET", other + "?cursor=" + quote(q1["next_cursor"], safe=""), 400, token=a["token"])
|
||||
|
||||
|
||||
def test_logout():
|
||||
a = register("lo")
|
||||
call("DELETE", "/api/v1/auth/sessions/current", 204, token=a["token"])
|
||||
call("GET", "/api/v1/users/me", 401, token=a["token"])
|
||||
call("DELETE", "/api/v1/auth/sessions/current", 401, token=a["token"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
for test in (test_registration_validation, test_auth_transitions, test_messages_and_access,
|
||||
test_chat_validation, test_pagination, test_logout):
|
||||
test()
|
||||
print("ok", test.__name__)
|
||||
print("PASS student-tests")
|
||||
Reference in New Issue
Block a user