Files
mtusi2026lab3/student-tests/test_api.py
T
Alexey BodanyukandClaude Opus 5.5 4f6cfda37a chore: перенос решения lab2 (src, миграции, student-tests, Dockerfile, compose, lock) без изменений
Исходная точка lab3: код из solution/bvt2302-bodanyuk лабы 2, коммит ef44e48
(PR mtusi2026/mtusi2026lab2#42 принят). README, COURSE, contracts/ и tests/
преподавателя не тронуты; к Makefile дописан студенческий раздел lab2,
.env.example — версия lab2. Исследование трека 2 lab2 (bench/track2) не переносилось.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:02:13 +03:00

202 lines
11 KiB
Python

"""Contract behaviour over real HTTP (stand must be running). Lab 1 checks moved to Bearer + new lab 2 auth."""
from __future__ import annotations
import base64
import uuid
import pytest
from conftest import PASSWORD, basic
pytestmark = pytest.mark.stack
def key(item: dict) -> tuple[str, int]:
return item["created_at"], uuid.UUID(item["id"]).int
# ================================================================== registration & login
def test_register_never_returns_password_and_login_returns_bearer(api):
actor = api.register("alice", display_name="Алиса 👩‍💻")
assert set(actor["user"]) == {"id", "username", "display_name", "created_at"}
session = api.call("POST", "/api/v1/auth/sessions", 201,
headers={"Authorization": basic(actor["username"], PASSWORD)}, schema="Session").json()
assert session["token_type"] == "Bearer" and len(session["token"]) >= 43
assert actor["username"] not in session["token"] and actor["id"] not in session["token"]
assert api.call("GET", "/api/v1/users/me", 200, token=session["token"], schema="User").json() == actor["user"]
def test_duplicate_username_is_409(api):
actor = api.register("dup")
body = {"username": actor["username"], "display_name": "Другой", "password": PASSWORD}
assert api.call("POST", "/api/v1/users", 409, json_body=body).json()["error"]["code"] == "conflict"
@pytest.mark.parametrize("password", ["short-11ch", " " * 12, " \t \n " * 3, "я" * 129])
def test_bad_password_on_registration_is_400(api, password):
body = {"username": "pw_" + uuid.uuid4().hex[:10], "display_name": "x", "password": password}
api.call("POST", "/api/v1/users", 400, json_body=body)
@pytest.mark.parametrize("password", ["я" * 128, "with:colons:inside", "Twelve chars"])
def test_edge_passwords_register_and_login(api, password):
actor = api.user("edge", password=password)
api.call("GET", "/api/v1/users/me", 200, token=actor["token"])
def test_wrong_password_and_unknown_user_give_the_same_401(api):
actor = api.register("victim")
wrong = api.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic(actor["username"], "Wrong-password-1")})
unknown = api.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic("nobody_" + uuid.uuid4().hex[:8], PASSWORD)})
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
assert wrong.headers["www-authenticate"] == 'Basic realm="messenger", charset="UTF-8"'
@pytest.mark.parametrize("header", ["Basic é", "Basic !!!", "Basic " + base64.b64encode(b"no_colon").decode(),
"Basic " + base64.b64encode(b"\xff\xfe:x").decode(), "Bearer " + "a" * 43, ""])
def test_malformed_basic_is_401_not_500(api, header):
# Raw UTF-8 bytes, as curl would send them (httpx refuses non-ASCII str headers).
api.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": header.encode("utf-8")} if header else {})
def test_logout_revokes_only_this_token(api):
actor = api.user("logout")
second = api.login(actor)
api.call("DELETE", "/api/v1/auth/sessions/current", 204, token=actor["token"])
api.call("GET", "/api/v1/users/me", 401, token=actor["token"])
api.call("DELETE", "/api/v1/auth/sessions/current", 401, token=actor["token"])
api.call("GET", "/api/v1/users/me", 200, token=second) # other session of the same user survives
def test_x_user_id_basic_and_garbage_do_not_authenticate(api):
actor = api.user("hdr")
for headers in ({"X-User-Id": actor["id"]},
{"Authorization": basic(actor["username"], PASSWORD)},
{"Authorization": "Bearer " + "A" * 43},
{"Authorization": "Bearer"}):
api.call("GET", "/api/v1/users/me", 401, headers=headers)
me = api.call("GET", "/api/v1/users/me", 200, token=actor["token"], headers={"X-User-Id": str(uuid.uuid4())})
assert me.json()["id"] == actor["id"]
# ================================================================== validation / errors (from lab 1)
@pytest.mark.parametrize("raw", [b"{", b"", b"[]", b"null", b'{"username": "abc_def", "display_name": NaN, "password": "Twelve-chars"}',
b'{"username": "abc_def", "display_name": "x", "password": "Twelve-chars"}{"a": 1}',
b'{"username": "abc_def", "display_name": "\\ud800", "password": "Twelve-chars"}'])
def test_malformed_json_is_400(api, raw):
api.call("POST", "/api/v1/users", 400, raw=raw, headers={"Content-Type": "application/json"})
@pytest.mark.parametrize("body", [
{"username": "abc_def", "display_name": "x"}, # no password
{"username": "abc_def", "display_name": "x", "password": "Twelve-chars", "extra": 1},
{"username": "Abc_def", "display_name": "x", "password": "Twelve-chars"},
{"username": "abc_def", "display_name": " ", "password": "Twelve-chars"},
{"username": "abc_def", "display_name": "x" * 101, "password": "Twelve-chars"},
{"username": 5, "display_name": "x", "password": "Twelve-chars"},
])
def test_invalid_registration_fields_are_400(api, body):
api.call("POST", "/api/v1/users", 400, json_body=body)
def test_unicode_limits_are_code_points_and_nul_is_stored(api):
actor = api.user("uni", display_name="😀" * 100)
assert actor["user"]["display_name"] == "😀" * 100
nul = api.user("nul", display_name="A\u0000B")
assert api.call("GET", "/api/v1/users/me", 200, token=nul["token"]).json()["display_name"] == "A\u0000B"
chat = api.chat(actor, title="T\u0000itle")
assert chat["title"] == "T\u0000itle"
assert api.send(actor, chat, "hello\u0000world")["text"] == "hello\u0000world"
assert api.send(actor, chat, "🙂" * 4000)["text"] == "🙂" * 4000
api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 400, token=actor["token"], json_body={"text": "я" * 4001})
texts = [m["text"] for m in api.history(actor, chat, 100)[0]]
assert texts == ["hello\u0000world", "🙂" * 4000]
def test_oversized_body_and_wrong_content_type(api):
api.call("POST", "/api/v1/users", 413, json_body={"username": "big_body", "display_name": "x" * 70_000, "password": PASSWORD})
api.call("POST", "/api/v1/users", 400, raw=b'{"username":"abc_def"}', headers={"Content-Type": "text/plain"})
# ================================================================== chats & membership
def test_chat_validation(api):
alice, bob = api.user("alice"), api.user("bob")
for body in ({"title": "x", "member_ids": [alice["id"], bob["id"], bob["id"]]},
{"title": "x", "member_ids": [alice["id"], str(uuid.uuid4())]},
{"title": "x", "member_ids": [bob["id"]]},
{"title": " ", "member_ids": [alice["id"]]},
{"title": "x", "member_ids": [alice["id"], "bob"]}):
api.call("POST", "/api/v1/chats", 400, token=alice["token"], json_body=body)
def test_foreign_chat_is_indistinguishable_from_missing(api):
alice, bob, eve = api.user("alice"), api.user("bob"), api.user("eve")
chat = api.chat(alice, bob)
for chat_id in (chat["id"], str(uuid.uuid4())):
base = f"/api/v1/chats/{chat_id}"
errors = [api.call("GET", base, 404, token=eve["token"]).json(),
api.call("GET", base + "/messages", 404, token=eve["token"]).json(),
api.call("POST", base + "/messages", 404, token=eve["token"], json_body={"text": "чужое"}).json(),
api.call("GET", base + "/messages?cursor=garbage", 404, token=eve["token"]).json()]
assert len({e["error"]["message"] for e in errors}) == 1
api.call("GET", "/api/v1/chats/not-a-uuid", 401)
api.call("GET", "/api/v1/chats/not-a-uuid", 400, token=alice["token"])
api.call("GET", "/api/v1/chats/NOT-A-UUID/messages", 400, token=alice["token"])
def test_chat_list_order_pagination_and_isolation(api):
alice, bob, eve = api.user("alice"), api.user("bob"), api.user("eve")
created = [api.chat(alice, bob, title=f"Чат {i}") for i in range(5)]
api.chat(eve, title="Чат Евы")
walked, cursor = [], None
while True:
query = "?limit=2" + (f"&cursor={cursor}" if cursor else "")
page = api.call("GET", "/api/v1/chats" + query, 200, token=bob["token"], schema="ChatPage").json()
walked += page["items"]
cursor = page["next_cursor"]
if not cursor:
break
assert walked == created
first = api.call("GET", "/api/v1/chats?limit=1", 200, token=alice["token"]).json()["next_cursor"]
api.call("GET", f"/api/v1/chats?limit=1&cursor={first}", 400, token=bob["token"]) # cursor of another user
api.call("GET", "/api/v1/chats?limit=0", 400, token=bob["token"])
# ================================================================== messages & keyset pagination
def test_history_pages_without_loss_or_duplicates(api):
alice, bob = api.user("alice"), api.user("bob")
chat = api.chat(alice, bob)
sent = [api.send(alice if i % 2 else bob, chat, f"сообщение {i}") for i in range(25)]
items, pages = api.history(bob, chat, 7)
assert pages == 4 and items == sent and items == sorted(items, key=key)
assert sent[0]["sender_id"] == bob["id"] and sent[1]["sender_id"] == alice["id"]
@pytest.mark.parametrize("query", ["limit=0", "limit=101", "limit=abc", "limit=1&limit=2", "cursor=", "cursor=garbage",
"cursor=djF8bXx4fDF8Mg", "cursor=" + base64.urlsafe_b64encode(b"v1|m|x|99999999999999999999|y").decode()])
def test_bad_limit_or_cursor_is_400(api, query):
alice = api.user("alice")
chat = api.chat(alice)
api.call("GET", f"/api/v1/chats/{chat['id']}/messages?{query}", 400, token=alice["token"])
def test_cursor_bound_to_chat(api):
alice = api.user("alice")
a, b = api.chat(alice, title="A"), api.chat(alice, title="B")
for chat in (a, b):
api.send(alice, chat, "1")
api.send(alice, chat, "2")
cursor = api.call("GET", f"/api/v1/chats/{a['id']}/messages?limit=1", 200, token=alice["token"]).json()["next_cursor"]
api.call("GET", f"/api/v1/chats/{b['id']}/messages?cursor={cursor}", 400, token=alice["token"])
empty = api.chat(alice, title="Empty")
api.call("GET", f"/api/v1/chats/{empty['id']}/messages?cursor=garbage", 400, token=alice["token"])
def test_read_after_write(api):
alice, bob = api.user("alice"), api.user("bob")
chat = api.chat(alice, bob)
for i in range(5):
message = api.send(alice, chat, f"m{i}")
last = api.call("GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", 200, token=bob["token"]).json()["items"][-1]
assert last == message