Реализация лабораторной 2: PostgreSQL, сессии, Valkey-кэш
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,201 @@
|
||||
"""Minimal standard-library HTTP client for the student's own tests.
|
||||
|
||||
Run with the API already up:
|
||||
|
||||
python -m unittest discover -s student-tests -p "test_*.py" -v
|
||||
|
||||
BASE_URL selects the stand (default http://127.0.0.1:8080). No third-party
|
||||
dependency is needed, so `make test-student` works on a clean clone.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
# 127.0.0.1 rather than "localhost": on a dual-stack host "localhost" resolves
|
||||
# to ::1 first, a published Docker port may answer on IPv4 only, and every IPv6
|
||||
# attempt then costs ~2 s of SYN retry before urllib falls back to IPv4. The IPv4
|
||||
# literal keeps the client fast and never reaches the application.
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
|
||||
TIMEOUT = float(os.environ.get("STUDENT_TEST_TIMEOUT", "20"))
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
"""The contract never requires redirects; fail loudly instead of following."""
|
||||
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: ANN001
|
||||
return None
|
||||
|
||||
|
||||
# The lab stand is always loopback; urllib ignores the Windows proxy bypass
|
||||
# list, so a corporate/system proxy would otherwise be used for localhost too.
|
||||
_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
|
||||
|
||||
|
||||
class Response:
|
||||
def __init__(self, status: int, headers: dict[str, str], data: bytes) -> None:
|
||||
self.status = status
|
||||
self.headers = headers
|
||||
self.data = data
|
||||
try:
|
||||
self.json = json.loads(data.decode("utf-8")) if data else None
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
self.json = None
|
||||
|
||||
def header(self, name: str) -> str:
|
||||
for key, value in self.headers.items():
|
||||
if key.lower() == name.lower():
|
||||
return value
|
||||
return ""
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover - diagnostics only
|
||||
return "Response(status=%s, json=%r)" % (self.status, self.json)
|
||||
|
||||
|
||||
def request(
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
body=None,
|
||||
raw: bytes | None = None,
|
||||
token: str | None = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
content_type: str | None = None,
|
||||
timeout: float | None = None,
|
||||
base_url: str | None = None,
|
||||
) -> Response:
|
||||
url = (base_url or BASE_URL) + path
|
||||
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 content_type is not None:
|
||||
request_headers["Content-Type"] = content_type
|
||||
if token is not None:
|
||||
request_headers["Authorization"] = "Bearer " + token
|
||||
request_headers.update(headers or {})
|
||||
prepared = urllib.request.Request(url, data=data, headers=request_headers, method=method)
|
||||
try:
|
||||
response = _OPENER.open(prepared, timeout=timeout or TIMEOUT)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
payload = response.read()
|
||||
return Response(response.code, dict(response.headers.items()), payload)
|
||||
|
||||
|
||||
def basic(username: str, password: str) -> dict[str, str]:
|
||||
encoded = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii")
|
||||
return {"Authorization": "Basic " + encoded}
|
||||
|
||||
|
||||
def new_registration(prefix: str = "st", password: str | None = None) -> dict[str, str]:
|
||||
suffix = uuid.uuid4().hex[:12]
|
||||
return {
|
||||
"username": prefix + "_" + suffix,
|
||||
"display_name": "Тест " + suffix,
|
||||
"password": password or ("St-" + uuid.uuid4().hex),
|
||||
}
|
||||
|
||||
|
||||
def register(registration: dict[str, str] | None = None) -> Response:
|
||||
return request("POST", "/api/v1/users", body=registration or new_registration())
|
||||
|
||||
|
||||
def login(username: str, password: str) -> Response:
|
||||
return request("POST", "/api/v1/auth/sessions", headers=basic(username, password))
|
||||
|
||||
|
||||
class Actor:
|
||||
"""A registered user with a live session, as a client would hold it."""
|
||||
|
||||
def __init__(self, registration: dict[str, str]) -> None:
|
||||
self.registration = registration
|
||||
response = register(registration)
|
||||
if response.status != 201:
|
||||
raise AssertionError(
|
||||
"registration failed: %s %r" % (response.status, response.json)
|
||||
)
|
||||
self.user = response.json
|
||||
self.username = registration["username"]
|
||||
self.password = registration["password"]
|
||||
|
||||
@property
|
||||
def id(self) -> str:
|
||||
return self.user["id"]
|
||||
|
||||
def sign_in(self) -> "Actor":
|
||||
response = login(self.username, self.password)
|
||||
if response.status != 201:
|
||||
raise AssertionError("login failed: %s %r" % (response.status, response.json))
|
||||
self.session = response.json
|
||||
self.token = response.json["token"]
|
||||
return self
|
||||
|
||||
|
||||
def actor(prefix: str = "st", password: str | None = None) -> Actor:
|
||||
return Actor(new_registration(prefix, password)).sign_in()
|
||||
|
||||
|
||||
def create_chat(token: str, member_ids: list[str], title: str = "Тестовый чат") -> dict:
|
||||
response = request(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
body={"title": title, "member_ids": member_ids},
|
||||
token=token,
|
||||
)
|
||||
if response.status != 201:
|
||||
raise AssertionError("chat creation failed: %s %r" % (response.status, response.json))
|
||||
return response.json
|
||||
|
||||
|
||||
def send(token: str, chat_id: str, text: str) -> dict:
|
||||
response = request(
|
||||
"POST", "/api/v1/chats/" + chat_id + "/messages", body={"text": text}, token=token
|
||||
)
|
||||
if response.status != 201:
|
||||
raise AssertionError("message failed: %s %r" % (response.status, response.json))
|
||||
return response.json
|
||||
|
||||
|
||||
def history(token: str, chat_id: str, limit: int = 100) -> list[dict]:
|
||||
"""Walk every page of a chat, guarding against cursor loops."""
|
||||
items: list[dict] = []
|
||||
seen: set[str] = set()
|
||||
cursor: str | None = None
|
||||
while True:
|
||||
path = "/api/v1/chats/" + chat_id + "/messages?limit=" + str(limit)
|
||||
if cursor is not None:
|
||||
path += "&cursor=" + urllib.parse.quote(cursor, safe="")
|
||||
response = request("GET", path, token=token)
|
||||
if response.status != 200:
|
||||
raise AssertionError("history failed: %s %r" % (response.status, response.json))
|
||||
items.extend(response.json["items"])
|
||||
cursor = response.json["next_cursor"]
|
||||
if cursor is None:
|
||||
return items
|
||||
if cursor in seen:
|
||||
raise AssertionError("cursor loop detected")
|
||||
seen.add(cursor)
|
||||
|
||||
|
||||
def expect_error(test, response: Response, status: int, code: str) -> dict:
|
||||
"""Assert the public error envelope, request id echo and the status."""
|
||||
test.assertEqual(response.status, status, response.json)
|
||||
test.assertIsInstance(response.json, dict)
|
||||
error = response.json.get("error")
|
||||
test.assertIsNotNone(error, "missing error envelope")
|
||||
test.assertEqual(error["code"], code)
|
||||
test.assertTrue(error["message"])
|
||||
request_id = response.header("X-Request-Id")
|
||||
test.assertTrue(request_id, "missing X-Request-Id header")
|
||||
test.assertEqual(error["request_id"], request_id)
|
||||
return error
|
||||
@@ -0,0 +1,329 @@
|
||||
"""Own functional tests: contract edges carried from lab 1 plus lab 2 auth.
|
||||
|
||||
Every test creates unique synthetic users, so the file is safe to re-run against
|
||||
the same stand (the API has no delete endpoint by design).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import common
|
||||
|
||||
|
||||
def timestamp(value: str) -> datetime:
|
||||
return datetime.fromisoformat(value[:-1] + "+00:00")
|
||||
|
||||
|
||||
class Base(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
again = common.request("POST", "/api/v1/users", body=common.new_registration())
|
||||
if again.status != 201:
|
||||
raise AssertionError("stand is not serving: %r" % (again.json,))
|
||||
cls.alice = common.actor("alice")
|
||||
cls.bob = common.actor("bob")
|
||||
cls.eve = common.actor("eve")
|
||||
cls.chat = common.create_chat(
|
||||
cls.alice.token, [cls.alice.id, cls.bob.id], "Контрактный чат"
|
||||
)
|
||||
|
||||
|
||||
class HealthAndEnvelope(Base):
|
||||
def test_health_endpoints_and_request_id(self) -> None:
|
||||
live = common.request("GET", "/health/live")
|
||||
self.assertEqual(live.status, 200)
|
||||
self.assertEqual(live.json, {"status": "ok"})
|
||||
self.assertTrue(live.header("X-Request-Id"))
|
||||
ready = common.request("GET", "/health/ready")
|
||||
self.assertEqual(ready.status, 200)
|
||||
self.assertEqual(ready.json, {"status": "ok"})
|
||||
|
||||
def test_unknown_route_uses_same_error_envelope(self) -> None:
|
||||
common.expect_error(self, common.request("GET", "/api/v1/nope"), 404, "not_found")
|
||||
|
||||
def test_query_parameters_rejected_where_not_supported(self) -> None:
|
||||
response = common.request(
|
||||
"GET", "/api/v1/users/me?verbose=1", token=self.alice.token
|
||||
)
|
||||
common.expect_error(self, response, 400, "invalid_request")
|
||||
|
||||
|
||||
class Registration(Base):
|
||||
def test_response_has_no_secret_fields(self) -> None:
|
||||
response = common.register(common.new_registration())
|
||||
self.assertEqual(response.status, 201)
|
||||
self.assertEqual(
|
||||
set(response.json), {"id", "username", "display_name", "created_at"}
|
||||
)
|
||||
self.assertNotIn("password", response.json)
|
||||
self.assertNotIn("password_hash", response.json)
|
||||
|
||||
def test_duplicate_username_conflict(self) -> None:
|
||||
registration = common.new_registration()
|
||||
self.assertEqual(common.register(registration).status, 201)
|
||||
common.expect_error(self, common.register(registration), 409, "conflict")
|
||||
|
||||
def test_username_rules(self) -> None:
|
||||
for username in ("UPPER_case", "ab", "with-dash", "with space"):
|
||||
body = common.new_registration()
|
||||
body["username"] = username
|
||||
common.expect_error(self, common.register(body), 400, "invalid_request")
|
||||
|
||||
def test_password_rules(self) -> None:
|
||||
short = common.new_registration(password="x" * 11)
|
||||
common.expect_error(self, common.register(short), 400, "invalid_request")
|
||||
long_password = common.new_registration(password="x" * 129)
|
||||
common.expect_error(self, common.register(long_password), 400, "invalid_request")
|
||||
# 12 Unicode code points are enough, even when they are multi-byte.
|
||||
unicode_password = common.new_registration(password="😀" * 12)
|
||||
self.assertEqual(common.register(unicode_password).status, 201)
|
||||
|
||||
def test_malformed_json_extra_fields_and_wrong_types(self) -> None:
|
||||
common.expect_error(
|
||||
self,
|
||||
common.request(
|
||||
"POST", "/api/v1/users", raw=b'{"username": ', content_type="application/json"
|
||||
),
|
||||
400,
|
||||
"invalid_request",
|
||||
)
|
||||
body = common.new_registration()
|
||||
body["is_admin"] = True
|
||||
common.expect_error(self, common.register(body), 400, "invalid_request")
|
||||
body = common.new_registration()
|
||||
body["display_name"] = 42
|
||||
common.expect_error(self, common.register(body), 400, "invalid_request")
|
||||
|
||||
def test_unsupported_media_type(self) -> None:
|
||||
response = common.request(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
raw=b"username=alice",
|
||||
content_type="application/x-www-form-urlencoded",
|
||||
)
|
||||
common.expect_error(self, response, 415, "unsupported_media_type")
|
||||
|
||||
|
||||
class Chats(Base):
|
||||
def test_membership_validation(self) -> None:
|
||||
cases = [
|
||||
[self.bob.id], # caller is missing
|
||||
[self.alice.id, self.alice.id], # duplicate member
|
||||
[self.alice.id, str(uuid.uuid4())], # unknown member
|
||||
[], # no members
|
||||
]
|
||||
for member_ids in cases:
|
||||
response = common.request(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
body={"title": "Плохой чат", "member_ids": member_ids},
|
||||
token=self.alice.token,
|
||||
)
|
||||
common.expect_error(self, response, 400, "invalid_request")
|
||||
|
||||
def test_foreign_chat_is_hidden_everywhere(self) -> None:
|
||||
chat_id = self.chat["id"]
|
||||
common.expect_error(
|
||||
self,
|
||||
common.request("GET", "/api/v1/chats/" + chat_id, token=self.eve.token),
|
||||
404,
|
||||
"not_found",
|
||||
)
|
||||
common.expect_error(
|
||||
self,
|
||||
common.request(
|
||||
"GET", "/api/v1/chats/" + chat_id + "/messages", token=self.eve.token
|
||||
),
|
||||
404,
|
||||
"not_found",
|
||||
)
|
||||
common.expect_error(
|
||||
self,
|
||||
common.request(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat_id + "/messages",
|
||||
body={"text": "чужое"},
|
||||
token=self.eve.token,
|
||||
),
|
||||
404,
|
||||
"not_found",
|
||||
)
|
||||
listed = common.request("GET", "/api/v1/chats?limit=100", token=self.eve.token)
|
||||
self.assertEqual(listed.status, 200)
|
||||
self.assertNotIn(chat_id, [item["id"] for item in listed.json["items"]])
|
||||
|
||||
def test_messages_are_validated_and_unicode_preserved(self) -> None:
|
||||
chat = common.create_chat(self.alice.token, [self.alice.id, self.bob.id])
|
||||
for text in ("", " \n\t ", "x" * 4001):
|
||||
response = common.request(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
body={"text": text},
|
||||
token=self.alice.token,
|
||||
)
|
||||
common.expect_error(self, response, 400, "invalid_request")
|
||||
prefix = "Привет 👋 世界 "
|
||||
text = prefix + "x" * (4000 - len(prefix)) # exactly the contract maximum
|
||||
message = common.send(self.alice.token, chat["id"], text)
|
||||
self.assertEqual(message["text"], text)
|
||||
self.assertEqual(message["sender_id"], self.alice.id)
|
||||
|
||||
injected = common.request(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
body={"text": "подмена", "sender_id": self.bob.id},
|
||||
token=self.alice.token,
|
||||
)
|
||||
common.expect_error(self, injected, 400, "invalid_request")
|
||||
|
||||
|
||||
class Pagination(Base):
|
||||
def test_walks_every_page_without_loss_or_duplicates(self) -> None:
|
||||
chat = common.create_chat(self.alice.token, [self.alice.id, self.bob.id])
|
||||
sent = [
|
||||
common.send(self.alice.token if index % 2 else self.bob.token, chat["id"], "msg-%d" % index)
|
||||
for index in range(7)
|
||||
]
|
||||
collected: list[dict] = []
|
||||
cursor = None
|
||||
pages = 0
|
||||
while True:
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=2"
|
||||
if cursor is not None:
|
||||
path += "&cursor=" + cursor
|
||||
page = common.request("GET", path, token=self.alice.token)
|
||||
self.assertEqual(page.status, 200)
|
||||
collected.extend(page.json["items"])
|
||||
pages += 1
|
||||
cursor = page.json["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
self.assertLess(pages, 10, "pagination did not terminate")
|
||||
self.assertEqual(pages, 4)
|
||||
self.assertEqual([item["id"] for item in collected], [item["id"] for item in sent])
|
||||
self.assertEqual(
|
||||
collected,
|
||||
sorted(collected, key=lambda item: (timestamp(item["created_at"]), item["id"])),
|
||||
)
|
||||
|
||||
def test_cursor_is_bound_to_its_chat(self) -> None:
|
||||
other = common.create_chat(self.alice.token, [self.alice.id])
|
||||
common.send(self.alice.token, other["id"], "a")
|
||||
common.send(self.alice.token, other["id"], "b")
|
||||
first = common.request(
|
||||
"GET", "/api/v1/chats/" + other["id"] + "/messages?limit=1", token=self.alice.token
|
||||
)
|
||||
cursor = first.json["next_cursor"]
|
||||
self.assertIsNotNone(cursor)
|
||||
response = common.request(
|
||||
"GET",
|
||||
"/api/v1/chats/" + self.chat["id"] + "/messages" + "?limit=1&cursor=" + cursor,
|
||||
token=self.alice.token,
|
||||
)
|
||||
common.expect_error(self, response, 400, "invalid_request")
|
||||
|
||||
def test_limit_and_cursor_validation(self) -> None:
|
||||
base = "/api/v1/chats/" + self.chat["id"] + "/messages"
|
||||
for query in ("?limit=0", "?limit=101", "?limit=abc", "?cursor=", "?cursor=not-a-cursor", "?limit=1&limit=2", "?unknown=1"):
|
||||
common.expect_error(
|
||||
self,
|
||||
common.request("GET", base + query, token=self.alice.token),
|
||||
400,
|
||||
"invalid_request",
|
||||
)
|
||||
|
||||
|
||||
class Authentication(Base):
|
||||
def test_basic_is_not_accepted_outside_session_creation(self) -> None:
|
||||
response = common.request(
|
||||
"GET", "/api/v1/users/me", headers=common.basic(self.alice.username, self.alice.password)
|
||||
)
|
||||
common.expect_error(self, response, 401, "unauthorized")
|
||||
self.assertTrue(response.header("WWW-Authenticate").lower().startswith("bearer"))
|
||||
|
||||
def test_missing_and_unknown_tokens(self) -> None:
|
||||
for headers in ({}, {"Authorization": "Bearer not-a-real-token"}):
|
||||
response = common.request("GET", "/api/v1/users/me", headers=headers)
|
||||
common.expect_error(self, response, 401, "unauthorized")
|
||||
self.assertTrue(response.header("WWW-Authenticate").lower().startswith("bearer"))
|
||||
|
||||
def test_x_user_id_is_ignored(self) -> None:
|
||||
response = common.request("GET", "/api/v1/users/me", headers={"X-User-Id": self.alice.id})
|
||||
common.expect_error(self, response, 401, "unauthorized")
|
||||
overridden = common.request(
|
||||
"GET",
|
||||
"/api/v1/users/me",
|
||||
token=self.alice.token,
|
||||
headers={"X-User-Id": self.eve.id},
|
||||
)
|
||||
self.assertEqual(overridden.status, 200)
|
||||
self.assertEqual(overridden.json["id"], self.alice.id)
|
||||
|
||||
def test_session_payload_and_expiry(self) -> None:
|
||||
response = common.login(self.alice.username, self.alice.password)
|
||||
self.assertEqual(response.status, 201)
|
||||
session = response.json
|
||||
self.assertEqual(set(session), {"token", "token_type", "expires_at", "user"})
|
||||
self.assertEqual(session["token_type"], "Bearer")
|
||||
self.assertGreaterEqual(len(session["token"]), 43)
|
||||
self.assertNotIn(self.alice.username, session["token"])
|
||||
self.assertNotEqual(session["token"], self.alice.id)
|
||||
self.assertEqual(session["user"], self.alice.user)
|
||||
self.assertGreater(timestamp(session["expires_at"]), datetime.now(timezone.utc))
|
||||
me = common.request("GET", "/api/v1/users/me", token=session["token"])
|
||||
self.assertEqual(me.status, 200)
|
||||
self.assertEqual(me.json, self.alice.user)
|
||||
|
||||
def test_wrong_password_and_unknown_user_are_indistinguishable(self) -> None:
|
||||
wrong = common.login(self.alice.username, "definitely-wrong-password")
|
||||
unknown = common.login("nobody_here_" + uuid.uuid4().hex[:8], "definitely-wrong-password")
|
||||
messages = []
|
||||
for response in (wrong, unknown):
|
||||
error = common.expect_error(self, response, 401, "unauthorized")
|
||||
self.assertTrue(
|
||||
response.header("WWW-Authenticate").lower().startswith("basic")
|
||||
)
|
||||
messages.append(error["message"])
|
||||
# Same message and challenge: a client cannot tell the accounts apart.
|
||||
self.assertEqual(messages[0], messages[1])
|
||||
|
||||
def test_logout_revokes_only_that_session(self) -> None:
|
||||
first = common.login(self.alice.username, self.alice.password).json["token"]
|
||||
second = common.login(self.alice.username, self.alice.password).json["token"]
|
||||
revoked = common.request("DELETE", "/api/v1/auth/sessions/current", token=first)
|
||||
self.assertEqual(revoked.status, 204)
|
||||
self.assertEqual(revoked.data, b"")
|
||||
common.expect_error(
|
||||
self,
|
||||
common.request("GET", "/api/v1/users/me", token=first),
|
||||
401,
|
||||
"unauthorized",
|
||||
)
|
||||
common.expect_error(
|
||||
self,
|
||||
common.request("DELETE", "/api/v1/auth/sessions/current", token=first),
|
||||
401,
|
||||
"unauthorized",
|
||||
)
|
||||
still_valid = common.request("GET", "/api/v1/users/me", token=second)
|
||||
self.assertEqual(still_valid.status, 200)
|
||||
|
||||
def test_session_endpoint_rejects_json_body_and_bad_basic(self) -> None:
|
||||
response = common.request(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
body={"username": self.alice.username, "password": self.alice.password},
|
||||
)
|
||||
common.expect_error(self, response, 401, "unauthorized")
|
||||
response = common.request(
|
||||
"POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic !!!not-base64!!!"}
|
||||
)
|
||||
common.expect_error(self, response, 401, "unauthorized")
|
||||
self.assertTrue(response.header("WWW-Authenticate").lower().startswith("basic"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Dependency outage behaviour: Valkey down, then PostgreSQL down.
|
||||
|
||||
Requires Docker access on the same host as the Compose stand and is therefore
|
||||
opt-in:
|
||||
|
||||
STUDENT_DOCKER_TESTS=1 python -m unittest -v test_degradation
|
||||
|
||||
The test never removes volumes and restores both services in `finally`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import statistics
|
||||
import subprocess
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import common
|
||||
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
PROJECT = os.environ.get("COMPOSE_PROJECT_NAME", "mtusi2026lab2")
|
||||
ENV_FILE = os.environ.get("COMPOSE_ENV_FILE", ".env")
|
||||
ENABLED = os.environ.get("STUDENT_DOCKER_TESTS") == "1"
|
||||
|
||||
|
||||
def compose(*arguments: str, timeout: int = 120) -> None:
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "-p", PROJECT, "--env-file", ENV_FILE, *arguments],
|
||||
cwd=str(REPO_ROOT),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=timeout,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(
|
||||
"docker compose %s failed: %s" % (" ".join(arguments), result.stderr[-500:])
|
||||
)
|
||||
|
||||
|
||||
def wait_ready(expected: int, seconds: float) -> float:
|
||||
started = time.monotonic()
|
||||
deadline = started + seconds
|
||||
last = None
|
||||
while time.monotonic() < deadline:
|
||||
last = common.request("GET", "/health/ready", timeout=5)
|
||||
if last.status == expected:
|
||||
return time.monotonic() - started
|
||||
time.sleep(0.5)
|
||||
raise AssertionError(
|
||||
"readiness did not reach %s within %.0fs (last=%s %r)"
|
||||
% (expected, seconds, last.status if last else None, last.json if last else None)
|
||||
)
|
||||
|
||||
|
||||
@unittest.skipUnless(ENABLED, "set STUDENT_DOCKER_TESTS=1 to stop real containers")
|
||||
class DependencyOutages(unittest.TestCase):
|
||||
def test_valkey_loss_degrades_then_postgres_loss_is_bounded(self) -> None:
|
||||
alice = common.actor("degrade")
|
||||
chat = common.create_chat(alice.token, [alice.id], "Устойчивость")
|
||||
# Warm the session cache.
|
||||
self.assertEqual(common.request("GET", "/api/v1/users/me", token=alice.token).status, 200)
|
||||
|
||||
cached = self._sample_latency(alice.token, 60)
|
||||
summary = {"cached_p50_ms": round(cached["p50"], 2)}
|
||||
try:
|
||||
# 1. Valkey is a cache: auth still works, without DB-free fast path.
|
||||
compose("stop", "valkey")
|
||||
ready = common.request("GET", "/health/ready")
|
||||
self.assertEqual(
|
||||
ready.status, 200, "session cache must not be a readiness dependency"
|
||||
)
|
||||
me = common.request("GET", "/api/v1/users/me", token=alice.token)
|
||||
self.assertEqual(me.status, 200, me.json)
|
||||
sent = common.request(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
body={"text": "без кэша"},
|
||||
token=alice.token,
|
||||
)
|
||||
self.assertEqual(sent.status, 201, sent.json)
|
||||
without_cache = self._sample_latency(alice.token, 60)
|
||||
summary["cache_down_p50_ms"] = round(without_cache["p50"], 2)
|
||||
summary["cache_down_p95_ms"] = round(without_cache["p95"], 2)
|
||||
|
||||
compose("start", "valkey")
|
||||
time.sleep(3)
|
||||
self.assertEqual(common.request("GET", "/health/ready").status, 200)
|
||||
|
||||
# 2. PostgreSQL is the source of truth: bounded errors, never a 200
|
||||
# for a token the server cannot verify, and never a raw 500.
|
||||
compose("stop", "postgres")
|
||||
ready = common.request("GET", "/health/ready")
|
||||
self.assertEqual(ready.status, 503, ready.json)
|
||||
self.assertEqual(ready.json["error"]["code"], "unavailable")
|
||||
|
||||
started = time.monotonic()
|
||||
write = common.request(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
body={"text": "без базы"},
|
||||
token=alice.token,
|
||||
timeout=30,
|
||||
)
|
||||
bounded = time.monotonic() - started
|
||||
self.assertEqual(write.status, 503, write.json)
|
||||
self.assertEqual(write.json["error"]["code"], "unavailable")
|
||||
self.assertLess(bounded, 10, "database failure must fail fast")
|
||||
summary["db_down_write_seconds"] = round(bounded, 2)
|
||||
|
||||
for leaked in ("psycopg", "postgresql://", "password", "Traceback"):
|
||||
self.assertNotIn(leaked, json.dumps(write.json))
|
||||
unknown = common.request(
|
||||
"GET", "/api/v1/users/me", token="unknown-token-value", timeout=30
|
||||
)
|
||||
self.assertIn(unknown.status, (401, 503))
|
||||
self.assertNotEqual(unknown.status, 200)
|
||||
|
||||
# 3. Recovery keeps the same session and the stored chat.
|
||||
compose("start", "postgres")
|
||||
summary["recovery_seconds"] = round(wait_ready(200, 90), 2)
|
||||
after = common.request("GET", "/api/v1/chats/" + chat["id"], token=alice.token)
|
||||
self.assertEqual(after.status, 200, after.json)
|
||||
recovered = common.request(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
body={"text": "после восстановления"},
|
||||
token=alice.token,
|
||||
)
|
||||
self.assertEqual(recovered.status, 201, recovered.json)
|
||||
messages = common.history(alice.token, chat["id"])
|
||||
self.assertIn("после восстановления", [message["text"] for message in messages])
|
||||
finally:
|
||||
compose("start", "valkey", "postgres")
|
||||
try:
|
||||
wait_ready(200, 90)
|
||||
except AssertionError:
|
||||
pass
|
||||
print("\n outage summary: " + json.dumps(summary, ensure_ascii=False))
|
||||
|
||||
def _sample_latency(self, token: str, count: int) -> dict[str, float]:
|
||||
samples = []
|
||||
for _ in range(count):
|
||||
started = time.monotonic()
|
||||
response = common.request("GET", "/api/v1/users/me", token=token, timeout=30)
|
||||
samples.append(time.monotonic() - started)
|
||||
self.assertEqual(response.status, 200, response.json)
|
||||
ordered = sorted(samples)
|
||||
return {
|
||||
"p50": statistics.median(samples) * 1000,
|
||||
"p95": ordered[max(0, int(len(ordered) * 0.95) - 1)] * 1000,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Session expiry with SESSION_TTL_SECONDS=2, plus logout and bad credentials.
|
||||
|
||||
Run against the dedicated short-TTL stand:
|
||||
|
||||
scripts/ttl-stack.sh start
|
||||
BASE_URL=http://localhost:8081 python -m unittest -v test_expiry
|
||||
scripts/ttl-stack.sh stop
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import statistics
|
||||
import time
|
||||
import unittest
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import common
|
||||
|
||||
|
||||
def expires_at(session: dict) -> datetime:
|
||||
return datetime.fromisoformat(session["expires_at"][:-1] + "+00:00")
|
||||
|
||||
|
||||
class ShortTtlSessions(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
ready = common.request("GET", "/health/ready")
|
||||
if ready.status != 200:
|
||||
raise AssertionError("stand is not ready: %r" % (ready.json,))
|
||||
|
||||
def test_expiry_is_enforced_and_cache_does_not_extend_it(self) -> None:
|
||||
user = common.actor("ttl")
|
||||
started = datetime.now(timezone.utc)
|
||||
session = common.login(user.username, user.password)
|
||||
self.assertEqual(session.status, 201)
|
||||
lifetime = (expires_at(session.json) - started).total_seconds()
|
||||
self.assertLessEqual(lifetime, 5.0, "stand does not use a short TTL")
|
||||
|
||||
# Two reads: the second one is served from the Valkey cache, so the
|
||||
# expiry check below covers the cached path as well.
|
||||
for _ in range(2):
|
||||
self.assertEqual(
|
||||
common.request("GET", "/api/v1/users/me", token=session.json["token"]).status,
|
||||
200,
|
||||
)
|
||||
|
||||
time.sleep(3.2)
|
||||
expired = common.request("GET", "/api/v1/users/me", token=session.json["token"])
|
||||
common.expect_error(self, expired, 401, "unauthorized")
|
||||
self.assertTrue(expired.header("WWW-Authenticate").lower().startswith("bearer"))
|
||||
revoked = common.request(
|
||||
"DELETE", "/api/v1/auth/sessions/current", token=session.json["token"]
|
||||
)
|
||||
common.expect_error(self, revoked, 401, "unauthorized")
|
||||
|
||||
# A fresh login still works, so expiry removed only the old session.
|
||||
again = common.login(user.username, user.password)
|
||||
self.assertEqual(again.status, 201)
|
||||
self.assertEqual(
|
||||
common.request("GET", "/api/v1/users/me", token=again.json["token"]).status,
|
||||
200,
|
||||
)
|
||||
|
||||
def test_logout_is_immediate_even_when_the_session_is_cached(self) -> None:
|
||||
user = common.actor("ttllogout")
|
||||
token = user.token
|
||||
self.assertEqual(common.request("GET", "/api/v1/users/me", token=token).status, 200)
|
||||
self.assertEqual(
|
||||
common.request("DELETE", "/api/v1/auth/sessions/current", token=token).status,
|
||||
204,
|
||||
)
|
||||
outcome = common.request("GET", "/api/v1/users/me", token=token)
|
||||
common.expect_error(self, outcome, 401, "unauthorized")
|
||||
|
||||
def test_wrong_password_issues_no_session(self) -> None:
|
||||
user = common.actor("ttlwrong")
|
||||
denied = common.login(user.username, "not-the-password")
|
||||
common.expect_error(self, denied, 401, "unauthorized")
|
||||
self.assertTrue(denied.header("WWW-Authenticate").lower().startswith("basic"))
|
||||
|
||||
def test_session_lookup_latency_is_bounded(self) -> None:
|
||||
user = common.actor("ttllatency")
|
||||
samples = []
|
||||
for _ in range(30):
|
||||
started = time.monotonic()
|
||||
response = common.request("GET", "/api/v1/users/me", token=user.token, timeout=5)
|
||||
samples.append(time.monotonic() - started)
|
||||
self.assertEqual(response.status, 200)
|
||||
print(
|
||||
"\n /users/me warm cache p50=%.1fms p95=%.1fms"
|
||||
% (
|
||||
statistics.median(samples) * 1000,
|
||||
sorted(samples)[int(len(samples) * 0.95) - 1] * 1000,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Race, rollback and pool tests against the real PostgreSQL stand.
|
||||
|
||||
These are the checks a code reviewer would ask for on top of the smoke test:
|
||||
concurrent writers must not lose or duplicate messages, the username uniqueness
|
||||
must be decided by the database (not by a read-then-write check in Python), and
|
||||
a failed composite operation must leave nothing behind.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
import common
|
||||
|
||||
|
||||
class ConcurrentWrites(unittest.TestCase):
|
||||
def test_100_messages_from_10_clients_are_exactly_100(self) -> None:
|
||||
alice = common.actor("cwalice")
|
||||
bob = common.actor("cwbob")
|
||||
chat = common.create_chat(alice.token, [alice.id, bob.id], "Гонка сообщений")
|
||||
writers = 10
|
||||
per_writer = 10
|
||||
barrier = threading.Barrier(writers)
|
||||
errors: list[str] = []
|
||||
sent: list[str] = []
|
||||
lock = threading.Lock()
|
||||
|
||||
def writer(index: int) -> None:
|
||||
token = alice.token if index % 2 else bob.token
|
||||
barrier.wait()
|
||||
for number in range(per_writer):
|
||||
text = "race-%d-%d" % (index, number)
|
||||
try:
|
||||
common.send(token, chat["id"], text)
|
||||
with lock:
|
||||
sent.append(text)
|
||||
except AssertionError as error: # pragma: no cover - failure detail
|
||||
with lock:
|
||||
errors.append(str(error))
|
||||
|
||||
threads = [threading.Thread(target=writer, args=(index,)) for index in range(writers)]
|
||||
started = time.monotonic()
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join(timeout=120)
|
||||
elapsed = time.monotonic() - started
|
||||
self.assertEqual(errors, [])
|
||||
self.assertEqual(len(sent), writers * per_writer)
|
||||
|
||||
messages = common.history(alice.token, chat["id"], limit=100)
|
||||
self.assertEqual(len(messages), writers * per_writer)
|
||||
self.assertEqual(len({message["id"] for message in messages}), len(messages))
|
||||
self.assertEqual(sorted(message["text"] for message in messages), sorted(sent))
|
||||
print("\n concurrent writes: %d messages from %d clients in %.2fs"
|
||||
% (len(messages), writers, elapsed))
|
||||
|
||||
def test_duplicate_username_race_creates_one_user(self) -> None:
|
||||
registration = common.new_registration("race")
|
||||
attempts = 12
|
||||
barrier = threading.Barrier(attempts)
|
||||
statuses: list[int] = []
|
||||
lock = threading.Lock()
|
||||
|
||||
def attempt() -> None:
|
||||
barrier.wait()
|
||||
response = common.register(dict(registration))
|
||||
with lock:
|
||||
statuses.append(response.status)
|
||||
|
||||
threads = [threading.Thread(target=attempt) for _ in range(attempts)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join(timeout=60)
|
||||
self.assertEqual(statuses.count(201), 1, statuses)
|
||||
self.assertEqual(statuses.count(409), attempts - 1, statuses)
|
||||
# The single winner is usable, so exactly one row exists.
|
||||
session = common.login(registration["username"], registration["password"])
|
||||
self.assertEqual(session.status, 201)
|
||||
self.assertEqual(session.json["user"]["username"], registration["username"])
|
||||
|
||||
def test_chat_creation_rolls_back_on_unknown_member(self) -> None:
|
||||
alice = common.actor("rollback")
|
||||
before = self._chat_titles(alice.token)
|
||||
response = common.request(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
body={"title": "Атомарный чат", "member_ids": [alice.id, str(uuid.uuid4())]},
|
||||
token=alice.token,
|
||||
)
|
||||
common.expect_error(self, response, 400, "invalid_request")
|
||||
after = self._chat_titles(alice.token)
|
||||
# The chat row inserted before the failing membership step is gone.
|
||||
self.assertEqual(before, after)
|
||||
self.assertNotIn("Атомарный чат", after)
|
||||
|
||||
def _chat_titles(self, token: str) -> list[str]:
|
||||
titles: list[str] = []
|
||||
cursor = None
|
||||
for _ in range(50):
|
||||
path = "/api/v1/chats?limit=100"
|
||||
if cursor:
|
||||
path += "&cursor=" + cursor
|
||||
response = common.request("GET", path, token=token)
|
||||
self.assertEqual(response.status, 200)
|
||||
titles.extend(item["title"] for item in response.json["items"])
|
||||
cursor = response.json["next_cursor"]
|
||||
if cursor is None:
|
||||
return titles
|
||||
self.fail("chat pagination did not terminate")
|
||||
|
||||
def test_bounded_pool_serves_parallel_reads(self) -> None:
|
||||
alice = common.actor("pool")
|
||||
parallel = 50
|
||||
barrier = threading.Barrier(parallel)
|
||||
statuses: list[int] = []
|
||||
lock = threading.Lock()
|
||||
|
||||
def read() -> None:
|
||||
barrier.wait()
|
||||
# Chat lists are not cached, so this exercises the bounded SQL pool.
|
||||
response = common.request(
|
||||
"GET", "/api/v1/chats?limit=100", token=alice.token, timeout=10
|
||||
)
|
||||
with lock:
|
||||
statuses.append(response.status)
|
||||
|
||||
threads = [threading.Thread(target=read) for _ in range(parallel)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join(timeout=60)
|
||||
self.assertEqual(len(statuses), parallel)
|
||||
self.assertEqual(statuses, [200] * parallel)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user