Files
mtusi2026lab5/student-tests/run.py
T

126 lines
6.8 KiB
Python

#!/usr/bin/env python3
"""
Собственные тесты lab2 (запуск одной командой):
python student-tests/run.py --base-url http://localhost:8080
Негативные сценарии lab1 на новой аутентификации + проверки уровня «4»:
неверный пароль, logout, X-User-Id/Basic не дают доступ, гонка регистрации.
"""
import argparse
import base64
import json
import uuid
from concurrent.futures import ThreadPoolExecutor
from common import PASSWORD, Api, Report
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--base-url", default="http://localhost:8080")
api = Api(ap.parse_args().base_url)
r = Report()
alice, bob, eve = api.new_user("alice"), api.new_user("bob"), api.new_user("eve")
st, chat, _ = api.call("POST", "/api/v1/chats",
{"title": "own tests", "member_ids": [alice["id"], bob["id"]]}, token=alice["token"])
assert st == 201, st
mpath = f"/api/v1/chats/{chat['id']}/messages"
print("== аутентификация ==")
st, _, rh = api.login(alice["username"], "Wrong-password-123")
r.check(st == 401 and rh.get("WWW-Authenticate", "").startswith("Basic"), "wrong password -> 401 + Basic challenge")
st, _, _ = api.login("no_such_user_" + uuid.uuid4().hex[:8], PASSWORD)
r.check(st == 401, "unknown user -> 401 (same as wrong password)")
st, _, rh = api.call("GET", "/api/v1/users/me")
r.check(st == 401 and rh.get("WWW-Authenticate", "").startswith("Bearer"), "no token -> 401 + Bearer challenge")
st, _, _ = api.call("GET", "/api/v1/users/me", headers={"X-User-Id": alice["id"]})
r.check(st == 401, "X-User-Id alone gives no access")
st, _, _ = api.call("GET", "/api/v1/users/me", token="forged-" + uuid.uuid4().hex)
r.check(st == 401, "unknown/forged token -> 401")
basic = base64.b64encode(f"{alice['username']}:{alice['password']}".encode()).decode()
st, _, _ = api.call("GET", "/api/v1/users/me", headers={"Authorization": "Basic " + basic})
r.check(st == 401, "Basic on business endpoint -> 401")
st, me, _ = api.call("GET", "/api/v1/users/me", token=alice["token"], headers={"X-User-Id": eve["id"]})
r.check(st == 200 and me["id"] == alice["id"], "X-User-Id cannot override bearer identity")
st, _, _ = api.call("POST", "/api/v1/users", {"username": "short_pw_" + uuid.uuid4().hex[:6],
"display_name": "x", "password": "short"})
r.check(st == 400, "password shorter than 12 -> 400")
print("== logout ==")
tmp = api.new_user("logout")
st, _, _ = api.call("DELETE", "/api/v1/auth/sessions/current", token=tmp["token"])
r.check(st == 204, "logout -> 204")
st, _, _ = api.call("GET", "/api/v1/users/me", token=tmp["token"])
r.check(st == 401, "token after logout -> 401")
st, _, _ = api.call("DELETE", "/api/v1/auth/sessions/current", token=tmp["token"])
r.check(st == 401, "second logout -> 401")
print("== гонка регистрации одного username ==")
name = "race_" + uuid.uuid4().hex[:10]
def reg(_):
st, _, _ = api.call("POST", "/api/v1/users", {"username": name, "display_name": "r", "password": PASSWORD})
return st
with ThreadPoolExecutor(max_workers=20) as pool:
codes = list(pool.map(reg, range(20)))
r.check(codes.count(201) == 1 and codes.count(409) == 19,
f"20 parallel registrations -> one 201, nineteen 409 (got {sorted(codes)})")
print("== ошибки и доступ (из lab1) ==")
st, _, _ = api.raw("POST", "/api/v1/users", b"{not json", {"Content-Type": "application/json"})
r.check(st == 400, "malformed JSON -> 400")
st, _, _ = api.call("POST", "/api/v1/users", {"username": alice["username"], "display_name": "d", "password": PASSWORD})
r.check(st == 409, "duplicate username -> 409")
for bad in ("review123\n", "review123\r\n", " review123", "Review123", "ab"):
st, _, _ = api.call("POST", "/api/v1/users", {"username": bad, "display_name": "d", "password": PASSWORD})
r.check(st == 400, f"invalid username {bad!r} -> 400, not 500 (got {st})")
st, _, _ = api.call("POST", mpath, {"text": " "}, token=alice["token"])
r.check(st == 400, "blank message -> 400")
st, _, _ = api.call("POST", mpath, {"text": "x", "sender_id": eve["id"]}, token=alice["token"])
r.check(st == 400, "sender_id in body is rejected")
st, _, _ = api.call("POST", mpath, {"text": "чужое"}, token=eve["token"])
r.check(st == 404, "outsider POST to foreign chat -> 404")
st, _, _ = api.call("GET", mpath, token=eve["token"])
r.check(st == 404, "outsider GET foreign history -> 404")
st, _, _ = api.call("GET", "/api/v1/chats/not-a-uuid", token=alice["token"])
r.check(st == 400, "invalid chat uuid -> 400")
print("== пагинация ==")
for i in range(5):
api.call("POST", mpath, {"text": f"m{i}"}, token=bob["token"])
seen, cursor, pages = [], None, 0
while pages < 10:
st, page, _ = api.call("GET", f"{mpath}?limit=2" + (f"&cursor={cursor}" if cursor else ""), token=alice["token"])
pages += 1
seen += [m["id"] for m in page["items"]]
cursor = page["next_cursor"]
if cursor is None:
break
r.check(len(seen) == 5 and len(set(seen)) == 5 and pages == 3, "5 messages / limit 2 -> 3 pages, no duplicates")
st, other, _ = api.call("POST", "/api/v1/chats", {"title": "other", "member_ids": [alice["id"]]}, token=alice["token"])
st, p, _ = api.call("GET", f"{mpath}?limit=1", token=alice["token"])
st, _, _ = api.call("GET", f"/api/v1/chats/{other['id']}/messages?cursor={p['next_cursor']}", token=alice["token"])
r.check(st == 400, "cursor from another chat -> 400")
print("== Content-Type ==")
body = json.dumps({"username": "ct_" + uuid.uuid4().hex[:8], "display_name": "c", "password": PASSWORD}).encode()
st, _, _ = api.raw("POST", "/api/v1/users", body, {"Content-Type": "text/plain"})
r.check(st == 415, f"valid JSON with text/plain -> 415 (got {st})")
st, _, _ = api.raw("POST", mpath, json.dumps({"text": "x"}).encode(),
{"Content-Type": "text/plain", "Authorization": "Bearer " + alice["token"]})
r.check(st == 415, f"message with text/plain -> 415 (got {st})")
st, _, _ = api.raw("POST", "/api/v1/chats", b"{}", {"Content-Type": "text/plain"})
r.check(st == 401, f"text/plain without token -> 401 first (got {st})")
st, _, _ = api.raw("POST", mpath, json.dumps({"text": "utf8"}).encode(),
{"Content-Type": "application/json; charset=utf-8", "Authorization": "Bearer " + alice["token"],
"Idempotency-Key": uuid.uuid4().hex})
r.check(st == 201, f"application/json; charset=utf-8 accepted (got {st})")
r.finish()
if __name__ == "__main__":
main()