forked from mtusi2026/mtusi2026lab4
перенос основы 3 лабы
This commit is contained in:
@@ -0,0 +1,314 @@
|
||||
"""Проверки уровня 4 в отдельном Compose project с синтетическими данными."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import urlopen
|
||||
from uuid import uuid4
|
||||
|
||||
from helpers import Client, ROOT
|
||||
from client import Failure
|
||||
from resilience import history
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.check_output(["docker", *args], text=True, timeout=180).strip()
|
||||
|
||||
|
||||
def main():
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
project = "lab3-check-" + uuid4().hex[:10]
|
||||
base = f"http://127.0.0.1:{port}"
|
||||
env = dict(os.environ, COMPOSE_PROJECT_NAME=project, HOST_PORT=str(port),
|
||||
API_REPLICAS="2", SESSION_TTL_SECONDS="3600", BASE_URL=base)
|
||||
result = {"utc": datetime.now(timezone.utc).isoformat(), "project": project,
|
||||
"base_url": base, "host": platform.system() + " " + platform.machine(),
|
||||
"docker": docker("info", "--format", "{{.ServerVersion}} {{.Architecture}} CPUs={{.NCPU}} RAM={{.MemTotal}}"),
|
||||
"commit": docker("compose", "version", "--short"),
|
||||
"profile": {"workers": 4, "pause_seconds": 0.05, "operation": "POST message then GET history, same-key retry after uncertain POST"}}
|
||||
result["compose_version"] = result.pop("commit")
|
||||
result["source_commit"] = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip()
|
||||
result["working_tree"] = True
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, env=env, text=True, timeout=180).strip()
|
||||
|
||||
def script(name):
|
||||
subprocess.run([str(ROOT / "scripts" / name)], cwd=ROOT, env=env, check=True, timeout=240)
|
||||
|
||||
def inspect_all():
|
||||
ids = compose("ps", "-a", "-q").split()
|
||||
return json.loads(docker("inspect", *ids))
|
||||
|
||||
def apis():
|
||||
return [i for i in inspect_all() if i["Config"]["Labels"]["com.docker.compose.service"] == "api"]
|
||||
|
||||
def metadata(info):
|
||||
return {"id": info["Id"], "instance": info["Config"]["Hostname"],
|
||||
"service": info["Config"]["Labels"]["com.docker.compose.service"],
|
||||
"image": info["Image"], "started_at": info["State"]["StartedAt"],
|
||||
"running": info["State"]["Running"], "exit_code": info["State"]["ExitCode"],
|
||||
"memory_bytes": info["HostConfig"]["Memory"], "nano_cpus": info["HostConfig"]["NanoCpus"],
|
||||
"published_ports": info["HostConfig"]["PortBindings"],
|
||||
"mounts": [{"type": m["Type"], "destination": m["Destination"], "name": m.get("Name")} for m in info["Mounts"]]}
|
||||
|
||||
def sql(query):
|
||||
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-c", query)
|
||||
|
||||
def check_shutdown():
|
||||
info = apis()[0]
|
||||
# Внутреннее подключение через docker exec не публикует порт API на хост.
|
||||
pending_code = """import socket,time
|
||||
s=socket.create_connection(('127.0.0.1',8080),timeout=2)
|
||||
s.sendall(b'POST /api/v1/users HTTP/1.1\\r\\nHost: localhost\\r\\nContent-Type: application/json\\r\\nContent-Length: 1000\\r\\nExpect: 100-continue\\r\\n\\r\\n')
|
||||
assert b'100 Continue' in s.recv(1024)
|
||||
s.sendall(b'{"username":')
|
||||
print('pending',flush=True)
|
||||
time.sleep(30)
|
||||
"""
|
||||
pending = subprocess.Popen(["docker", "exec", info["Id"], "python", "-u", "-c", pending_code],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
try:
|
||||
assert pending.stdout.readline().strip() == "pending"
|
||||
started = time.monotonic()
|
||||
docker("kill", "--signal=TERM", info["Id"])
|
||||
first_refusal = None
|
||||
while True:
|
||||
state = json.loads(docker("inspect", info["Id"]))[0]["State"]
|
||||
if not state["Running"]:
|
||||
break
|
||||
assert time.monotonic() - started < 8
|
||||
probe = subprocess.run(["docker", "exec", info["Id"], "python", "-c",
|
||||
"import socket; s=socket.socket(); s.settimeout(.2); raise SystemExit(s.connect_ex(('127.0.0.1',8080)))"],
|
||||
capture_output=True, timeout=3)
|
||||
if probe.returncode and first_refusal is None:
|
||||
first_refusal = time.monotonic() - started
|
||||
time.sleep(0.1)
|
||||
elapsed = time.monotonic() - started
|
||||
assert first_refusal is not None and first_refusal < elapsed < 8
|
||||
assert state["ExitCode"] == 0 and not state["OOMKilled"]
|
||||
logs = subprocess.run(["docker", "logs", info["Id"]], capture_output=True, text=True, check=True)
|
||||
assert "Application shutdown complete" in logs.stdout + logs.stderr
|
||||
result["sigterm"] = {"instance": info["Config"]["Hostname"], "unfinished_request": True,
|
||||
"shutdown_seconds": round(elapsed, 3), "new_connections_refused_seconds": round(first_refusal, 3),
|
||||
"exit_code": state["ExitCode"], "oom_killed": state["OOMKilled"]}
|
||||
print("PASS: SIGTERM with unfinished request:", json.dumps(result["sigterm"]), flush=True)
|
||||
finally:
|
||||
pending.communicate(timeout=10)
|
||||
compose("start", "api")
|
||||
script("wait-ready.sh")
|
||||
|
||||
def load_action(label, action, target=None):
|
||||
client = Client(base, timeout=2)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
original = client.message(alice, chat, "До воздействия")["json"]
|
||||
stop = threading.Event()
|
||||
lock = threading.Lock()
|
||||
successes, errors, confirmed = [], [], {}
|
||||
started = time.monotonic()
|
||||
|
||||
def worker(index):
|
||||
c = Client(base, timeout=2)
|
||||
key = uuid4().hex
|
||||
while not stop.is_set():
|
||||
for method in ("POST", "GET"):
|
||||
try:
|
||||
if method == "POST":
|
||||
response = c.message(alice, chat, "load-" + key, key=key)
|
||||
with lock:
|
||||
confirmed[response["json"]["id"]] = response["json"]
|
||||
key = uuid4().hex
|
||||
else:
|
||||
response = c.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100",
|
||||
actor=bob, schema="MessagePage")
|
||||
with lock:
|
||||
successes.append((time.monotonic() - started, method,
|
||||
response["headers"]["X-Instance-Id"], response["elapsed"]))
|
||||
except Failure as exc:
|
||||
with lock:
|
||||
errors.append((time.monotonic() - started, method, str(exc)))
|
||||
stop.wait(0.05)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
futures = [pool.submit(worker, i) for i in range(4)]
|
||||
time.sleep(1)
|
||||
action_start = time.monotonic() - started
|
||||
try:
|
||||
action_info = action()
|
||||
action_end = time.monotonic() - started
|
||||
# Охватывает обнаружение отказа и устойчивую работу после него.
|
||||
time.sleep(max(3, 15 - (action_end - action_start)))
|
||||
finally:
|
||||
stop.set()
|
||||
for future in futures:
|
||||
future.result()
|
||||
elapsed = time.monotonic() - started
|
||||
items = history(client, bob, chat)
|
||||
by_id = {m["id"]: m for m in items}
|
||||
assert len(items) == len(by_id) == len({m["text"] for m in items}), "Повтор создал дубль"
|
||||
assert by_id.get(original["id"]) == original
|
||||
assert all(by_id.get(mid) == msg for mid, msg in confirmed.items()), "Потеря подтверждённого сообщения"
|
||||
after = [s for s in successes if s[0] >= action_end]
|
||||
assert {s[1] for s in after} == {"POST", "GET"}, "Нет чтений/записей после воздействия"
|
||||
recovery = {method: round(min(s[0] for s in successes if s[0] >= action_start and s[1] == method) - action_start, 3)
|
||||
for method in ("POST", "GET")}
|
||||
assert max(recovery.values()) <= 10, recovery
|
||||
max_gap = {}
|
||||
for method in ("POST", "GET"):
|
||||
moments = sorted(s[0] for s in successes if s[1] == method)
|
||||
max_gap[method] = round(max(b - a for a, b in zip(moments, moments[1:])), 3)
|
||||
assert max(max_gap.values()) <= 10, max_gap
|
||||
if target:
|
||||
assert target not in {s[2] for s in after[-20:]}, "Остановленная реплика ещё отвечает"
|
||||
buckets = []
|
||||
for second in range(int(elapsed) + 1):
|
||||
buckets.append({"second": second, "successes": sum(second <= s[0] < second + 1 for s in successes),
|
||||
"errors": sum(second <= e[0] < second + 1 for e in errors)})
|
||||
latencies = sorted(s[3] * 1000 for s in successes)
|
||||
summary = {"label": label, "duration_seconds": round(elapsed, 3), "successful_requests": len(successes),
|
||||
"successful_writes": len(confirmed), "errors": len(errors), "successful_rps": round(len(successes) / elapsed, 2),
|
||||
"first_success_after_action_seconds": recovery, "maximum_success_gap_seconds": max_gap,
|
||||
"action_start_seconds": round(action_start, 3), "action_end_seconds": round(action_end, 3),
|
||||
"p50_ms": round(latencies[len(latencies) // 2], 3),
|
||||
"p95_ms": round(latencies[int(len(latencies) * .95)], 3),
|
||||
"confirmed_data_preserved": True, "duplicate_messages": 0,
|
||||
"instances": sorted({s[2] for s in successes}), "per_second": buckets,
|
||||
"error_samples": errors[:5], "action": action_info}
|
||||
print(json.dumps({k: v for k, v in summary.items() if k not in ("per_second", "error_samples", "action")}, ensure_ascii=False), flush=True)
|
||||
return summary
|
||||
|
||||
print("Command: ./scripts/check-docker.sh; project:", project, flush=True)
|
||||
print("Docker:", result["docker"], flush=True)
|
||||
try:
|
||||
script("start.sh")
|
||||
initial = inspect_all()
|
||||
result["containers"] = [metadata(info) for info in initial]
|
||||
assert len(apis()) == 2
|
||||
for info in initial:
|
||||
assert info["HostConfig"]["Memory"] > 0 and info["HostConfig"]["NanoCpus"] > 0
|
||||
if info["Config"]["Labels"]["com.docker.compose.service"] != "lb":
|
||||
assert not info["HostConfig"]["PortBindings"]
|
||||
for info in apis():
|
||||
assert docker("exec", info["Id"], "id", "-u") == "10001"
|
||||
assert all(m["Destination"].startswith("/run/secrets/") for m in info["Mounts"])
|
||||
print("PASS: 2 real API containers, CPU/RAM limits, API non-root and no public ports; only LB published", flush=True)
|
||||
subprocess.run([str(ROOT / "scripts/check.sh")], cwd=ROOT, env=env, check=True, timeout=240)
|
||||
result["api_tests"] = "public smoke + 28 student tests passed"
|
||||
subprocess.run([str(ROOT / "scripts/demo.sh")], cwd=ROOT, env=env, check=True, stdout=subprocess.DEVNULL, timeout=30)
|
||||
assert sql("SELECT count(*) FROM schema_migrations") == "2"
|
||||
count = sql("SELECT count(*) FROM messages")
|
||||
for _ in range(2):
|
||||
compose("run", "--rm", "migrate")
|
||||
assert sql("SELECT count(*) FROM schema_migrations") == "2"
|
||||
assert sql("SELECT count(*) FROM messages") == count
|
||||
print("PASS: migrations only in one-shot service; repeated execution preserves data", flush=True)
|
||||
|
||||
replay_client = Client(base)
|
||||
replay_actor, _, _, replay_chat = replay_client.bootstrap()
|
||||
replay_key = uuid4().hex
|
||||
saved_message = replay_client.message(replay_actor, replay_chat, "Повтор после рестарта", key=replay_key)["json"]
|
||||
before = {i["Id"]: metadata(i) for i in inspect_all() if i["State"]["Running"]}
|
||||
subprocess.run(["make", "test-persistence", "PYTHON=" + sys.executable, "ACTION_SCRIPT=scripts/restart.sh"],
|
||||
cwd=ROOT, env=env, check=True, timeout=180)
|
||||
after = {i["Id"]: metadata(i) for i in inspect_all() if i["State"]["Running"]}
|
||||
assert before.keys() == after.keys()
|
||||
assert all(before[cid]["started_at"] != after[cid]["started_at"] for cid in before)
|
||||
assert replay_client.message(replay_actor, replay_chat, "Повтор после рестарта", key=replay_key)["json"] == saved_message
|
||||
result["persistence"] = {"before": list(before.values()), "after": list(after.values()), "passed": True,
|
||||
"idempotency_replay_after_restart": True}
|
||||
print("PASS: both API, LB, PostgreSQL, Valkey actually restarted; session and confirmed data preserved", flush=True)
|
||||
|
||||
check_shutdown()
|
||||
|
||||
dependency_client = Client(base)
|
||||
actor = dependency_client.user("deps")
|
||||
result["dependency_readiness"] = []
|
||||
for dependency in ("valkey", "postgres"):
|
||||
try:
|
||||
compose("stop", "--timeout", "8", dependency)
|
||||
probe_id = apis()[0]["Id"]
|
||||
readiness = subprocess.run(["docker", "exec", probe_id, "python", "-m", "src.healthcheck"], capture_output=True, timeout=10)
|
||||
assert readiness.returncode == 1
|
||||
live = docker("exec", probe_id, "python", "-c",
|
||||
"from urllib.request import urlopen; print(urlopen('http://127.0.0.1:8080/health/live').status)")
|
||||
assert live == "200"
|
||||
deadline = time.monotonic() + 8
|
||||
while True:
|
||||
try:
|
||||
urlopen(base + "/health/ready", timeout=2).close()
|
||||
except HTTPError as error:
|
||||
if error.code == 503:
|
||||
break
|
||||
raise
|
||||
except OSError:
|
||||
# Уже отправленный запрос может истечь до исключения backend.
|
||||
pass
|
||||
assert time.monotonic() < deadline
|
||||
time.sleep(0.1)
|
||||
result["dependency_readiness"].append({"dependency": dependency, "api_live": 200, "api_ready": 503, "lb_ready": 503})
|
||||
print("PASS:", dependency, "outage: API live=200, ready=503, LB ready=503", flush=True)
|
||||
finally:
|
||||
compose("start", dependency)
|
||||
script("wait-ready.sh")
|
||||
dependency_client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
|
||||
subprocess.run(["make", "test-failover", "PYTHON=" + sys.executable, "ACTION_SCRIPT=scripts/stop-one.sh"],
|
||||
cwd=ROOT, env=env, check=True, timeout=90)
|
||||
assert sum(i["State"]["Running"] for i in apis()) == 1
|
||||
result["public_failover"] = {"passed": True, "containers_after": [metadata(i) for i in apis()]}
|
||||
compose("start", "api")
|
||||
script("wait-ready.sh")
|
||||
|
||||
result["failovers"] = []
|
||||
for info in apis():
|
||||
target = info["Config"]["Hostname"]
|
||||
|
||||
def stop_target():
|
||||
subprocess.run([str(ROOT / "scripts/stop-one.sh")], cwd=ROOT,
|
||||
env=dict(env, TARGET_INSTANCE_ID=target), check=True, timeout=10)
|
||||
stopped = json.loads(docker("inspect", info["Id"]))[0]
|
||||
assert not stopped["State"]["Running"]
|
||||
assert not stopped["State"]["OOMKilled"] and stopped["State"]["ExitCode"] == 0
|
||||
# Uvicorn пишет в stderr; получаем оба потока без вывода запросов.
|
||||
logs_result = subprocess.run(["docker", "logs", info["Id"]], capture_output=True, text=True, check=True)
|
||||
assert "Application shutdown complete" in logs_result.stdout + logs_result.stderr
|
||||
return metadata(stopped)
|
||||
|
||||
result["failovers"].append(load_action("stop " + target, stop_target, target))
|
||||
compose("start", "api")
|
||||
script("wait-ready.sh")
|
||||
|
||||
before = {i["Id"]: metadata(i) for i in inspect_all() if i["State"]["Running"]}
|
||||
|
||||
def replace():
|
||||
script("rolling-update.sh")
|
||||
after = {i["Id"]: metadata(i) for i in inspect_all() if i["State"]["Running"]}
|
||||
old_api = {i["id"] for i in before.values() if i["service"] == "api"}
|
||||
new_api = {i["id"] for i in after.values() if i["service"] == "api"}
|
||||
assert len(new_api) == 2 and not old_api & new_api
|
||||
for cid, info in before.items():
|
||||
if info["service"] != "api":
|
||||
assert after[cid]["started_at"] == info["started_at"]
|
||||
return {"before": list(before.values()), "after": list(after.values())}
|
||||
|
||||
result["rolling_update"] = load_action("sequential API replacement", replace)
|
||||
result["passed"] = True
|
||||
print("PASS: all lab3 grade-4 checks completed", flush=True)
|
||||
finally:
|
||||
output = ROOT / "evidence" / "lab3-checks.json"
|
||||
output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
|
||||
compose("down", "--volumes", "--timeout", "8")
|
||||
print("Removed only temporary test containers and volumes:", project, flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,42 @@
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
from urllib.parse import urlencode
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client
|
||||
|
||||
|
||||
class ApiTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.client = Client()
|
||||
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
|
||||
self.path = "/api/v1/chats/" + self.chat["id"]
|
||||
|
||||
def assert_error(self, method, path, status, code, **kwargs):
|
||||
if method == "POST" and path.endswith("/messages"):
|
||||
kwargs["headers"] = {"Idempotency-Key": uuid4().hex, **kwargs.get("headers", {})}
|
||||
result = self.client.call(method, path, status, **kwargs)
|
||||
self.assertEqual(result["json"]["error"]["code"], code)
|
||||
return result["json"]["error"]
|
||||
|
||||
def read_all(self, path, actor, schema, limit=3):
|
||||
items = []
|
||||
cursor = None
|
||||
seen_cursors = set()
|
||||
while True:
|
||||
query = {"limit": limit}
|
||||
if cursor is not None:
|
||||
query["cursor"] = cursor
|
||||
page = self.client.call("GET", path + "?" + urlencode(query), actor=actor, schema=schema)["json"]
|
||||
self.assertLessEqual(len(page["items"]), limit)
|
||||
items.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return items
|
||||
self.assertTrue(page["items"], "Пустая страница не должна вести к следующей")
|
||||
self.assertNotIn(cursor, seen_cursors, "Зацикливание пагинации")
|
||||
seen_cursors.add(cursor)
|
||||
@@ -0,0 +1,164 @@
|
||||
import base64
|
||||
import json
|
||||
from urllib.parse import urlencode
|
||||
from uuid import uuid4
|
||||
|
||||
from helpers import ApiTestCase
|
||||
|
||||
|
||||
class ApiTests(ApiTestCase):
|
||||
def test_duplicate_username(self):
|
||||
self.assert_error("POST", "/api/v1/users", 409, "conflict", body=self.alice["registration"])
|
||||
|
||||
def test_invalid_user_fields(self):
|
||||
invalid_bodies = [
|
||||
{}, [], None,
|
||||
{"username": "ab", "display_name": "Имя"},
|
||||
{"username": "UPPER", "display_name": "Имя"},
|
||||
{"username": "name\n", "display_name": "Имя"},
|
||||
{"username": "язык", "display_name": "Имя"},
|
||||
{"username": "a" * 33, "display_name": "Имя"},
|
||||
{"username": 123, "display_name": "Имя"},
|
||||
{"username": "valid_name", "display_name": " \t\n"},
|
||||
{"username": "valid_name", "display_name": "👋" * 101},
|
||||
{"username": "valid_name", "display_name": False},
|
||||
{"username": "valid_name", "display_name": "Имя", "extra": 1},
|
||||
]
|
||||
for body in invalid_bodies:
|
||||
if isinstance(body, dict):
|
||||
body = {**body, "password": "Synthetic-password-123"}
|
||||
with self.subTest(body=body):
|
||||
self.assert_error("POST", "/api/v1/users", 400, "invalid_request",
|
||||
raw=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
|
||||
|
||||
def test_malformed_json_and_encoding(self):
|
||||
invalid_bodies = [
|
||||
b'{"username":', b'', b'not JSON', b'\xff',
|
||||
'{"username":"valid_name","display_name":"Имя"}'.encode("utf-16"),
|
||||
b'{"username":"valid_name","display_name":"\\ud800"}',
|
||||
]
|
||||
for body in invalid_bodies:
|
||||
with self.subTest(body=body):
|
||||
self.assert_error("POST", "/api/v1/users", 400, "invalid_request",
|
||||
raw=body, headers={"Content-Type": "application/json"})
|
||||
|
||||
def test_wrong_content_type(self):
|
||||
self.assert_error("POST", "/api/v1/users", 415, "unsupported_media_type",
|
||||
raw=b'{}', headers={"Content-Type": "text/plain"})
|
||||
|
||||
def test_identification_and_authentication_order(self):
|
||||
self.assert_error("GET", "/api/v1/users/me", 401, "unauthorized")
|
||||
self.assert_error("GET", "/api/v1/users/me", 401, "unauthorized",
|
||||
headers={"X-User-Id": self.alice["id"]})
|
||||
self.assert_error("GET", "/api/v1/users/me", 401, "unauthorized",
|
||||
headers={"Authorization": "Bearer unknown-session"})
|
||||
self.assert_error("POST", self.path + "/messages", 401, "unauthorized",
|
||||
raw=b'{', headers={"Content-Type": "application/json"})
|
||||
me = self.client.call("GET", "/api/v1/users/me", schema="User", actor=self.alice,
|
||||
headers={"X-User-Id": self.bob["id"]})["json"]
|
||||
self.assertEqual(me, self.alice["user"])
|
||||
|
||||
def test_invalid_chat_members(self):
|
||||
invalid_members = [
|
||||
[], [self.bob["id"]], [self.alice["id"], str(uuid4())],
|
||||
[self.alice["id"], self.alice["id"]],
|
||||
[self.alice["id"], self.alice["id"].upper()],
|
||||
[self.alice["id"], "not-a-uuid"], [True], self.alice["id"],
|
||||
[self.alice["id"]] + [str(uuid4()) for _ in range(100)],
|
||||
]
|
||||
for members in invalid_members:
|
||||
with self.subTest(members=members):
|
||||
self.assert_error("POST", "/api/v1/chats", 400, "invalid_request", actor=self.alice,
|
||||
body={"title": "Чат", "member_ids": members})
|
||||
chats = self.read_all("/api/v1/chats", self.alice, "ChatPage")
|
||||
self.assertEqual([chat["id"] for chat in chats], [self.chat["id"]])
|
||||
|
||||
def test_invalid_chat_title(self):
|
||||
for title in ("", " \n", "a" * 101, 123, None):
|
||||
with self.subTest(title=title):
|
||||
self.assert_error("POST", "/api/v1/chats", 400, "invalid_request", actor=self.alice,
|
||||
body={"title": title, "member_ids": [self.alice["id"]]})
|
||||
|
||||
def test_chat_access(self):
|
||||
outsider = self.assert_error("GET", self.path, 404, "not_found", actor=self.eve)
|
||||
missing = self.assert_error("GET", "/api/v1/chats/" + str(uuid4()), 404, "not_found", actor=self.eve)
|
||||
self.assertEqual(outsider["message"], missing["message"])
|
||||
self.assert_error("GET", self.path + "/messages", 404, "not_found", actor=self.eve)
|
||||
self.assert_error("POST", self.path + "/messages", 404, "not_found", actor=self.eve, body={"text": "Чужое"})
|
||||
self.assertEqual(self.read_all("/api/v1/chats", self.eve, "ChatPage"), [])
|
||||
self.assert_error("GET", "/api/v1/chats/not-a-uuid", 400, "invalid_request", actor=self.alice)
|
||||
|
||||
def test_invalid_message_fields(self):
|
||||
for text in ("", " \t\n", "👋" * 4001, 123, True, None, []):
|
||||
with self.subTest(text_type=type(text).__name__):
|
||||
self.assert_error("POST", self.path + "/messages", 400, "invalid_request",
|
||||
actor=self.alice, body={"text": text})
|
||||
self.assert_error("POST", self.path + "/messages", 400, "invalid_request", actor=self.alice,
|
||||
body={"text": "Подмена автора", "sender_id": self.bob["id"]})
|
||||
self.assertEqual(self.read_all(self.path + "/messages", self.alice, "MessagePage"), [])
|
||||
|
||||
def test_unicode_and_text_preservation(self):
|
||||
for text in (" Привет, мир 👋\n", "👋" * 4000):
|
||||
message = self.client.message(self.bob, self.chat, text)["json"]
|
||||
self.assertEqual(message["text"], text)
|
||||
self.assertEqual(message["sender_id"], self.bob["id"])
|
||||
items = self.read_all(self.path + "/messages", self.alice, "MessagePage")
|
||||
self.assertEqual([item["text"] for item in items], [" Привет, мир 👋\n", "👋" * 4000])
|
||||
|
||||
def test_message_pagination_and_changing_limit(self):
|
||||
sent = [self.client.message(self.alice, self.chat, f"Сообщение {i}")["json"] for i in range(8)]
|
||||
items = self.read_all(self.path + "/messages", self.bob, "MessagePage", limit=3)
|
||||
self.assertEqual(items, sorted(sent, key=lambda item: (item["created_at"], item["id"])))
|
||||
first = self.client.call("GET", self.path + "/messages?limit=1", actor=self.alice, schema="MessagePage")["json"]
|
||||
query = urlencode({"limit": 100, "cursor": first["next_cursor"]})
|
||||
rest = self.client.call("GET", self.path + "/messages?" + query, actor=self.alice, schema="MessagePage")["json"]
|
||||
self.assertEqual(first["items"] + rest["items"], items)
|
||||
self.assertIsNone(rest["next_cursor"])
|
||||
|
||||
def test_default_page_size(self):
|
||||
for i in range(51):
|
||||
self.client.message(self.alice, self.chat, f"Сообщение {i}")
|
||||
page = self.client.call("GET", self.path + "/messages", actor=self.alice, schema="MessagePage")["json"]
|
||||
self.assertEqual(len(page["items"]), 50)
|
||||
self.assertIsNotNone(page["next_cursor"])
|
||||
|
||||
def test_chat_pagination_and_cursor_owner(self):
|
||||
for i in range(4):
|
||||
self.client.call("POST", "/api/v1/chats", 201, actor=self.alice,
|
||||
body={"title": f"Чат {i}", "member_ids": [self.alice["id"], self.bob["id"]]})
|
||||
chats = self.read_all("/api/v1/chats", self.alice, "ChatPage", limit=2)
|
||||
self.assertEqual(len(chats), 5)
|
||||
self.assertEqual(len({chat["id"] for chat in chats}), 5)
|
||||
self.assertEqual(chats, sorted(chats, key=lambda item: (item["created_at"], item["id"])))
|
||||
first = self.client.call("GET", "/api/v1/chats?limit=1", actor=self.alice, schema="ChatPage")["json"]
|
||||
query = urlencode({"cursor": first["next_cursor"]})
|
||||
self.assert_error("GET", "/api/v1/chats?" + query, 400, "invalid_request", actor=self.bob)
|
||||
|
||||
def test_invalid_limits_and_cursors(self):
|
||||
bad_queries = [{"limit": value} for value in ("0", "101", "-1", "1.5", "1.0", "abc", "")]
|
||||
bad_queries += [{"cursor": value} for value in ("", "not-base64!", "e30=", "W10=")]
|
||||
for path in ("/api/v1/chats", self.path + "/messages"):
|
||||
for query in bad_queries:
|
||||
with self.subTest(path=path, query=query):
|
||||
self.assert_error("GET", path + "?" + urlencode(query), 400, "invalid_request", actor=self.alice)
|
||||
|
||||
def test_cursor_cannot_be_used_for_another_chat_or_changed(self):
|
||||
for i in range(2):
|
||||
self.client.message(self.alice, self.chat, f"Сообщение {i}")
|
||||
first = self.client.call("GET", self.path + "/messages?limit=1", actor=self.alice, schema="MessagePage")["json"]
|
||||
cursor = first["next_cursor"]
|
||||
other = self.client.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat",
|
||||
body={"title": "Другой чат", "member_ids": [self.alice["id"]]})["json"]
|
||||
path = "/api/v1/chats/" + other["id"] + "/messages?" + urlencode({"cursor": cursor})
|
||||
self.assert_error("GET", path, 400, "invalid_request", actor=self.alice)
|
||||
data = json.loads(base64.urlsafe_b64decode(cursor))
|
||||
data["id"] = str(uuid4())
|
||||
changed = base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
|
||||
self.assert_error("GET", self.path + "/messages?" + urlencode({"cursor": changed}),
|
||||
400, "invalid_request", actor=self.alice)
|
||||
|
||||
def test_framework_errors_and_request_ids(self):
|
||||
first = self.assert_error("GET", "/unknown", 404, "not_found")
|
||||
second = self.assert_error("GET", "/unknown", 404, "not_found")
|
||||
self.assertNotEqual(first["request_id"], second["request_id"])
|
||||
self.assert_error("POST", "/health/live", 405, "invalid_request")
|
||||
@@ -0,0 +1,47 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import threading
|
||||
from uuid import uuid4
|
||||
|
||||
from helpers import ApiTestCase, Client
|
||||
|
||||
|
||||
class ConcurrencyTests(ApiTestCase):
|
||||
def test_ten_clients_send_one_hundred_messages(self):
|
||||
barrier = threading.Barrier(10)
|
||||
|
||||
def send_messages(worker):
|
||||
client = Client()
|
||||
actor = self.alice if worker % 2 == 0 else self.bob
|
||||
barrier.wait(timeout=10)
|
||||
sent = []
|
||||
for index in range(10):
|
||||
message = client.message(actor, self.chat, f"parallel-{worker}-{index}")["json"]
|
||||
self.assertEqual(message["sender_id"], actor["id"])
|
||||
sent.append(message)
|
||||
return sent
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
batches = list(pool.map(send_messages, range(10)))
|
||||
sent = [message for batch in batches for message in batch]
|
||||
history = self.read_all(self.path + "/messages", self.alice, "MessagePage", limit=17)
|
||||
self.assertEqual(len(history), 100)
|
||||
self.assertEqual(len({message["id"] for message in history}), 100)
|
||||
self.assertEqual(history, sorted(sent, key=lambda item: (item["created_at"], item["id"])))
|
||||
self.assertEqual({message["text"] for message in history},
|
||||
{f"parallel-{worker}-{index}" for worker in range(10) for index in range(10)})
|
||||
print("PASS: 10 clients sent 100 messages; history contains exactly 100 unique messages.")
|
||||
|
||||
def test_simultaneous_registration_of_one_username(self):
|
||||
username = "race_" + uuid4().hex[:20]
|
||||
barrier = threading.Barrier(10)
|
||||
|
||||
def register(worker):
|
||||
client = Client()
|
||||
barrier.wait(timeout=10)
|
||||
return client.call("POST", "/api/v1/users", [201, 409],
|
||||
body={"username": username, "display_name": f"Клиент {worker}", "password": "Synthetic-password-123"})["status"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
statuses = list(pool.map(register, range(10)))
|
||||
self.assertEqual(statuses.count(201), 1)
|
||||
self.assertEqual(statuses.count(409), 9)
|
||||
@@ -0,0 +1,62 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import threading
|
||||
from uuid import uuid4
|
||||
|
||||
from helpers import ApiTestCase, Client
|
||||
|
||||
|
||||
class IdempotencyTests(ApiTestCase):
|
||||
def test_parallel_replay_across_replicas(self):
|
||||
key = uuid4().hex
|
||||
barrier = threading.Barrier(20)
|
||||
|
||||
def send(_):
|
||||
client = Client()
|
||||
barrier.wait(timeout=10)
|
||||
return client.message(self.alice, self.chat, "Одно сообщение 👋", key=key)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=20) as pool:
|
||||
responses = list(pool.map(send, range(20)))
|
||||
self.assertGreaterEqual(len({r["headers"]["X-Instance-Id"] for r in responses}), 2)
|
||||
self.assertTrue(all(r["json"] == responses[0]["json"] for r in responses))
|
||||
self.assertEqual(self.read_all(self.path + "/messages", self.bob, "MessagePage"), [responses[0]["json"]])
|
||||
|
||||
def test_key_format_and_missing_key(self):
|
||||
for key in (None, "", " ", "a b", "a/b", "a" * 129):
|
||||
with self.subTest(key=key):
|
||||
headers = {} if key is None else {"Idempotency-Key": key}
|
||||
self.client.call("POST", self.path + "/messages", 400, actor=self.alice,
|
||||
body={"text": "Текст"}, headers=headers)
|
||||
for key in ("A", "a" * 128, "ABCdef012._:-"):
|
||||
self.client.message(self.alice, self.chat, key, key=key)
|
||||
|
||||
def test_conflict_and_semantic_json_replay(self):
|
||||
key = uuid4().hex
|
||||
first = self.client.message(self.alice, self.chat, "Текст 👋", key=key)["json"]
|
||||
replay = self.client.call("POST", self.path + "/messages", 201, actor=self.alice,
|
||||
raw=json.dumps({"text": "Текст 👋"}, ensure_ascii=True, indent=2).encode(),
|
||||
headers={"Content-Type": "application/json", "Idempotency-Key": key},
|
||||
schema="Message")["json"]
|
||||
self.assertEqual(first, replay)
|
||||
self.assert_error("POST", self.path + "/messages", 409, "conflict", actor=self.alice,
|
||||
body={"text": "Другой"}, headers={"Idempotency-Key": key})
|
||||
self.assertEqual(self.read_all(self.path + "/messages", self.bob, "MessagePage"), [first])
|
||||
|
||||
def test_scope_is_user_and_chat(self):
|
||||
key = uuid4().hex
|
||||
first = self.client.message(self.alice, self.chat, "Алиса", key=key)["json"]
|
||||
second = self.client.message(self.bob, self.chat, "Боб", key=key)["json"]
|
||||
other = self.client.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat",
|
||||
body={"title": "Другой чат", "member_ids": [self.alice["id"]]})["json"]
|
||||
third = self.client.message(self.alice, other, "Другой чат", key=key)["json"]
|
||||
self.assertEqual(len({first["id"], second["id"], third["id"]}), 3)
|
||||
|
||||
def test_replay_rechecks_session_and_access(self):
|
||||
key = uuid4().hex
|
||||
self.client.message(self.alice, self.chat, "Текст", key=key)
|
||||
self.client.call("POST", self.path + "/messages", 404, actor=self.eve,
|
||||
body={"text": "Текст"}, headers={"Idempotency-Key": key})
|
||||
self.client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.alice)
|
||||
self.client.call("POST", self.path + "/messages", 401, actor=self.alice,
|
||||
body={"text": "Текст"}, headers={"Idempotency-Key": key})
|
||||
@@ -0,0 +1,51 @@
|
||||
import base64
|
||||
from uuid import uuid4
|
||||
|
||||
from helpers import ApiTestCase
|
||||
|
||||
|
||||
class SessionTests(ApiTestCase):
|
||||
def basic(self, username, password):
|
||||
value = base64.b64encode((username + ":" + password).encode()).decode()
|
||||
return {"Authorization": "Basic " + value}
|
||||
|
||||
def test_wrong_password_and_basic_only_for_login(self):
|
||||
registration = self.alice["registration"]
|
||||
self.assert_error("POST", "/api/v1/auth/sessions", 401, "unauthorized",
|
||||
headers=self.basic(registration["username"], "wrong-password"))
|
||||
self.assert_error("POST", "/api/v1/auth/sessions", 401, "unauthorized")
|
||||
self.assert_error("POST", "/api/v1/auth/sessions", 401, "unauthorized",
|
||||
headers={"Authorization": "Basic not-base64!"})
|
||||
self.assert_error("GET", "/api/v1/users/me", 401, "unauthorized",
|
||||
headers=self.basic(registration["username"], registration["password"]))
|
||||
|
||||
def test_logout_revokes_only_one_session(self):
|
||||
registration = self.alice["registration"]
|
||||
second = self.client.call("POST", "/api/v1/auth/sessions", 201, schema="Session",
|
||||
headers=self.basic(registration["username"], registration["password"]))["json"]
|
||||
self.client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.alice)
|
||||
self.assert_error("GET", "/api/v1/users/me", 401, "unauthorized", actor=self.alice)
|
||||
self.assert_error("DELETE", "/api/v1/auth/sessions/current", 401, "unauthorized", actor=self.alice)
|
||||
self.client.call("GET", "/api/v1/users/me", schema="User", headers={"Authorization": "Bearer " + second["token"]})
|
||||
|
||||
def test_password_validation(self):
|
||||
for password in ("short", "x" * 129, 123, None, " " * 12):
|
||||
body = {"username": "pw_" + uuid4().hex[:20], "display_name": "Пароль", "password": password}
|
||||
self.assert_error("POST", "/api/v1/users", 400, "invalid_request", body=body)
|
||||
|
||||
def test_unicode_password_with_colon_and_private_response(self):
|
||||
username = "pw_" + uuid4().hex[:20]
|
||||
password = "Пароль:с:двоеточием-123"
|
||||
user = self.client.call("POST", "/api/v1/users", 201, schema="User",
|
||||
body={"username": username, "display_name": "Пароль", "password": password})["json"]
|
||||
session = self.client.call("POST", "/api/v1/auth/sessions", 201, schema="Session",
|
||||
headers=self.basic(username, password))["json"]
|
||||
self.assertEqual(session["user"], user)
|
||||
self.assertEqual(set(user), {"id", "username", "display_name", "created_at"})
|
||||
self.assertGreaterEqual(len(session["token"]), 32)
|
||||
|
||||
def test_sql_like_message_is_plain_text(self):
|
||||
text = "'; DROP TABLE messages; -- Привет"
|
||||
message = self.client.message(self.alice, self.chat, text)["json"]
|
||||
self.assertEqual(message["text"], text)
|
||||
self.assertEqual(self.read_all(self.path + "/messages", self.bob, "MessagePage"), [message])
|
||||
Reference in New Issue
Block a user