From 73e45f60f7b88fda1b0ad8bd3045666c90295f10 Mon Sep 17 00:00:00 2001 From: koichakaev <52+koichakaev@noreply.gitea.privcloud.tech> Date: Fri, 6 Nov 2026 19:13:01 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0=D1=82?= =?UTF-8?q?=D0=B5=D0=BB=D1=8C=D1=81=D0=BA=D0=B8=D0=B5=20=D0=BF=D1=80=D0=BE?= =?UTF-8?q?=D0=B2=D0=B5=D1=80=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- student-tests/dependencies.py | 50 ++++++++++++++++++++++++++++ student-tests/idempotency_race.py | 23 +++++++++++++ student-tests/quality.py | 54 +++++++++++++++++++++++++++++++ student-tests/session_ttl.py | 20 ++++++++++++ 4 files changed, 147 insertions(+) create mode 100644 student-tests/dependencies.py create mode 100644 student-tests/idempotency_race.py create mode 100644 student-tests/quality.py create mode 100644 student-tests/session_ttl.py diff --git a/student-tests/dependencies.py b/student-tests/dependencies.py new file mode 100644 index 00000000..4b6f782f --- /dev/null +++ b/student-tests/dependencies.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""Stop/start Valkey and PostgreSQL with volumes preserved; verify bounded failures and recovery.""" +import subprocess +import time + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) + +from client import Client, Failure, arguments, check, run + +ROOT = Path(__file__).resolve().parents[1] + +def compose(action, service): + subprocess.run(["docker", "compose", "--env-file", ".env", action, service], cwd=ROOT, + check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + +def main(): + args=arguments("Check session fallback and database dependency failure") + c=Client(args.base_url,args.ca_file,timeout=8) + actor=c.user("dependency") + + compose("stop","valkey") + try: + c.call("GET","/health/ready",200,schema="Health") + me=c.call("GET","/api/v1/users/me",200,actor=actor,schema="User")["json"] + check(me["id"]==actor["id"],"session failed while Valkey was down") + finally: + compose("start","valkey") + + compose("stop","postgres") + try: + c.call("GET","/health/ready",503) + c.call("GET","/api/v1/users/me",503,actor=actor) + finally: + compose("start","postgres") + + deadline=time.monotonic()+60 + while True: + try: + c.call("GET","/health/ready",200,schema="Health") + break + except Failure: + check(time.monotonic()=2,'test did not observe requests served by two API replicas') + history=base.call('GET',f"/api/v1/chats/{chat['id']}/messages?limit=100",actor=bob,schema='MessagePage')['json']['items'] + check(sum(m['id'] in ids for m in history)==1,'message is not visible exactly once through LB') + print(f'PASS: 32 concurrent retries, one message, {len(instances)} API instances observed') + +if __name__=='__main__': run(main) diff --git a/student-tests/quality.py b/student-tests/quality.py new file mode 100644 index 00000000..021a1ee0 --- /dev/null +++ b/student-tests/quality.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Level-4 checks: concurrent unique registration and atomic chat creation.""" +import concurrent.futures +import json +import os +import subprocess +import uuid + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) + +from client import Client, Failure, arguments, check, run + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +def db_count(table): + # Fixed table allowlist: user input is never interpolated here. + assert table in {"users", "chats", "chat_members", "messages"} + output = subprocess.run(["docker", "compose", "--env-file", ".env", "exec", "-T", "postgres", + "psql", "-X", "-U", "messenger", "-d", "messenger", "-At", "-c", + "SELECT count(*) FROM " + table], cwd=ROOT, check=True, text=True, + stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout + return int(output.strip()) + +def main(): + args = arguments("Check registration race and transaction rollback") + c = Client(args.base_url, args.ca_file) + alice, bob, _, _ = c.bootstrap() + username = "race_" + uuid.uuid4().hex[:16] + body = {"username": username, "display_name": "Гонка регистрации", "password": "Test-password-" + uuid.uuid4().hex} + def register(_): + try: + return c.call("POST", "/api/v1/users", [201, 409], body=body)["status"] + except Failure: + raise + with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool: + statuses = list(pool.map(register, range(12))) + check(statuses.count(201) == 1 and statuses.count(409) == 11, + "username race must create exactly one user and return 409 to all other requests") + before = db_count("chats") + after = c.call("POST", "/api/v1/chats", 400, actor=alice, + body={"title": "rollback probe", "member_ids": [alice["id"], str(uuid.uuid4())]}) + check(after["status"] == 400 and db_count("chats") == before, + "invalid multi-step chat creation left a partial chat row") + plan = subprocess.run(["docker", "compose", "--env-file", ".env", "exec", "-T", "postgres", + "psql", "-X", "-U", "messenger", "-d", "messenger", "-At", "-c", + "EXPLAIN (ANALYZE, BUFFERS) SELECT id FROM messages WHERE chat_id=md5('chat-0')::uuid ORDER BY created_at,id LIMIT 50"], + cwd=ROOT, check=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.splitlines() + print(json.dumps({"registration_race": {"201": statuses.count(201), "409": statuses.count(409)}, + "chat_rollback": "PASS", "history_index_plan": plan}, ensure_ascii=False, indent=2)) + +if __name__ == "__main__": run(main) diff --git a/student-tests/session_ttl.py b/student-tests/session_ttl.py new file mode 100644 index 00000000..d13a9f20 --- /dev/null +++ b/student-tests/session_ttl.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +"""Run only with SESSION_TTL_SECONDS=2 in the Compose environment.""" +import time +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) + +from client import Client, Failure, arguments, check, run + +def main(): + args=arguments("Check persisted session expiry with a short TTL") + c=Client(args.base_url,args.ca_file) + actor=c.user("ttl") + c.call("GET","/api/v1/users/me",200,actor=actor,schema="User") + time.sleep(2.2) + c.call("GET","/api/v1/users/me",401,actor=actor) + print("PASS: session expired at the configured two-second TTL") + +if __name__=="__main__": run(main)