Files
mtusi2026lab3/student-tests/test_api.py
T

247 lines
11 KiB
Python

import base64
import datetime as dt
import uuid
from common import PASSWORD, basic, call, check, login, new_chat, new_key, new_user, read_history, run_tests, send
def parse_time(value):
return dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
def test_duplicate_username():
body = {"username": "dup_" + uuid.uuid4().hex[:10], "display_name": "First user", "password": PASSWORD}
call("POST", "/api/v1/users", 201, body=body)
call("POST", "/api/v1/users", 409, body=dict(body, display_name="Second user"))
print("PASS: duplicate username returns 409")
def test_invalid_json():
alice = new_user("alice")
chat = new_chat(alice)
call("POST", "/api/v1/users", 400, raw=b'{"username":')
call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=alice["token"], raw=b"not json",
headers={"Idempotency-Key": new_key()})
print("PASS: invalid JSON returns 400")
def test_wrong_fields():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
call("POST", "/api/v1/users", 400, body={"username": "Bad Name!", "display_name": "x", "password": PASSWORD})
call("POST", "/api/v1/users", 400,
body={"username": "valid_" + uuid.uuid4().hex[:8], "display_name": "x", "password": PASSWORD, "is_admin": True})
# Отправителя нельзя подставить: он берётся из сессии.
call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=alice["token"],
body={"text": "hi", "sender_id": bob["id"]}, headers={"Idempotency-Key": new_key()})
print("PASS: wrong and extra fields return 400")
def test_foreign_chat():
alice, bob, eve = new_user("alice"), new_user("bob"), new_user("eve")
chat = new_chat(alice, bob)
call("GET", f"/api/v1/chats/{chat['id']}", 404, token=eve["token"])
call("GET", f"/api/v1/chats/{chat['id']}/messages", 404, token=eve["token"])
send(eve, chat["id"], "not my chat", expected=404)
# Несуществующий чат выглядит так же, как чужой.
call("GET", f"/api/v1/chats/{uuid.uuid4()}", 404, token=eve["token"])
print("PASS: foreign chat returns 404")
def test_empty_message():
alice = new_user("alice")
chat = new_chat(alice)
for text in ("", " ", "\n\t"):
send(alice, chat["id"], text, expected=400)
send(alice, chat["id"], "я" * 4001, expected=400)
send(alice, chat["id"], "я" * 4000)
print("PASS: empty and too long messages return 400, 4000 chars is ok")
def test_pagination():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob)
sent = [send(alice, chat["id"], f"Message {i}").json["id"] for i in range(7)]
history, pages = read_history(bob, chat["id"], limit=2)
check(pages == 4, f"expected 4 pages, got {pages}")
check([m["id"] for m in history] == sent, "pages overlap, lose or reorder messages")
other = new_chat(alice)
for i in range(3):
send(alice, other["id"], f"Other {i}")
first = call("GET", f"/api/v1/chats/{other['id']}/messages?limit=1", token=alice["token"]).json
call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor={first['next_cursor']}", 400, token=alice["token"])
call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor=broken", 400, token=alice["token"])
print("PASS: pagination works across multiple pages, foreign cursor returns 400")
def test_chat_list_pagination():
alice, bob = new_user("alice"), new_user("bob")
created = [new_chat(alice, bob, title=f"Chat {i}")["id"] for i in range(3)]
seen, cursor = [], None
while True:
query = "?limit=1" + (f"&cursor={cursor}" if cursor else "")
page = call("GET", "/api/v1/chats" + query, token=bob["token"]).json
seen += [chat["id"] for chat in page["items"]]
cursor = page["next_cursor"]
if cursor is None:
break
check(seen == created, "chat list pages are wrong")
print("PASS: chat list pagination")
def test_unicode():
alice, bob = new_user("alice"), new_user("bob")
chat = new_chat(alice, bob, title="Чат 👋")
text = "Привет 👋 你好"
check(send(alice, chat["id"], text).json["text"] == text, "text changed on write")
history, _ = read_history(bob, chat["id"])
check(history[-1]["text"] == text, "text changed on read")
print("PASS: unicode text is stored as is")
def test_nul_character_is_stored():
name, title, text = "A\u0000B", "Chat\u0000title", "hello\u0000world"
body = {"username": "nul_" + uuid.uuid4().hex[:10], "display_name": name, "password": "pass\u0000word-123"}
user = call("POST", "/api/v1/users", 201, body=body).json
check(user["display_name"] == name, "display_name with U+0000 changed")
token = login(body["username"], body["password"]).json["token"]
check(call("GET", "/api/v1/users/me", token=token).json["display_name"] == name, "display_name changed on read")
chat = call("POST", "/api/v1/chats", 201, token=token, body={"title": title, "member_ids": [user["id"]]}).json
check(chat["title"] == title, "title with U+0000 changed")
check(call("GET", f"/api/v1/chats/{chat['id']}", token=token).json["title"] == title, "title changed on read")
sent = call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=token, body={"text": text},
headers={"Idempotency-Key": new_key()}).json
history = call("GET", f"/api/v1/chats/{chat['id']}/messages", token=token).json["items"]
check(sent["text"] == text and history[-1]["text"] == text, "text with U+0000 changed")
login("nul\u0000user", PASSWORD, expected=401)
print("PASS: strings with U+0000 are stored and returned as is")
def test_user_has_no_password():
body = {"username": "np_" + uuid.uuid4().hex[:10], "display_name": "No password", "password": PASSWORD}
user = call("POST", "/api/v1/users", 201, body=body).json
check(set(user) == {"id", "username", "display_name", "created_at"}, f"unexpected fields: {set(user)}")
print("PASS: user response has no password or hash")
def test_password_rules():
def register(password, expected):
body = {"username": "pw_" + uuid.uuid4().hex[:10], "display_name": "Password", "password": password}
call("POST", "/api/v1/users", expected, body=body)
register("x" * 11, 400)
register("x" * 129, 400)
register(" " * 12, 400)
register("x" * 12, 201)
register("я" * 128, 201)
print("PASS: password length 12..128, blank password is rejected")
def test_login_gives_token():
username = "lg_" + uuid.uuid4().hex[:10]
user = call("POST", "/api/v1/users", 201,
body={"username": username, "display_name": "Login", "password": PASSWORD}).json
reply = login(username, PASSWORD)
session = reply.json
check(session["token_type"] == "Bearer", "token_type must be Bearer")
check(session["user"] == user, "session user differs from registered user")
check(len(session["token"]) >= 43, "token is too short")
check(username not in session["token"] and user["id"] not in session["token"], "token is not opaque")
check(reply.headers.get("cache-control") == "no-store", "response with token must not be cached")
left = (parse_time(session["expires_at"]) - dt.datetime.now(dt.timezone.utc)).total_seconds()
check(290 < left <= 3600 + 5, f"unexpected session lifetime: {left:.0f} s")
me = call("GET", "/api/v1/users/me", token=session["token"]).json
check(me == user, "/users/me returned another user")
print("PASS: Basic login returns opaque Bearer token with expiry")
def test_wrong_password():
user = new_user("wp")
wrong = login(user["username"], "Wrong-password-000", expected=401)
unknown = login("nobody_" + uuid.uuid4().hex[:8], PASSWORD, expected=401)
check(wrong.headers["www-authenticate"].lower().startswith("basic"), "login 401 must ask for Basic")
check(wrong.json["error"]["message"] == unknown.json["error"]["message"], "different answers leak usernames")
print("PASS: wrong password and unknown user both return the same 401")
def test_malformed_basic():
no_colon = base64.b64encode(b"just_username").decode()
for header in (None, "Basic", "Basic !!!", "Basic " + no_colon, "Bearer something"):
headers = {} if header is None else {"Authorization": header}
call("POST", "/api/v1/auth/sessions", 401, headers=headers)
print("PASS: malformed Basic header returns 401")
def test_password_with_colon_and_unicode():
password = "пароль:с:двоеточием 👋"
user = new_user("colon", password=password)
call("GET", "/api/v1/users/me", token=user["token"])
print("PASS: password with colon and unicode works")
def test_bearer_required():
user = new_user("br")
for headers in ({}, {"Authorization": basic(user["username"], user["password"])},
{"X-User-Id": user["id"]}, {"Authorization": "Bearer " + "A" * 43},
{"Authorization": "Bearer"}, {"Authorization": "Token " + user["token"]}):
reply = call("GET", "/api/v1/users/me", 401, headers=headers)
check(reply.headers["www-authenticate"].lower().startswith("bearer"), "401 must ask for Bearer")
call("GET", "/api/v1/users/me", 200, headers={"Authorization": "bearer " + user["token"]})
print("PASS: business endpoints need Bearer; Basic and X-User-Id give 401")
def test_x_user_id_ignored():
alice, bob = new_user("alice"), new_user("bob")
me = call("GET", "/api/v1/users/me", token=alice["token"], headers={"X-User-Id": bob["id"]}).json
check(me["id"] == alice["id"], "X-User-Id changed the current user")
print("PASS: X-User-Id does not change the current user")
def test_auth_before_body():
alice = new_user("alice")
chat = new_chat(alice)
call("POST", f"/api/v1/chats/{chat['id']}/messages", 401, raw=b"not json")
call("GET", f"/api/v1/chats/{uuid.uuid4()}", 401)
print("PASS: 401 comes before 400 and 404")
def test_logout():
user = new_user("lo")
second = login(user["username"], user["password"]).json["token"]
call("DELETE", "/api/v1/auth/sessions/current", 204, token=user["token"])
call("GET", "/api/v1/users/me", 401, token=user["token"])
call("DELETE", "/api/v1/auth/sessions/current", 401, token=user["token"])
call("GET", "/api/v1/users/me", 200, token=second) # другая сессия того же пользователя жива
again = login(user["username"], user["password"]).json["token"]
check(again != user["token"], "new login must give a new token")
call("GET", "/api/v1/users/me", 200, token=again)
print("PASS: logout revokes only the current session")
if __name__ == "__main__":
run_tests([
test_duplicate_username,
test_invalid_json,
test_wrong_fields,
test_foreign_chat,
test_empty_message,
test_pagination,
test_chat_list_pagination,
test_unicode,
test_nul_character_is_stored,
test_user_has_no_password,
test_password_rules,
test_login_gives_token,
test_wrong_password,
test_malformed_basic,
test_password_with_colon_and_unicode,
test_bearer_required,
test_x_user_id_ignored,
test_auth_before_body,
test_logout,
])