forked from mtusi2026/mtusi2026lab2
ЛР 2: PostgreSQL, сессии Basic/Bearer, Redis-кэш, тесты и отчёт
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Недоступность зависимостей (уровень «4»). Сам останавливает и запускает контейнеры:
|
||||
python student-tests/outage.py --base-url http://localhost:8080
|
||||
|
||||
1. Redis остановлен → API работает в обход кэша (сессии читаются из PostgreSQL).
|
||||
2. PostgreSQL остановлен → защищённые запросы получают ограниченную ошибку 503,
|
||||
неизвестный токен НЕ принимается (никогда 200), /health/ready = 503.
|
||||
3. PostgreSQL запущен снова → тот же токен снова работает, данные на месте.
|
||||
"""
|
||||
import argparse
|
||||
import shlex
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from common import Api, Report
|
||||
|
||||
COMPOSE = "docker compose --env-file .env"
|
||||
|
||||
|
||||
def sh(cmd: str):
|
||||
print(f" $ {cmd}")
|
||||
subprocess.run(shlex.split(cmd), check=True, stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def wait_ready(api: Api, seconds=90):
|
||||
deadline = time.time() + seconds
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
if api.raw("GET", "/health/ready", timeout=3)[0] == 200:
|
||||
return True
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--stop-redis", default=f"{COMPOSE} stop redis")
|
||||
ap.add_argument("--start-redis", default=f"{COMPOSE} start redis")
|
||||
ap.add_argument("--stop-db", default=f"{COMPOSE} stop postgres")
|
||||
ap.add_argument("--start-db", default=f"{COMPOSE} start postgres")
|
||||
args = ap.parse_args()
|
||||
api, r = Api(args.base_url), Report()
|
||||
|
||||
user = api.new_user("outage")
|
||||
st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "outage", "member_ids": [user["id"]]}, token=user["token"])
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
api.call("POST", path, {"text": "before outage"}, token=user["token"])
|
||||
|
||||
print("== 1. Redis недоступен ==")
|
||||
sh(args.stop_redis)
|
||||
try:
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token=user["token"])
|
||||
r.check(st == 200, "valid token still works without Redis (cache bypassed)")
|
||||
st, _, _ = api.call("POST", path, {"text": "without redis"}, token=user["token"])
|
||||
r.check(st == 201, "writes still work without Redis")
|
||||
fresh = api.register("noredis")
|
||||
st, sess, _ = api.login(fresh["username"], fresh["password"])
|
||||
r.check(st == 201, "login works without Redis")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token="forged-" + uuid.uuid4().hex)
|
||||
r.check(st == 401, "forged token still rejected without Redis")
|
||||
finally:
|
||||
sh(args.start_redis)
|
||||
|
||||
print("== 2. PostgreSQL недоступен ==")
|
||||
sh(args.stop_db)
|
||||
try:
|
||||
time.sleep(1)
|
||||
st, _, _ = api.call("GET", path, token=user["token"])
|
||||
r.check(st == 503, f"history without DB -> 503, not a hang (got {st})")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token="forged-" + uuid.uuid4().hex)
|
||||
r.check(st in (401, 503), f"unknown token is never trusted without DB (got {st})")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me")
|
||||
r.check(st == 401, "anonymous request -> 401")
|
||||
st = api.raw("GET", "/health/ready")[0]
|
||||
r.check(st == 503, "/health/ready -> 503")
|
||||
st = api.raw("GET", "/health/live")[0]
|
||||
r.check(st == 200, "/health/live -> 200 (process is alive)")
|
||||
finally:
|
||||
sh(args.start_db)
|
||||
|
||||
print("== 3. восстановление ==")
|
||||
r.check(wait_ready(api), "/health/ready back to 200")
|
||||
st, page, _ = api.call("GET", path, token=user["token"])
|
||||
texts = [m["text"] for m in (page or {}).get("items", [])]
|
||||
r.check(st == 200 and "before outage" in texts and "without redis" in texts,
|
||||
"same token reads the same history after DB is back")
|
||||
r.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user