forked from mtusi2026/mtusi2026lab5
ЛР5: асинхронная обработка вложений (RabbitMQ + worker), transactional outbox, варианты, трек 5.1
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
"""Student tests run against an already-running compose stand.
|
||||
|
||||
Start the stand first (secrets + `docker compose up -d --build`), then:
|
||||
|
||||
.venv\\Scripts\\python -m pytest student-tests -v
|
||||
# or: make test-student PYTHON=.venv/bin/python
|
||||
|
||||
Override the target with BASE_URL (default http://localhost:8080).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080")
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def base_url() -> str:
|
||||
return BASE_URL.rstrip("/")
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def client(base_url):
|
||||
from http_client import Client
|
||||
|
||||
return Client(base_url)
|
||||
|
||||
|
||||
def _register_and_login(client, label: str) -> dict:
|
||||
suffix = os.urandom(4).hex()
|
||||
username = f"s_{label}_{suffix}"
|
||||
password = "T3st-" + os.urandom(8).hex()
|
||||
registered = client.register(username, password, "Студент " + label)
|
||||
assert registered.status == 201, registered.body
|
||||
user = registered.json
|
||||
session = client.login(username, password)
|
||||
assert session.status == 201, session.body
|
||||
payload = session.json
|
||||
return {
|
||||
"id": user["id"],
|
||||
"username": username,
|
||||
"password": password,
|
||||
"user": user,
|
||||
"token": payload["token"],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def alice(client):
|
||||
return _register_and_login(client, "alice")
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def bob(client):
|
||||
return _register_and_login(client, "bob")
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def chat(client, alice, bob):
|
||||
response = client.create_chat(alice["token"], [alice["id"], bob["id"]])
|
||||
assert response.status == 201, response.body
|
||||
return response.json
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Minimal stdlib HTTP client for student black-box tests (no extra deps)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
|
||||
@dataclass
|
||||
class Response:
|
||||
status: int
|
||||
headers: object
|
||||
body: bytes
|
||||
|
||||
@property
|
||||
def json(self):
|
||||
if not self.body:
|
||||
return None
|
||||
return json.loads(self.body.decode("utf-8"))
|
||||
|
||||
@property
|
||||
def content_type(self) -> str:
|
||||
return self.headers.get_content_type()
|
||||
|
||||
@property
|
||||
def request_id(self) -> Optional[str]:
|
||||
return self.headers.get("X-Request-Id")
|
||||
|
||||
@property
|
||||
def instance_id(self) -> Optional[str]:
|
||||
return self.headers.get("X-Instance-Id")
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, base_url: str):
|
||||
self.base = base_url.rstrip("/")
|
||||
|
||||
def request(
|
||||
self,
|
||||
method: str,
|
||||
path: str,
|
||||
body=None,
|
||||
raw: Optional[bytes] = None,
|
||||
token: Optional[str] = None,
|
||||
basic: Optional[str] = None,
|
||||
headers: Optional[dict] = None,
|
||||
) -> Response:
|
||||
data = raw
|
||||
request_headers = {"Accept": "application/json"}
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
request_headers["Content-Type"] = "application/json"
|
||||
if raw is not None:
|
||||
request_headers.setdefault("Content-Type", "application/json")
|
||||
if token is not None:
|
||||
request_headers["Authorization"] = "Bearer " + token
|
||||
if basic is not None:
|
||||
request_headers["Authorization"] = "Basic " + basic
|
||||
if headers:
|
||||
request_headers.update(headers)
|
||||
request = urllib.request.Request(
|
||||
self.base + path, data=data, headers=request_headers, method=method
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=15) as response:
|
||||
return Response(response.status, response.headers, response.read())
|
||||
except urllib.error.HTTPError as error:
|
||||
return Response(error.code, error.headers, error.read())
|
||||
|
||||
# -- convenience --------------------------------------------------------
|
||||
def register(self, username: str, password: str, display_name: str = "Студент") -> Response:
|
||||
return self.request(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
body={"username": username, "display_name": display_name, "password": password},
|
||||
)
|
||||
|
||||
def login(self, username: str, password: str) -> Response:
|
||||
credential = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode()
|
||||
return self.request("POST", "/api/v1/auth/sessions", basic=credential)
|
||||
|
||||
def me(self, token: str) -> Response:
|
||||
return self.request("GET", "/api/v1/users/me", token=token)
|
||||
|
||||
def create_chat(self, token: str, member_ids, title: str = "Чат") -> Response:
|
||||
return self.request(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
body={"title": title, "member_ids": list(member_ids)},
|
||||
token=token,
|
||||
)
|
||||
|
||||
def send(
|
||||
self,
|
||||
token: str,
|
||||
chat_id: str,
|
||||
text: str,
|
||||
key: Optional[str] = None,
|
||||
headers: Optional[dict] = None,
|
||||
attachments=None,
|
||||
) -> Response:
|
||||
# lab3 requires an Idempotency-Key on every message POST.
|
||||
request_headers = dict(headers or {})
|
||||
request_headers.setdefault("Idempotency-Key", key or os.urandom(16).hex())
|
||||
body = {"text": text}
|
||||
if attachments is not None:
|
||||
body["attachment_ids"] = list(attachments)
|
||||
return self.request(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
body=body,
|
||||
token=token,
|
||||
headers=request_headers,
|
||||
)
|
||||
|
||||
def upload_attachment(self, token: str, chat_id: str, content: bytes, filename: str = "sample.png",
|
||||
content_type: str = "image/png") -> Response:
|
||||
return self.request(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat_id}/attachments?filename={filename}",
|
||||
raw=content,
|
||||
token=token,
|
||||
headers={"Content-Type": content_type},
|
||||
)
|
||||
|
||||
def get_attachment(self, token: str, attachment_id: str) -> Response:
|
||||
return self.request("GET", f"/api/v1/attachments/{attachment_id}", token=token)
|
||||
|
||||
def download(self, token: str, attachment_id: str, variant: Optional[str] = None) -> Response:
|
||||
path = f"/api/v1/attachments/{attachment_id}/content"
|
||||
if variant is not None:
|
||||
path += f"?variant={variant}"
|
||||
return self.request("GET", path, token=token)
|
||||
|
||||
def list_messages(self, token: str, chat_id: str, limit: int = 50, cursor=None) -> Response:
|
||||
path = f"/api/v1/chats/{chat_id}/messages?limit={limit}"
|
||||
if cursor is not None:
|
||||
from urllib.parse import quote
|
||||
|
||||
path += "&cursor=" + quote(cursor, safe="")
|
||||
return self.request("GET", path, token=token)
|
||||
|
||||
def logout(self, token: str) -> Response:
|
||||
return self.request("DELETE", "/api/v1/auth/sessions/current", token=token)
|
||||
@@ -0,0 +1,133 @@
|
||||
"""Attachment tests for lab5: async accept (202), variants, access control.
|
||||
|
||||
Upload now returns ``202 queued``; readiness is polled via GET metadata.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
|
||||
|
||||
def _assert_error(response, status, code):
|
||||
assert response.status == status, (response.status, response.body)
|
||||
assert response.content_type == "application/json"
|
||||
payload = response.json
|
||||
assert payload["error"]["code"] == code
|
||||
assert payload["error"]["request_id"] == response.request_id
|
||||
|
||||
|
||||
def _fresh_actor(client, label):
|
||||
from conftest import _register_and_login
|
||||
|
||||
return _register_and_login(client, label)
|
||||
|
||||
|
||||
def _peer_chat(client, actor):
|
||||
peer = _fresh_actor(client, "att_peer")
|
||||
response = client.create_chat(actor["token"], [actor["id"], peer["id"]], title="Attachment chat")
|
||||
assert response.status == 201, response.body
|
||||
return response.json, peer
|
||||
|
||||
|
||||
def wait_ready(client, token, attachment_id, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
last = None
|
||||
while time.monotonic() < deadline:
|
||||
last = client.get_attachment(token, attachment_id).json
|
||||
if last["status"] == "failed":
|
||||
raise AssertionError(f"attachment failed: {last.get('error_code')}")
|
||||
if last["status"] == "ready":
|
||||
return last
|
||||
time.sleep(0.3)
|
||||
raise AssertionError(f"attachment not ready in time: {last}")
|
||||
|
||||
|
||||
def test_upload_is_202_queued_then_ready(client, alice, bob, chat):
|
||||
upload = client.upload_attachment(alice["token"], chat["id"], SAMPLE, filename="sample.png")
|
||||
assert upload.status == 202, upload.body
|
||||
att = upload.json
|
||||
assert att["status"] == "queued"
|
||||
assert att["error_code"] is None
|
||||
assert att["variants"] == []
|
||||
assert att["chat_id"] == chat["id"] and att["owner_id"] == alice["id"]
|
||||
assert att["content_type"] == "image/png"
|
||||
assert att["size_bytes"] == len(SAMPLE)
|
||||
assert att["sha256"] == hashlib.sha256(SAMPLE).hexdigest()
|
||||
|
||||
ready = wait_ready(client, bob["token"], att["id"])
|
||||
assert ready["status"] == "ready" and ready["error_code"] is None
|
||||
names = {v["name"] for v in ready["variants"]}
|
||||
assert {"thumbnail", "crop", "optimized"} <= names, names
|
||||
|
||||
download = client.download(bob["token"], att["id"])
|
||||
assert download.status == 200, download.body
|
||||
assert download.body == SAMPLE
|
||||
assert download.content_type == "image/png"
|
||||
|
||||
message = client.send(alice["token"], chat["id"], "", attachments=[att["id"]])
|
||||
assert message.status == 201, message.body
|
||||
assert message.json["attachment_ids"] == [att["id"]]
|
||||
|
||||
|
||||
def test_content_409_while_queued(client, alice, chat):
|
||||
# A fresh attachment is queued/processing for at least a moment; if the
|
||||
# worker is fast it may already be ready, so accept either 409 or 200.
|
||||
att = client.upload_attachment(alice["token"], chat["id"], SAMPLE).json
|
||||
response = client.download(alice["token"], att["id"])
|
||||
assert response.status in (200, 409), response.status
|
||||
if response.status == 409:
|
||||
_assert_error(response, 409, "conflict")
|
||||
|
||||
|
||||
def test_foreign_actor_gets_404(client, alice, bob, chat):
|
||||
att = client.upload_attachment(alice["token"], chat["id"], SAMPLE).json
|
||||
stranger = _fresh_actor(client, "foreign")
|
||||
_assert_error(client.get_attachment(stranger["token"], att["id"]), 404, "not_found")
|
||||
_assert_error(client.download(stranger["token"], att["id"]), 404, "not_found")
|
||||
|
||||
|
||||
def test_cross_chat_attachment_is_404(client, alice, bob, chat):
|
||||
other_chat, _peer = _peer_chat(client, alice)
|
||||
foreign = client.upload_attachment(alice["token"], other_chat["id"], SAMPLE).json
|
||||
response = client.send(alice["token"], chat["id"], "", attachments=[foreign["id"]])
|
||||
_assert_error(response, 404, "not_found")
|
||||
|
||||
|
||||
def test_oversized_upload_is_413(client, alice, chat):
|
||||
too_big = b"\x89PNG\r\n\x1a\n" + b"\x00" * (10 * 1024 * 1024 + 1)
|
||||
_assert_error(client.upload_attachment(alice["token"], chat["id"], too_big), 413, "payload_too_large")
|
||||
|
||||
|
||||
def test_corrupt_image_is_415(client, alice, chat):
|
||||
corrupt = b"\x89PNG\r\n\x1a\n" + os.urandom(256)
|
||||
_assert_error(client.upload_attachment(alice["token"], chat["id"], corrupt), 415, "unsupported_media_type")
|
||||
|
||||
|
||||
def test_mime_spoof_is_415(client, alice, chat):
|
||||
spoof = b"GIF89a" + os.urandom(64)
|
||||
_assert_error(
|
||||
client.upload_attachment(alice["token"], chat["id"], spoof, content_type="image/png"),
|
||||
415,
|
||||
"unsupported_media_type",
|
||||
)
|
||||
|
||||
|
||||
def test_empty_upload_is_415(client, alice, chat):
|
||||
_assert_error(client.upload_attachment(alice["token"], chat["id"], b""), 415, "unsupported_media_type")
|
||||
|
||||
|
||||
def test_unsafe_filename_is_400(client, alice, chat):
|
||||
_assert_error(
|
||||
client.upload_attachment(alice["token"], chat["id"], SAMPLE, filename="a/b.png"),
|
||||
400,
|
||||
"invalid_request",
|
||||
)
|
||||
|
||||
|
||||
def test_empty_text_without_attachment_is_400(client, alice, chat):
|
||||
_assert_error(client.send(alice["token"], chat["id"], ""), 400, "invalid_request")
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Authentication and registration tests (lab2 auth, unchanged in lab3)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import os
|
||||
|
||||
|
||||
def _assert_error(response, status, code, challenge_prefix=None):
|
||||
assert response.status == status, (response.status, response.body)
|
||||
assert response.content_type == "application/json"
|
||||
payload = response.json
|
||||
assert payload["error"]["code"] == code
|
||||
assert response.request_id, "missing X-Request-Id"
|
||||
assert payload["error"]["request_id"] == response.request_id
|
||||
if challenge_prefix:
|
||||
header = response.headers.get("WWW-Authenticate", "")
|
||||
assert header.lower().startswith(challenge_prefix.lower()), header
|
||||
|
||||
|
||||
def test_registration_requires_password(client):
|
||||
response = client.request(
|
||||
"POST", "/api/v1/users", body={"username": "no_pw_" + os.urandom(3).hex(), "display_name": "X"}
|
||||
)
|
||||
_assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_short_password_is_400(client):
|
||||
response = client.register("shortpw_" + os.urandom(3).hex(), "too-short")
|
||||
_assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_extra_field_is_400(client):
|
||||
response = client.request(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
body={
|
||||
"username": "extra_" + os.urandom(3).hex(),
|
||||
"display_name": "X",
|
||||
"password": "T3st-" + os.urandom(8).hex(),
|
||||
"role": "admin",
|
||||
},
|
||||
)
|
||||
_assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_malformed_json_is_400(client):
|
||||
response = client.request("POST", "/api/v1/users", raw=b"{not json")
|
||||
_assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_duplicate_username_is_409(client):
|
||||
username = "dup_" + os.urandom(4).hex()
|
||||
password = "T3st-" + os.urandom(8).hex()
|
||||
assert client.register(username, password).status == 201
|
||||
_assert_error(client.register(username, password), 409, "conflict")
|
||||
|
||||
|
||||
def test_registration_never_returns_password(client):
|
||||
response = client.register("pw_hidden_" + os.urandom(3).hex(), "T3st-" + os.urandom(8).hex())
|
||||
assert response.status == 201, response.body
|
||||
assert "password" not in response.json
|
||||
|
||||
|
||||
def test_wrong_password_is_401_basic(client, alice):
|
||||
_assert_error(
|
||||
client.login(alice["username"], "definitely-wrong-password"),
|
||||
401,
|
||||
"unauthorized",
|
||||
challenge_prefix="Basic",
|
||||
)
|
||||
|
||||
|
||||
def test_unknown_user_is_401_basic(client):
|
||||
_assert_error(
|
||||
client.login("ghost_" + os.urandom(4).hex(), "T3st-" + os.urandom(8).hex()),
|
||||
401,
|
||||
"unauthorized",
|
||||
challenge_prefix="Basic",
|
||||
)
|
||||
|
||||
|
||||
def test_basic_on_business_endpoint_is_401_bearer(client, alice):
|
||||
credential = base64.b64encode(f"{alice['username']}:{alice['password']}".encode()).decode()
|
||||
response = client.request("GET", "/api/v1/users/me", basic=credential)
|
||||
_assert_error(response, 401, "unauthorized", challenge_prefix="Bearer")
|
||||
|
||||
|
||||
def test_missing_auth_is_401_bearer(client):
|
||||
_assert_error(client.request("GET", "/api/v1/users/me"), 401, "unauthorized", challenge_prefix="Bearer")
|
||||
|
||||
|
||||
def test_unknown_bearer_is_401(client):
|
||||
_assert_error(
|
||||
client.me("not-a-real-token-" + os.urandom(8).hex()),
|
||||
401,
|
||||
"unauthorized",
|
||||
challenge_prefix="Bearer",
|
||||
)
|
||||
|
||||
|
||||
def test_x_user_id_is_ignored(client, alice, bob):
|
||||
only_header = client.request("GET", "/api/v1/users/me", headers={"X-User-Id": alice["id"]})
|
||||
_assert_error(only_header, 401, "unauthorized", challenge_prefix="Bearer")
|
||||
response = client.request(
|
||||
"GET", "/api/v1/users/me", token=alice["token"], headers={"X-User-Id": bob["id"]}
|
||||
)
|
||||
assert response.status == 200, response.body
|
||||
assert response.json["id"] == alice["id"]
|
||||
|
||||
|
||||
def test_logout_revokes_session(client):
|
||||
suffix = os.urandom(4).hex()
|
||||
username = f"s_out_{suffix}"
|
||||
password = "T3st-" + os.urandom(8).hex()
|
||||
assert client.register(username, password).status == 201
|
||||
token = client.login(username, password).json["token"]
|
||||
assert client.me(token).status == 200
|
||||
logout = client.logout(token)
|
||||
assert logout.status == 204, logout.body
|
||||
assert not logout.body
|
||||
_assert_error(client.me(token), 401, "unauthorized", challenge_prefix="Bearer")
|
||||
_assert_error(client.logout(token), 401, "unauthorized", challenge_prefix="Bearer")
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Concurrency: 100 parallel unique messages survive without loss."""
|
||||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import os
|
||||
|
||||
|
||||
def _register(client, label):
|
||||
username = f"s_race_{label}_{os.urandom(4).hex()}"
|
||||
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_100_concurrent_messages_are_not_lost(client, alice):
|
||||
senders = [_register(client, str(i)) for i in range(10)]
|
||||
members = [alice["id"]] + [sender["id"] for sender in senders]
|
||||
chat = client.create_chat(alice["token"], members).json
|
||||
|
||||
def worker(task):
|
||||
sender, index = task
|
||||
response = client.send(sender["token"], chat["id"], f"race-{index}")
|
||||
assert response.status == 201, response.body
|
||||
return response.json["id"]
|
||||
|
||||
tasks = [(senders[index // 10], index) for index in range(100)]
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=25) as pool:
|
||||
created = list(pool.map(worker, tasks))
|
||||
|
||||
assert len(created) == 100
|
||||
assert len(set(created)) == 100, "duplicate message ids"
|
||||
history = client.list_messages(alice["token"], chat["id"], limit=100).json
|
||||
stored = [item["id"] for item in history["items"]]
|
||||
assert len(stored) == 100, f"stored {len(stored)} of 100"
|
||||
assert len(set(stored)) == 100
|
||||
assert set(stored) == set(created)
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Lab3 shared idempotency: replay, conflict and cross-replica concurrency."""
|
||||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import json
|
||||
import uuid
|
||||
|
||||
|
||||
def test_replay_same_key_returns_same_message(client, alice, chat):
|
||||
key = uuid.uuid4().hex
|
||||
first = client.send(alice["token"], chat["id"], "идемпотентно", key=key)
|
||||
assert first.status == 201, first.body
|
||||
replay = client.send(alice["token"], chat["id"], "идемпотентно", key=key)
|
||||
assert replay.status == 201, replay.body
|
||||
assert replay.json == first.json, "replay must return the same Message"
|
||||
|
||||
|
||||
def test_same_key_different_body_is_409(client, alice, chat):
|
||||
key = uuid.uuid4().hex
|
||||
assert client.send(alice["token"], chat["id"], "первый", key=key).status == 201
|
||||
conflict = client.send(alice["token"], chat["id"], "второй", key=key)
|
||||
assert conflict.status == 409, conflict.body
|
||||
assert conflict.json["error"]["code"] == "conflict"
|
||||
|
||||
|
||||
def test_missing_key_is_400(client, alice, chat):
|
||||
response = client.request(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
body={"text": "без ключа"},
|
||||
token=alice["token"],
|
||||
)
|
||||
assert response.status == 400, response.body
|
||||
assert response.json["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
def test_invalid_key_is_400(client, alice, chat):
|
||||
for bad in ("bad key", "has/slash", "x" * 129, "with$sign"):
|
||||
response = client.request(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
body={"text": "плохой ключ"},
|
||||
token=alice["token"],
|
||||
headers={"Idempotency-Key": bad},
|
||||
)
|
||||
assert response.status == 400, (bad, response.status, response.body)
|
||||
|
||||
|
||||
def test_concurrent_same_key_creates_exactly_one_message(client, alice, chat):
|
||||
key = uuid.uuid4().hex
|
||||
text = "конкурентный повтор " + uuid.uuid4().hex
|
||||
|
||||
def send(_):
|
||||
return client.send(alice["token"], chat["id"], text, key=key)
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
responses = list(pool.map(send, range(8)))
|
||||
|
||||
assert all(r.status == 201 for r in responses), [r.status for r in responses]
|
||||
bodies = {json.dumps(r.json, sort_keys=True) for r in responses}
|
||||
assert len(bodies) == 1, "parallel replays returned different messages"
|
||||
|
||||
history = client.list_messages(alice["token"], chat["id"], limit=100).json["items"]
|
||||
matching = [m for m in history if m["text"] == text]
|
||||
assert len(matching) == 1, f"expected exactly one stored message, got {len(matching)}"
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Lab3 balancing: X-Instance-Id is present and more than one replica serves."""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def test_instance_header_present_on_success(client, alice):
|
||||
response = client.me(alice["token"])
|
||||
assert response.status == 200, response.body
|
||||
assert response.instance_id, "missing X-Instance-Id"
|
||||
|
||||
|
||||
def test_instance_header_present_on_error(client):
|
||||
response = client.request("GET", "/api/v1/users/me")
|
||||
assert response.status == 401, response.body
|
||||
assert response.instance_id, "error response missing X-Instance-Id"
|
||||
|
||||
|
||||
def test_at_least_two_instances_seen_through_lb(client, alice):
|
||||
seen = set()
|
||||
for _ in range(60):
|
||||
instance = client.me(alice["token"]).instance_id
|
||||
if instance:
|
||||
seen.add(instance)
|
||||
assert len(seen) >= 2, f"expected >=2 API replicas behind the LB, saw {sorted(seen)}"
|
||||
@@ -0,0 +1,65 @@
|
||||
"""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")
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Keyset pagination tests (carried over from lab2)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
|
||||
|
||||
def _fake_cursor(payload) -> str:
|
||||
raw = json.dumps(payload, separators=(",", ":")).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _fresh_chat(client, alice):
|
||||
suffix = os.urandom(4).hex()
|
||||
username = f"s_page_{suffix}"
|
||||
password = "T3st-" + os.urandom(8).hex()
|
||||
assert client.register(username, password).status == 201
|
||||
peer_token = client.login(username, password).json["token"]
|
||||
peer_id = client.me(peer_token).json["id"]
|
||||
response = client.create_chat(alice["token"], [alice["id"], peer_id])
|
||||
assert response.status == 201, response.body
|
||||
return response.json
|
||||
|
||||
|
||||
def test_full_traversal_without_duplicates(client, alice):
|
||||
chat = _fresh_chat(client, alice)
|
||||
expected = []
|
||||
for index in range(5):
|
||||
response = client.send(alice["token"], chat["id"], f"msg-{index}")
|
||||
assert response.status == 201, response.body
|
||||
expected.append(response.json["id"])
|
||||
|
||||
seen = []
|
||||
cursor = None
|
||||
while True:
|
||||
page = client.list_messages(alice["token"], chat["id"], limit=2, cursor=cursor).json
|
||||
assert len(page["items"]) <= 2
|
||||
seen.extend(item["id"] for item in page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
assert len(seen) == 5
|
||||
assert len(set(seen)) == 5, "duplicate across pages"
|
||||
assert seen == expected, "pagination reordered history"
|
||||
|
||||
|
||||
def test_cursor_from_other_chat_is_400(client, alice):
|
||||
first = _fresh_chat(client, alice)
|
||||
second = _fresh_chat(client, alice)
|
||||
for index in range(3):
|
||||
client.send(alice["token"], first["id"], f"a{index}")
|
||||
client.send(alice["token"], second["id"], f"b{index}")
|
||||
cursor = client.list_messages(alice["token"], first["id"], limit=1).json["next_cursor"]
|
||||
assert cursor
|
||||
foreign = client.list_messages(alice["token"], second["id"], limit=1, cursor=cursor)
|
||||
assert foreign.status == 400, foreign.body
|
||||
assert foreign.json["error"]["code"] == "invalid_request"
|
||||
|
||||
|
||||
def test_garbage_cursor_is_400(client, alice):
|
||||
chat = _fresh_chat(client, alice)
|
||||
client.send(alice["token"], chat["id"], "hello")
|
||||
response = client.list_messages(alice["token"], chat["id"], cursor="!!!not-a-cursor!!!")
|
||||
assert response.status == 400, response.body
|
||||
|
||||
|
||||
def test_well_formed_cursor_with_wrong_types_is_400(client, alice):
|
||||
bad_payloads = [
|
||||
{"r": "chats", "t": "2026-01-01T00:00:00.000000Z", "i": 1},
|
||||
{"r": "chats", "t": "2026-01-01T00:00:00.000000Z", "i": []},
|
||||
{"r": "chats", "t": "2026-01-01T00:00:00.000000Z", "i": True},
|
||||
{"r": "chats", "t": "not-a-time", "i": "11111111-1111-4111-8111-111111111111"},
|
||||
]
|
||||
for payload in bad_payloads:
|
||||
response = client.request(
|
||||
"GET", "/api/v1/chats?cursor=" + _fake_cursor(payload), token=alice["token"]
|
||||
)
|
||||
assert response.status == 400, (payload, response.status, response.body)
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Variant pipeline tests (lab5): thumbnail/crop/optimized correctness."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from test_attachments import SAMPLE, wait_ready
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def jpeg_size(data: bytes):
|
||||
assert data[:2] == b"\xff\xd8", "not JPEG"
|
||||
i = 2
|
||||
sof = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}
|
||||
while i < len(data):
|
||||
assert data[i] == 0xFF, "invalid JPEG marker"
|
||||
while i < len(data) and data[i] == 0xFF:
|
||||
i += 1
|
||||
marker = data[i]
|
||||
i += 1
|
||||
if marker in {0xD9, 0xDA}:
|
||||
break
|
||||
if marker in {0x01, 0xD8} or 0xD0 <= marker <= 0xD7:
|
||||
continue
|
||||
length = int.from_bytes(data[i : i + 2], "big")
|
||||
if marker in sof:
|
||||
return (int.from_bytes(data[i + 5 : i + 7], "big"), int.from_bytes(data[i + 3 : i + 5], "big"))
|
||||
i += length
|
||||
raise AssertionError("JPEG dimensions not found")
|
||||
|
||||
|
||||
def _variant(ready, name):
|
||||
matches = [v for v in ready["variants"] if v["name"] == name]
|
||||
assert len(matches) == 1, (name, ready["variants"])
|
||||
return matches[0]
|
||||
|
||||
|
||||
def test_variants_match_contract(client, alice, bob, chat):
|
||||
import hashlib
|
||||
|
||||
att = client.upload_attachment(alice["token"], chat["id"], SAMPLE).json
|
||||
ready = wait_ready(client, bob["token"], att["id"])
|
||||
assert len(ready["variants"]) == 3
|
||||
assert {v["name"] for v in ready["variants"]} == {"thumbnail", "crop", "optimized"}
|
||||
|
||||
thumb = _variant(ready, "thumbnail")
|
||||
assert (thumb["width"], thumb["height"]) == (256, 160), thumb
|
||||
assert thumb["content_type"] == "image/jpeg"
|
||||
body = client.download(bob["token"], att["id"], variant="thumbnail")
|
||||
assert body.content_type == "image/jpeg"
|
||||
assert len(body.body) == thumb["size_bytes"]
|
||||
assert hashlib.sha256(body.body).hexdigest() == thumb["sha256"]
|
||||
assert jpeg_size(body.body) == (256, 160)
|
||||
|
||||
crop = _variant(ready, "crop")
|
||||
assert (crop["width"], crop["height"]) == (128, 128), crop
|
||||
crop_body = client.download(bob["token"], att["id"], variant="crop").body
|
||||
assert jpeg_size(crop_body) == (128, 128)
|
||||
|
||||
optimized = _variant(ready, "optimized")
|
||||
assert optimized["content_type"] == "image/webp"
|
||||
opt_body = client.download(bob["token"], att["id"], variant="optimized").body
|
||||
assert opt_body[:4] == b"RIFF" and opt_body[8:12] == b"WEBP", "not WebP"
|
||||
|
||||
# original remains byte-identical
|
||||
assert client.download(bob["token"], att["id"]).body == SAMPLE
|
||||
|
||||
|
||||
def test_missing_variant_is_404(client, alice, bob, chat):
|
||||
from test_attachments import _assert_error
|
||||
|
||||
att = client.upload_attachment(alice["token"], chat["id"], SAMPLE).json
|
||||
wait_ready(client, bob["token"], att["id"])
|
||||
_assert_error(client.download(bob["token"], att["id"], variant="unknown"), 404, "not_found")
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Grade-4 integrity checks: registration race and composite-op rollback."""
|
||||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import os
|
||||
|
||||
|
||||
def test_concurrent_duplicate_username_single_winner(client):
|
||||
username = "race_dup_" + os.urandom(4).hex()
|
||||
password = "T3st-" + os.urandom(8).hex()
|
||||
|
||||
def register(_):
|
||||
return client.register(username, password).status
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as pool:
|
||||
statuses = list(pool.map(register, range(5)))
|
||||
|
||||
assert statuses.count(201) == 1, statuses
|
||||
assert statuses.count(409) == 4, statuses
|
||||
|
||||
|
||||
def test_failed_chat_creation_rolls_back(client, alice):
|
||||
def chats_count():
|
||||
return len(client.request("GET", "/api/v1/chats?limit=100", token=alice["token"]).json["items"])
|
||||
|
||||
before = chats_count()
|
||||
unknown = "00000000-0000-4000-8000-000000000000"
|
||||
response = client.create_chat(alice["token"], [alice["id"], unknown], title="should-rollback")
|
||||
assert response.status == 400, response.body
|
||||
after = chats_count()
|
||||
assert after == before, "failed composite operation left a partial chat"
|
||||
|
||||
listed = client.request("GET", "/api/v1/chats?limit=100", token=alice["token"]).json["items"]
|
||||
assert all(item["title"] != "should-rollback" for item in listed)
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Lab3 revocation: logout takes effect immediately on every replica.
|
||||
|
||||
Session validity is decided only by PostgreSQL, so a revoked token must be
|
||||
rejected regardless of which replica answers and regardless of the cache state.
|
||||
The heavier Valkey-outage reproduction lives in scripts/check-revocation.py.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
|
||||
def _actor(client, label="revoke"):
|
||||
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_logout_invalidates_across_replicas(client):
|
||||
actor = _actor(client)
|
||||
seen = set()
|
||||
for _ in range(20):
|
||||
response = client.me(actor["token"])
|
||||
assert response.status == 200, response.body
|
||||
seen.add(response.instance_id)
|
||||
assert len(seen) >= 2, f"expected the LB to spread requests, saw {sorted(seen)}"
|
||||
|
||||
logout = client.logout(actor["token"])
|
||||
assert logout.status == 204, logout.body
|
||||
|
||||
for _ in range(20):
|
||||
assert client.me(actor["token"]).status == 401
|
||||
Reference in New Issue
Block a user