Files
mtusi2026lab4/student-tests/test_api.py
T
Mikhail Verkovykh 728e53cc55 Реализовать lab4 на оценку 4: SeaweedFS, вложения и согласованность БД/S3.
Перенесён стенд lab3 (API, Redis-сессии, идемпотентность, HAProxy, реплики API). Добавлены приватный bucket SeaweedFS с отдельным ключом API, загрузка PNG/JPEG с лимитами и полной проверкой, компенсация и reconciler, плавная остановка API, тесты и evidence.
2026-11-06 19:48:37 +03:00

186 lines
5.3 KiB
Python

"""Grade 3/4 API checks: auth, conflict, X-User-Id ignored, logout."""
from __future__ import annotations
import base64
import time
import uuid
from helpers import call, register
def test_username_conflict():
a = register("conflict")
body = dict(a["registration"])
call("POST", "/api/v1/users", 409, body=body)
def test_wrong_password():
a = register("wrongpw")
bad = base64.b64encode(
(a["registration"]["username"] + ":wrong-password-xx").encode()
).decode()
resp = call(
"POST",
"/api/v1/auth/sessions",
401,
headers={"Authorization": "Basic " + bad},
)
assert resp["headers"].get("WWW-Authenticate", "").lower().startswith("basic")
def test_x_user_id_ignored():
a = register("xu")
b = register("xv")
me = call(
"GET",
"/api/v1/users/me",
200,
token=a["token"],
headers={"X-User-Id": b["id"]},
)["json"]
assert me["id"] == a["id"]
def test_basic_on_business_rejected():
a = register("basicbiz")
cred = base64.b64encode(
(a["registration"]["username"] + ":" + a["registration"]["password"]).encode()
).decode()
call(
"GET",
"/api/v1/users/me",
401,
headers={"Authorization": "Basic " + cred},
)
def test_logout_revokes():
a = register("logout")
call("DELETE", "/api/v1/auth/sessions/current", 204, token=a["token"])
call("GET", "/api/v1/users/me", 401, token=a["token"])
def test_chat_requires_caller_member():
a = register("owner")
b = register("peer")
call(
"POST",
"/api/v1/chats",
400,
token=a["token"],
body={"title": "no me", "member_ids": [b["id"]]},
)
def test_unknown_member_rolls_back():
a = register("atom")
fake = str(uuid.uuid4())
call(
"POST",
"/api/v1/chats",
400,
token=a["token"],
body={"title": "bad", "member_ids": [a["id"], fake]},
)
def test_whitespace_only_password_rejected():
# Maintainer remark: required strings must not be whitespace-only.
body = {
"username": "ws_" + uuid.uuid4().hex[:10],
"display_name": "Spaces",
"password": " " * 12,
}
call("POST", "/api/v1/users", 400, body=body)
def test_username_trailing_newline_400():
# The pattern must match the whole value: "name\n" is not a valid username.
for username in ("review123\n", "review123\r\n", "\nreview123"):
resp = call("POST", "/api/v1/users", 400,
body={"username": username, "display_name": "x", "password": "T3st-" + uuid.uuid4().hex})
assert resp["json"]["error"]["code"] == "invalid_request", repr(username)
def test_malformed_cursor_400():
a = register("cursor")
chat = call("POST", "/api/v1/chats", 201, token=a["token"], body={"title": "c", "member_ids": [a["id"]]})["json"]
def b64(raw: str) -> str:
return base64.urlsafe_b64encode(raw.encode()).decode()
bad = ["not-base64!!", b64("messages|not-a-date|" + str(uuid.uuid4())),
b64("messages|2026-01-01T00:00:00Z|not-a-uuid"), b64("chats|2026-01-01T00:00:00Z|" + str(uuid.uuid4()))]
for cursor in bad:
call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor={cursor}", 400, token=a["token"])
for cursor in bad[:3]:
call("GET", f"/api/v1/chats?cursor={cursor}", 400, token=a["token"])
def test_nul_in_text_roundtrip():
# U+0000 is valid message text: exact in the response, history and idempotent replay.
a = register("nul")
peer = register("nulb")
chat = call(
"POST",
"/api/v1/chats",
201,
token=a["token"],
body={"title": "nul-chat", "member_ids": [a["id"], peer["id"]]},
)["json"]
text = "abc\u0000def \\0 \\u0000"
key = {"Idempotency-Key": "nul-" + uuid.uuid4().hex}
path = f"/api/v1/chats/{chat['id']}/messages"
first = call("POST", path, 201, token=a["token"], body={"text": text}, headers=key)["json"]
assert first["text"] == text
again = call("POST", path, 201, token=a["token"], body={"text": text}, headers=key)["json"]
assert again == first
items = call("GET", path, 200, token=peer["token"])["json"]["items"]
assert [m["text"] for m in items if m["id"] == first["id"]] == [text]
def test_login_rejects_json_body():
a = register("bodylogin")
cred = base64.b64encode(
(a["registration"]["username"] + ":" + a["registration"]["password"]).encode()
).decode()
call(
"POST",
"/api/v1/auth/sessions",
400,
body={"unexpected": True},
headers={"Authorization": "Basic " + cred},
)
def test_invalid_basic_encoding_is_401():
# Maintainer remark: malformed Basic must be 401, not 500.
call(
"POST",
"/api/v1/auth/sessions",
401,
headers={"Authorization": "Basic " + base64.b64encode("é".encode()).decode()},
)
def test_unsupported_media_type():
a = register("ctype")
peer = register("ctypeb")
chat = call(
"POST",
"/api/v1/chats",
201,
token=a["token"],
body={"title": "ctype", "member_ids": [a["id"], peer["id"]]},
)["json"]
raw = b'{"text":"x"}'
call(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
415,
token=a["token"],
raw=raw,
headers={"Content-Type": "text/plain"},
)