Lab 3: solution for grade 3 - BPI2304 Vardanyan

This commit is contained in:
garik
2026-11-16 22:10:49 +03:00
parent 0ab3a341aa
commit 0b6edebfc0
17 changed files with 937 additions and 169 deletions
+41
View File
@@ -0,0 +1,41 @@
"""Additional lab3 end-to-end test; requires ORIGINAL skeleton's tests/client.py.
Creates one chat and posts an identical message 12 times through the load balancer.
"""
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import sys
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, arguments, check, run
def main():
args = arguments("Concurrent Idempotency-Key test for two replicas")
initial = Client(args.base_url, args.ca_file)
alice, bob, _, chat = initial.bootstrap()
key = uuid.uuid4().hex
text = "Один текст от параллельных реплик " + key
path = "/api/v1/chats/" + chat["id"] + "/messages"
def send_one(_index):
client = Client(args.base_url, args.ca_file)
response = client.call("POST", path, 201, actor=alice, body={"text": text},
headers={"Idempotency-Key": key}, schema="Message")
return response["json"], response["headers"]["X-Instance-Id"]
with ThreadPoolExecutor(max_workers=12) as executor:
replies = list(executor.map(send_one, range(12)))
ids = {row["id"] for row, _ in replies}
check(len(ids) == 1, "different message IDs returned for one key")
check(all(row == replies[0][0] for row, _ in replies), "different responses for one key")
messages = initial.call("GET", path, actor=bob, schema="MessagePage")["json"]["items"]
check(len([m for m in messages if m["text"] == text]) == 1,
"duplicate in PostgreSQL message history")
instances = {inst for _, inst in replies}
print("PASS: 12 concurrent same-key POSTs => one durable message; observed instances:",
", ".join(sorted(instances)))
if __name__ == "__main__":
run(main)
+72
View File
@@ -0,0 +1,72 @@
"""Fast pure-function checks; can run even without a local PostgreSQL/Docker install."""
import base64
from datetime import datetime, timezone
import importlib
import json
import sys
import types
import unittest
import uuid
try:
import psycopg # noqa: F401
except ImportError:
pg = types.ModuleType("psycopg")
pg.OperationalError = type("OperationalError", (Exception,), {})
pg.errors = types.SimpleNamespace(
UniqueViolation=type("UniqueViolation", (Exception,), {}),
QueryCanceled=type("QueryCanceled", (Exception,), {}),
)
sys.modules["psycopg"] = pg
rows = types.ModuleType("psycopg.rows")
rows.dict_row = lambda *args: None
sys.modules["psycopg.rows"] = rows
import server
class HelpersTest(unittest.TestCase):
def test_password_kdf(self):
h1 = server.password_hash("test-pass-123456789")
h2 = server.password_hash("test-pass-123456789")
self.assertNotEqual(h1, h2)
self.assertTrue(server.password_matches("test-pass-123456789", h1))
self.assertFalse(server.password_matches("WRONG", h1))
def test_uuid(self):
value = str(uuid.uuid4())
self.assertEqual(server.uuid_string(value), value)
for invalid in ("abc", None, value.upper()):
with self.assertRaises(server.ApiError):
server.uuid_string(invalid)
def test_cursor_page(self):
scope = "messages:" + str(uuid.uuid4())
a, b = str(uuid.uuid4()), str(uuid.uuid4())
items = [{"id": x, "created_at": "2026-11-16T12:00:00.000001Z"} for x in [a, b]]
result = server.next_page(items, 1, scope)
self.assertEqual(len(result["items"]), 1)
self.assertIsNotNone(result["next_cursor"])
limit, position = server.pagination({"limit": ["1"], "cursor": [result["next_cursor"]]}, scope)
self.assertEqual(limit, 1)
self.assertEqual(position[1], a)
self.assertEqual(position[0], datetime(2026, 11, 16, 12, 0, 0, 1, tzinfo=timezone.utc))
with self.assertRaises(server.ApiError):
server.pagination({"cursor": [result["next_cursor"]]}, "messages:another-chat")
def test_limits(self):
with self.assertRaises(server.ApiError):
server.pagination({"limit": ["0"]}, "chats:alice")
with self.assertRaises(server.ApiError):
server.pagination({"limit": ["101"]}, "chats:alice")
with self.assertRaises(server.ApiError):
server.require_fields({"text": "hi", "extra": "no"}, {"text"})
def test_keys(self):
self.assertTrue(server.IDEMPOTENCY_RE.fullmatch("aB12_:-.z"))
self.assertFalse(server.IDEMPOTENCY_RE.fullmatch("bad key"))
self.assertFalse(server.IDEMPOTENCY_RE.fullmatch(""))
if __name__ == "__main__":
unittest.main()