forked from mtusi2026/mtusi2026lab3
66 lines
2.5 KiB
Python
66 lines
2.5 KiB
Python
"""Negative and access-control tests (carried over, lab3 keeps them)."""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
|
|
|
|
def _assert_error(response, status, code):
|
|
assert response.status == status, (response.status, response.body)
|
|
payload = response.json
|
|
assert payload["error"]["code"] == code
|
|
assert payload["error"]["request_id"] == response.request_id
|
|
|
|
|
|
def _fresh_actor(client, label="peer"):
|
|
suffix = os.urandom(4).hex()
|
|
username = f"s_{label}_{suffix}"
|
|
password = "T3st-" + os.urandom(8).hex()
|
|
assert client.register(username, password).status == 201
|
|
token = client.login(username, password).json["token"]
|
|
return {"id": client.me(token).json["id"], "token": token}
|
|
|
|
|
|
def test_foreign_chat_is_404(client, alice, chat):
|
|
stranger = _fresh_actor(client, "stranger")
|
|
assert client.request("GET", f"/api/v1/chats/{chat['id']}", token=stranger["token"]).status == 404
|
|
_assert_error(client.send(stranger["token"], chat["id"], "чужое"), 404, "not_found")
|
|
_assert_error(client.list_messages(stranger["token"], chat["id"]), 404, "not_found")
|
|
|
|
|
|
def test_empty_message_is_400(client, alice, chat):
|
|
for text in ("", " ", "\t\n"):
|
|
_assert_error(client.send(alice["token"], chat["id"], text), 400, "invalid_request")
|
|
|
|
|
|
def test_oversized_message_is_400(client, alice, chat):
|
|
_assert_error(client.send(alice["token"], chat["id"], "x" * 4001), 400, "invalid_request")
|
|
|
|
|
|
def test_limit_out_of_range_is_400(client, alice, chat):
|
|
_assert_error(client.list_messages(alice["token"], chat["id"], limit=0), 400, "invalid_request")
|
|
_assert_error(client.list_messages(alice["token"], chat["id"], limit=101), 400, "invalid_request")
|
|
|
|
|
|
def test_sender_id_in_body_is_rejected(client, alice, bob, chat):
|
|
response = client.request(
|
|
"POST",
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
body={"text": "привет", "sender_id": bob["id"]},
|
|
token=alice["token"],
|
|
headers={"Idempotency-Key": os.urandom(12).hex()},
|
|
)
|
|
_assert_error(response, 400, "invalid_request")
|
|
|
|
|
|
def test_chat_without_caller_is_400(client, bob, alice):
|
|
_assert_error(client.create_chat(bob["token"], [alice["id"]]), 400, "invalid_request")
|
|
|
|
|
|
def test_chat_with_unknown_member_is_400(client, alice):
|
|
unknown = "00000000-0000-4000-8000-000000000000"
|
|
_assert_error(client.create_chat(alice["token"], [alice["id"], unknown]), 400, "invalid_request")
|
|
|
|
|
|
def test_chat_with_duplicate_members_is_400(client, alice):
|
|
_assert_error(client.create_chat(alice["token"], [alice["id"], alice["id"]]), 400, "invalid_request")
|