forked from mtusi2026/mtusi2026lab3
лабораторная работа 3
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,125 @@
|
||||
"""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,
|
||||
) -> 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())
|
||||
return self.request(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
body={"text": text},
|
||||
token=token,
|
||||
headers=request_headers,
|
||||
)
|
||||
|
||||
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,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,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)
|
||||
Reference in New Issue
Block a user