Реализована лабораторная 2 на оценку 4

This commit is contained in:
MacBook
2026-10-02 15:41:42 +03:00
parent 65003b6119
commit 6534f4de68
22 changed files with 1516 additions and 30 deletions
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Stop Redis and PostgreSQL separately and check bounded API failures."""
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check # noqa: E402
def compose(*args):
subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT,
check=True, stdout=subprocess.DEVNULL)
def wait_ready(client, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
time.sleep(0.5)
raise Failure("stack did not recover")
def main():
client = Client(timeout=5)
actor = client.user("dependency")
try:
compose("stop", "redis")
client.call("GET", "/health/ready", 503)
client.call("GET", "/api/v1/users/me", 503, actor=actor)
client.call("GET", "/api/v1/users/me", 401)
finally:
compose("start", "redis")
wait_ready(client)
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
try:
compose("stop", "postgres")
client.call("GET", "/health/ready", 503)
client.call("GET", "/api/v1/users/me", 503, actor=actor)
finally:
compose("start", "postgres")
wait_ready(client)
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
print("PASS: Redis/PostgreSQL failures returned 503; anonymous access stayed 401; state recovered")
if __name__ == "__main__":
try:
main()
except (Failure, OSError, subprocess.CalledProcessError) as exc:
print("FAIL:", exc)
raise SystemExit(1)
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env python3
"""Recreate the API with a two-second session TTL and prove expiry."""
import os
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check # noqa: E402
def compose(env, *args):
subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT,
env=env, check=True, stdout=subprocess.DEVNULL)
def wait_ready(timeout=60):
client = Client(timeout=2)
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
client.call("GET", "/health/ready", schema="Health")
return
except Failure:
time.sleep(0.5)
raise Failure("API did not become ready")
def main():
normal_env = dict(os.environ)
normal_env.pop("SESSION_TTL_SECONDS", None)
short_env = dict(normal_env)
short_env["SESSION_TTL_SECONDS"] = "2"
try:
compose(short_env, "up", "-d", "--force-recreate", "--no-deps", "--wait", "api")
wait_ready()
client = Client()
actor = client.user("expiry")
time.sleep(3)
client.call("GET", "/api/v1/users/me", 401, actor=actor)
print("PASS: two-second Redis session expired and was rejected")
finally:
compose(normal_env, "up", "-d", "--force-recreate", "--no-deps", "--wait", "api")
wait_ready()
if __name__ == "__main__":
try:
main()
except (Failure, OSError, subprocess.CalledProcessError) as exc:
print("FAIL:", exc)
raise SystemExit(1)
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Black-box checks for the grade 4 registration, transaction and auth cases."""
import base64
import concurrent.futures
import sys
import threading
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, arguments, check, run # noqa: E402
def basic(username, password):
raw = (username + ":" + password).encode("utf-8")
return {"Authorization": "Basic " + base64.b64encode(raw).decode("ascii")}
def main():
args = arguments("Grade 4 API checks")
base = Client(args.base_url, args.ca_file)
suffix = uuid.uuid4().hex[:12]
username = "race_" + suffix
password = "Race-password-" + uuid.uuid4().hex
registration = {"username": username, "display_name": "Гонка регистрации", "password": password}
workers = 4
barrier = threading.Barrier(workers)
def register(_):
client = Client(args.base_url, args.ca_file)
barrier.wait()
return client.call("POST", "/api/v1/users", [201, 409], body=registration)["status"]
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
statuses = list(pool.map(register, range(workers)))
check(statuses.count(201) == 1 and statuses.count(409) == workers - 1,
"concurrent registration must create exactly one user")
base.call("POST", "/api/v1/auth/sessions", 401,
headers=basic(username, "definitely-wrong-password"))
session = base.call("POST", "/api/v1/auth/sessions", 201,
headers=basic(username, password), schema="Session")["json"]
actor = {"id": session["user"]["id"], "token": session["token"]}
title = "rollback-" + suffix
base.call("POST", "/api/v1/chats", 400, actor=actor,
body={"title": title, "member_ids": [actor["id"], str(uuid.uuid4())]})
page = base.call("GET", "/api/v1/chats?limit=100", actor=actor, schema="ChatPage")["json"]
check(all(chat["title"] != title for chat in page["items"]),
"failed composite operation left a visible chat")
base.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=actor)
base.call("GET", "/api/v1/users/me", 401, actor=actor)
print("PASS: registration race, transaction rollback, bad password and logout")
if __name__ == "__main__":
run(main)