forked from mtusi2026/mtusi2026lab3
Добавить пользовательские проверки
This commit is contained in:
@@ -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()<deadline,"PostgreSQL did not recover within 60 seconds")
|
||||
time.sleep(.5)
|
||||
c.call("GET","/api/v1/users/me",200,actor=actor,schema="User")
|
||||
print("PASS: Valkey outage fell back to PostgreSQL; PostgreSQL outage returned bounded 503 and recovered with the same session")
|
||||
|
||||
if __name__=="__main__": run(main)
|
||||
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Concurrent duplicate POSTs through LB; assert one stable message result."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import uuid
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
def main():
|
||||
args=arguments('Parallel retry test through the shared load balancer')
|
||||
base=Client(args.base_url,args.ca_file,timeout=10)
|
||||
alice,bob,eve,chat=base.bootstrap(); key='race:'+uuid.uuid4().hex
|
||||
body={'text':'Параллельная отправка'}
|
||||
def send(_):
|
||||
c=Client(args.base_url,args.ca_file,timeout=10)
|
||||
return c.call('POST',f"/api/v1/chats/{chat['id']}/messages",201,actor=alice,body=body,headers={'Idempotency-Key':key},schema='Message')
|
||||
with ThreadPoolExecutor(max_workers=16) as pool: replies=list(pool.map(send,range(32)))
|
||||
ids={r['json']['id'] for r in replies}; instances={r['headers']['X-Instance-Id'] for r in replies}
|
||||
check(len(ids)==1,'concurrent retries created more than one message')
|
||||
check(len(instances)>=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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user