add lab3
This commit is contained in:
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Один ключ одновременно через LB создаёт ровно одно сообщение."""
|
||||
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, check, run # noqa: E402
|
||||
|
||||
|
||||
def main() -> None:
|
||||
client = Client()
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
text = "concurrent idempotency " + key
|
||||
|
||||
def send(_number: int):
|
||||
return Client().message(alice, chat, text, key=key)["json"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=16) as pool:
|
||||
replies = list(pool.map(send, range(16)))
|
||||
check(all(reply == replies[0] for reply in replies), "replays returned different messages")
|
||||
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
|
||||
history = client.call("GET", path, actor=alice, schema="MessagePage")["json"]["items"]
|
||||
check(sum(message["id"] == replies[0]["id"] for message in history) == 1, "concurrent retries created duplicates")
|
||||
print("PASS: concurrent idempotency through load balancer")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Запрет БД только для api-a через pg_hba; восстановление в finally."""
|
||||
import ipaddress
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check, run
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True).strip()
|
||||
|
||||
|
||||
def sql(statement):
|
||||
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d",
|
||||
"messenger", "-v", "ON_ERROR_STOP=1", "-Atc", statement)
|
||||
|
||||
|
||||
def ready(service):
|
||||
code = """import urllib.request, urllib.error
|
||||
try:
|
||||
print(urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=7).status)
|
||||
except urllib.error.HTTPError as error:
|
||||
print(error.code)
|
||||
"""
|
||||
return compose("exec", "-T", service, "/app/.venv/bin/python", "-c", code)
|
||||
|
||||
|
||||
def main():
|
||||
client = Client()
|
||||
container = json.loads(subprocess.check_output(
|
||||
["docker", "inspect", compose("ps", "-q", "api-a")], text=True))[0]
|
||||
addresses = list(container["NetworkSettings"]["Networks"].values())
|
||||
check(len(addresses) == 1, "test expects one API network")
|
||||
address = str(ipaddress.IPv4Address(addresses[0]["IPAddress"]))
|
||||
bad_id = container["Config"]["Hostname"]
|
||||
before = {client.call("GET", "/health/live")["headers"]["X-Instance-Id"] for _ in range(40)}
|
||||
check(len(before) == 2 and bad_id in before, "both API replicas must be reachable")
|
||||
check(ready("api-a") == ready("api-b") == "200", "both APIs must be ready")
|
||||
# Сохраняем исходный pg_hba; чужую оставшуюся резервную копию не перезаписываем.
|
||||
compose("exec", "-T", "postgres", "sh", "-ec",
|
||||
'test ! -e "$PGDATA/pg_hba.conf.readiness-backup"; '
|
||||
'cp -p "$PGDATA/pg_hba.conf" "$PGDATA/pg_hba.conf.readiness-backup"')
|
||||
try:
|
||||
compose("exec", "-T", "postgres", "sh", "-ec",
|
||||
'{ printf "host all all %s/32 reject\\n" "$1"; '
|
||||
'cat "$PGDATA/pg_hba.conf.readiness-backup"; } > "$PGDATA/pg_hba.conf"',
|
||||
"sh", address)
|
||||
sql("SELECT pg_reload_conf()")
|
||||
time.sleep(0.5)
|
||||
sql(f"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE client_addr = '{address}'::inet")
|
||||
check(ready("api-a") == "503", "api-a must be unready")
|
||||
check(ready("api-b") == "200", "api-b must remain ready")
|
||||
# 2s interval + 2s check timeout, с запасом на планировщик Docker Desktop.
|
||||
time.sleep(6)
|
||||
for _ in range(40):
|
||||
result = client.call("GET", "/health/live", 200)
|
||||
check(result["headers"]["X-Instance-Id"] != bad_id, "LB selected unready api-a")
|
||||
for _ in range(20):
|
||||
result = client.call("POST", "/api/v1/users", 201, body={
|
||||
"username": "r_" + uuid.uuid4().hex[:16],
|
||||
"display_name": "Readiness regression",
|
||||
"password": "Test-password-" + uuid.uuid4().hex,
|
||||
}, schema="User")
|
||||
check(result["headers"]["X-Instance-Id"] != bad_id, "registration reached api-a")
|
||||
print("PASS: api-a ready=503, api-b ready=200; 40/40 live and 20/20 registrations use api-b")
|
||||
finally:
|
||||
compose("exec", "-T", "postgres", "sh", "-ec",
|
||||
'mv "$PGDATA/pg_hba.conf.readiness-backup" "$PGDATA/pg_hba.conf"')
|
||||
sql("SELECT pg_reload_conf()")
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
observed = {client.call("GET", "/health/live")["headers"]["X-Instance-Id"] for _ in range(10)}
|
||||
if observed == before:
|
||||
check(ready("api-a") == "200", "restored api-a must be ready")
|
||||
print("PASS: database access restored; both API replicas returned to LB")
|
||||
return
|
||||
time.sleep(0.5)
|
||||
raise AssertionError("api-a did not return to LB")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка 503 readiness при остановленном PostgreSQL."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, run # noqa: E402
|
||||
|
||||
|
||||
def main() -> None:
|
||||
Client().call("GET", "/health/ready", 503)
|
||||
print("PASS: readiness rejects unavailable PostgreSQL")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Регрессии ревью: не-ASCII Bearer и невалидная кодировка JSON через LB."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
for path in ("/api/v1/users/me", "/api/v1/auth/sessions/current"):
|
||||
method = "DELETE" if path.endswith("/current") else "GET"
|
||||
result = client.call(method, path, 401,
|
||||
headers={"Authorization": "Bearer é"}, schema="Error")
|
||||
check(result["headers"].get("WWW-Authenticate", "").startswith("Bearer"),
|
||||
"missing Bearer challenge")
|
||||
check(result["json"]["error"]["code"] == "unauthorized", "wrong error code")
|
||||
check(result["json"]["error"]["request_id"] == result["headers"]["X-Request-Id"],
|
||||
"request IDs differ")
|
||||
for raw in (b"\xff", b"{", b'{"username":'):
|
||||
result = client.call("POST", "/api/v1/users", 400, raw=raw,
|
||||
headers={"Content-Type": "application/json"}, schema="Error")
|
||||
check(result["json"]["error"]["code"] == "invalid_request", "wrong JSON error code")
|
||||
check(result["json"]["error"]["request_id"] == result["headers"]["X-Request-Id"],
|
||||
"request IDs differ")
|
||||
print("PASS: non-ASCII Bearer returns 401/challenge; malformed JSON returns contract Error/400")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка expiry; запускается при SESSION_TTL_SECONDS=2."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, check, run # noqa: E402
|
||||
|
||||
|
||||
def main() -> None:
|
||||
client = Client()
|
||||
actor = client.user("expiry")
|
||||
time.sleep(3)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
print("PASS: expired Bearer session was rejected")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user