lab4: S3 вложения, compose-стенд, evidence и отчёт
This commit is contained in:
@@ -0,0 +1,323 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Собственные проверки lab2+lab3 (дополняют публичный smoke, ничего не ослабляют).
|
||||
|
||||
python student-tests/lab2_checks.py --base-url http://localhost:8080 # основные
|
||||
python student-tests/lab2_checks.py --base-url http://localhost:8080 --mode idem # идемпотентность и реплики (lab3)
|
||||
python student-tests/lab2_checks.py --base-url http://localhost:8080 --mode ttl # при SESSION_TTL_SECONDS=2
|
||||
|
||||
Только стандартная библиотека. Токены и пароли не печатаются.
|
||||
"""
|
||||
import argparse, base64, http.client, json, sys, threading, time, urllib.error, urllib.parse, urllib.request, uuid
|
||||
|
||||
PW = "correct-horse-battery"
|
||||
fails = []
|
||||
|
||||
|
||||
def call(base, method, path, body=None, headers=None, raw=None):
|
||||
h = dict(headers or {})
|
||||
data = raw
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
h.setdefault("Content-Type", "application/json")
|
||||
req = urllib.request.Request(base + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15) as r:
|
||||
return r.status, {k.lower(): v for k, v in r.headers.items()}, r.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, {k.lower(): v for k, v in e.headers.items()}, e.read()
|
||||
|
||||
|
||||
def post_big(base, path, size):
|
||||
"""POST тела size байт; сервер может ответить 413 и закрыть соединение раньше, чем тело отправлено."""
|
||||
u = urllib.parse.urlsplit(base)
|
||||
conn = http.client.HTTPConnection(u.hostname, u.port, timeout=15)
|
||||
conn.putrequest("POST", u.path + path)
|
||||
conn.putheader("Content-Type", "application/json")
|
||||
conn.putheader("Content-Length", str(size))
|
||||
conn.endheaders()
|
||||
try:
|
||||
conn.send(b"{" + b" " * (size - 2) + b"}")
|
||||
except OSError:
|
||||
pass # сервер уже ответил и закрыл соединение
|
||||
try:
|
||||
return conn.getresponse().status
|
||||
except (OSError, http.client.HTTPException) as e:
|
||||
return "нет ответа: %s" % type(e).__name__
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def js(b):
|
||||
try:
|
||||
return json.loads(b)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def check(name, ok, detail=""):
|
||||
print(("PASS" if ok else "FAIL") + ": " + name + ("" if ok else " -> " + detail))
|
||||
if not ok:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
def basic(u, p):
|
||||
return {"Authorization": "Basic " + base64.b64encode(f"{u}:{p}".encode()).decode()}
|
||||
|
||||
|
||||
def bearer(t):
|
||||
return {"Authorization": "Bearer " + t}
|
||||
|
||||
|
||||
def H(t, key=None):
|
||||
"""Заголовки отправки сообщения (lab3): Bearer + Idempotency-Key (по умолчанию новый)."""
|
||||
return {**bearer(t), "Idempotency-Key": key or uuid.uuid4().hex}
|
||||
|
||||
|
||||
class Api:
|
||||
def __init__(self, base):
|
||||
self.base = base + "/api/v1"
|
||||
|
||||
def __call__(self, *a, **k):
|
||||
return call(self.base, *a, **k)
|
||||
|
||||
def user(self, prefix="u"):
|
||||
name = f"{prefix}_{uuid.uuid4().hex[:10]}"
|
||||
s, _, b = self("POST", "/users", {"username": name, "display_name": name, "password": PW})
|
||||
assert s == 201, f"create user: {s}"
|
||||
u = js(b)
|
||||
s, _, b = self("POST", "/auth/sessions", headers=basic(name, PW))
|
||||
assert s == 201, f"login: {s}"
|
||||
return name, u["id"], js(b)["token"]
|
||||
|
||||
|
||||
def main_checks(api):
|
||||
a_name, a_id, a_tok = api.user("alice")
|
||||
b_name, b_id, b_tok = api.user("bob")
|
||||
c_name, c_id, c_tok = api.user("carol")
|
||||
|
||||
# --- регистрация
|
||||
s, _, _ = api("POST", "/users", {"username": a_name, "display_name": "x", "password": PW})
|
||||
check("повторный username -> 409", s == 409, str(s))
|
||||
s, _, b = api("POST", "/users", {"username": "x_" + uuid.uuid4().hex[:8], "display_name": "x", "password": "short"})
|
||||
check("пароль короче 12 -> 400", s == 400, str(s))
|
||||
s, _, b = api("POST", "/users", {"username": "x_" + uuid.uuid4().hex[:8], "display_name": "x", "password": PW, "extra": 1})
|
||||
check("лишнее поле -> 400", s == 400, str(s))
|
||||
s, _, b = api("GET", "/users/me", headers=bearer(a_tok))
|
||||
me = js(b) or {}
|
||||
check("User не содержит пароль/hash/токен", s == 200 and not ({"password", "password_hash", "token"} & set(me)), str(sorted(me)))
|
||||
|
||||
res = []
|
||||
rname = "race_" + uuid.uuid4().hex[:10]
|
||||
def reg():
|
||||
res.append(api("POST", "/users", {"username": rname, "display_name": "r", "password": PW})[0])
|
||||
ts = [threading.Thread(target=reg) for _ in range(10)]
|
||||
[t.start() for t in ts]; [t.join() for t in ts]
|
||||
check("гонка одинакового username: ровно один 201, остальные 409", sorted(res) == [201] + [409] * 9, str(sorted(res)))
|
||||
|
||||
# --- вход
|
||||
s1, h1, b1 = api("POST", "/auth/sessions", headers=basic(a_name, "wrong-password-123"))
|
||||
s2, h2, b2 = api("POST", "/auth/sessions", headers=basic("nosuchuser_zz", PW))
|
||||
e1, e2 = (js(b1) or {}).get("error", {}), (js(b2) or {}).get("error", {})
|
||||
check("неверный пароль и неизвестный пользователь неразличимы (401, тот же code/message/заголовок)",
|
||||
s1 == s2 == 401 and e1.get("code") == e2.get("code") and e1.get("message") == e2.get("message")
|
||||
and h1.get("www-authenticate") == h2.get("www-authenticate") == 'Basic realm="messenger", charset="UTF-8"',
|
||||
f"{s1}/{s2} {h1.get('www-authenticate')}")
|
||||
s, _, _ = api("POST", "/auth/sessions", {"username": a_name, "password": PW})
|
||||
check("вход JSON-телом без Basic -> 401", s == 401, str(s))
|
||||
s, _, _ = api("POST", "/auth/sessions", headers=bearer(a_tok))
|
||||
check("Bearer на POST /auth/sessions -> 401", s == 401, str(s))
|
||||
s, h, b = api("POST", "/auth/sessions", headers=basic(a_name, PW))
|
||||
d = js(b) or {}
|
||||
check("токен >=256 бит, token_type Bearer", s == 201 and len(d.get("token", "")) >= 43 and d.get("token_type") == "Bearer", str(s))
|
||||
|
||||
# --- бизнес-endpoint принимают только Bearer
|
||||
s, h, _ = api("GET", "/users/me", headers=basic(a_name, PW))
|
||||
check("Basic на бизнес-endpoint -> 401 + WWW-Authenticate: Bearer", s == 401 and h.get("www-authenticate", "").startswith("Bearer"), str(s))
|
||||
s, _, _ = api("GET", "/users/me", headers={"X-User-Id": a_id})
|
||||
check("один X-User-Id доступа не даёт", s == 401, str(s))
|
||||
s, _, b = api("GET", "/users/me", headers={**bearer(a_tok), "X-User-Id": b_id})
|
||||
check("X-User-Id игнорируется: владелец определяется токеном", s == 200 and (js(b) or {}).get("id") == a_id, str(s))
|
||||
s, _, _ = api("GET", "/users/me", headers=bearer("x" * 43))
|
||||
check("неизвестный токен -> 401", s == 401, str(s))
|
||||
|
||||
# --- запрос-идентификатор в ошибках
|
||||
s, h, b = api("GET", "/chats")
|
||||
check("X-Request-Id совпадает с request_id в теле ошибки", s == 401 and h.get("x-request-id") == (js(b) or {}).get("error", {}).get("request_id"), str(s))
|
||||
|
||||
# --- чаты и доступ
|
||||
s, _, b = api("GET", "/chats", headers=bearer(a_tok))
|
||||
before = len((js(b) or {}).get("items", []))
|
||||
s, _, b = api("POST", "/chats", {"title": "t", "member_ids": [a_id, str(uuid.uuid4())]}, bearer(a_tok))
|
||||
check("чат с неизвестным участником -> 400", s == 400, str(s))
|
||||
s, _, b = api("GET", "/chats", headers=bearer(a_tok))
|
||||
check("после отказа новый чат не появился (нет частичной записи)", len((js(b) or {}).get("items", [])) == before)
|
||||
s, _, b = api("POST", "/chats", {"title": "ab", "member_ids": [a_id, b_id]}, bearer(a_tok))
|
||||
chat = js(b) or {}
|
||||
check("чат создан с обоими участниками", s == 201 and sorted(chat.get("member_ids", [])) == sorted([a_id, b_id]), str(s))
|
||||
cid = chat.get("id", "")
|
||||
s, _, _ = api("POST", "/chats", {"title": "ab", "member_ids": [b_id]}, bearer(a_tok))
|
||||
check("создатель обязан быть среди member_ids -> 400", s == 400, str(s))
|
||||
for path in (f"/chats/{cid}", f"/chats/{cid}/messages"):
|
||||
s, _, _ = api("GET", path, headers=bearer(c_tok))
|
||||
check(f"посторонний: GET {path.split(cid)[1] or '/chat'} -> 404", s == 404, str(s))
|
||||
s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": "hi"}, H(c_tok))
|
||||
check("посторонний не может писать -> 404", s == 404, str(s))
|
||||
for path in ("/chats/not-a-uuid", "/chats/not-a-uuid/messages"):
|
||||
s, _, _ = api("GET", path, headers=bearer(a_tok))
|
||||
check(f"неверный UUID {path} -> 400", s == 400, str(s))
|
||||
s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": "hi", "sender_id": b_id}, H(a_tok))
|
||||
check("sender_id в запросе не принимается -> 400", s == 400, str(s))
|
||||
s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": " "}, H(a_tok))
|
||||
check("пробельный текст -> 400", s == 400, str(s))
|
||||
s, _, b = api("POST", f"/chats/{cid}/messages", {"text": "привет 👋"}, H(b_tok))
|
||||
check("отправитель берётся из токена", s == 201 and (js(b) or {}).get("sender_id") == b_id, str(s))
|
||||
|
||||
# --- пагинация
|
||||
for i in range(5):
|
||||
api("POST", f"/chats/{cid}/messages", {"text": f"m{i}"}, H(a_tok))
|
||||
seen, cur, pages = [], None, 0
|
||||
while True:
|
||||
s, _, b = api("GET", f"/chats/{cid}/messages?limit=2" + (f"&cursor={cur}" if cur else ""), headers=bearer(a_tok))
|
||||
d = js(b) or {}
|
||||
seen += [m["id"] for m in d.get("items", [])]
|
||||
pages += 1
|
||||
cur = d.get("next_cursor")
|
||||
if not cur or pages > 10:
|
||||
break
|
||||
check("пагинация limit=2: без повторов, все 6 сообщений", len(seen) == len(set(seen)) == 6, f"{len(seen)}/{len(set(seen))}")
|
||||
s, _, b = api("GET", f"/chats/{cid}/messages?limit=2", headers=bearer(a_tok))
|
||||
cur = (js(b) or {}).get("next_cursor")
|
||||
s, _, b = api("POST", "/chats", {"title": "other", "member_ids": [a_id]}, bearer(a_tok))
|
||||
other = (js(b) or {}).get("id")
|
||||
s, _, _ = api("GET", f"/chats/{other}/messages?cursor={cur}", headers=bearer(a_tok))
|
||||
check("cursor от другого чата -> 400", s == 400, str(s))
|
||||
for q in ("limit=0", "limit=101", "limit=abc", "limit=%2B5", "limit=2&limit=3"):
|
||||
s, _, _ = api("GET", f"/chats/{cid}/messages?{q}", headers=bearer(a_tok))
|
||||
check(f"?{q} -> 400", s == 400, str(s))
|
||||
|
||||
# --- тело запроса
|
||||
s = post_big(api.base, "/users", 1100 * 1024)
|
||||
check("тело >1 MiB -> 413", s == 413, str(s))
|
||||
s, _, _ = api("POST", "/users", raw=b"{}", headers={"Content-Type": "text/plain"})
|
||||
check("не JSON Content-Type -> 415", s == 415, str(s))
|
||||
s, _, _ = api("POST", "/users", raw=b"{", headers={"Content-Type": "application/json"})
|
||||
check("битый JSON -> 400", s == 400, str(s))
|
||||
|
||||
# --- logout (в конце: отзывает токен)
|
||||
s, _, _ = api("DELETE", "/auth/sessions/current", headers=bearer(a_tok))
|
||||
check("logout -> 204", s == 204, str(s))
|
||||
s, h, _ = api("DELETE", "/auth/sessions/current", headers=bearer(a_tok))
|
||||
check("повторный logout с отозванным токеном -> 401", s == 401, str(s))
|
||||
s, h, _ = api("GET", "/users/me", headers=bearer(a_tok))
|
||||
check("отозванный токен -> 401 + WWW-Authenticate: Bearer", s == 401 and h.get("www-authenticate", "").startswith("Bearer"), str(s))
|
||||
s, _, _ = api("GET", "/users/me", headers=bearer(b_tok))
|
||||
check("logout одного пользователя не затрагивает чужие сессии", s == 200, str(s))
|
||||
|
||||
|
||||
def idempotency_checks(api, min_instances):
|
||||
a_name, a_id, a_tok = api.user("alice")
|
||||
b_name, b_id, b_tok = api.user("bob")
|
||||
c_name, c_id, c_tok = api.user("carol")
|
||||
s, _, b = api("POST", "/chats", {"title": "idem", "member_ids": [a_id, b_id]}, bearer(a_tok))
|
||||
cid = js(b)["id"]
|
||||
s, _, b = api("POST", "/chats", {"title": "idem2", "member_ids": [a_id, b_id]}, bearer(a_tok))
|
||||
cid2 = js(b)["id"]
|
||||
|
||||
def hist(chat, tok):
|
||||
s, _, b = api("GET", f"/chats/{chat}/messages?limit=100", headers=bearer(tok))
|
||||
return (js(b) or {}).get("items", [])
|
||||
|
||||
# --- несколько реплик за LB, одна сессия, без повторного входа
|
||||
seen = set()
|
||||
for _ in range(60):
|
||||
s, h, _ = api("GET", "/users/me", headers=bearer(a_tok))
|
||||
if s != 200:
|
||||
break
|
||||
seen.add(h.get("x-instance-id"))
|
||||
check(f"через LB отвечают >= {min_instances} реплик с одним токеном (X-Instance-Id: {len(seen)})",
|
||||
len(seen) >= min_instances and None not in seen, str(seen))
|
||||
|
||||
# --- базовая идемпотентность
|
||||
key = "k-" + uuid.uuid4().hex
|
||||
s1, h1, b1 = api("POST", f"/chats/{cid}/messages", {"text": "один раз"}, H(a_tok, key))
|
||||
s2, h2, b2 = api("POST", f"/chats/{cid}/messages", {"text": "один раз"}, H(a_tok, key))
|
||||
check("повтор с тем же ключом: тот же 201 и то же сообщение", s1 == s2 == 201 and js(b1) == js(b2), f"{s1}/{s2}")
|
||||
check("повтор не создал дубль", len([m for m in hist(cid, a_tok) if m["text"] == "один раз"]) == 1)
|
||||
s, _, b = api("POST", f"/chats/{cid}/messages", {"text": "другой текст"}, H(a_tok, key))
|
||||
check("тот же ключ с другим телом -> 409", s == 409, str(s))
|
||||
s, _, b = api("POST", f"/chats/{cid}/messages", raw=b'{"text":"\xd0\xbe\xd0\xb4\xd0\xb8\xd0\xbd \xd1\x80\xd0\xb0\xd0\xb7"}',
|
||||
headers={**H(a_tok, key), "Content-Type": "application/json"})
|
||||
check("тот же ключ и то же тело (другое форматирование JSON) -> тот же результат", s == 201 and js(b) == js(b1), str(s))
|
||||
|
||||
# --- область ключа: пользователь + метод + путь
|
||||
s, _, b = api("POST", f"/chats/{cid2}/messages", {"text": "один раз"}, H(a_tok, key))
|
||||
check("тот же ключ в другом чате независим", s == 201 and js(b)["chat_id"] == cid2, str(s))
|
||||
s, _, b = api("POST", f"/chats/{cid}/messages", {"text": "один раз"}, H(b_tok, key))
|
||||
check("тот же ключ у другого пользователя независим", s == 201 and js(b)["sender_id"] == b_id, str(s))
|
||||
|
||||
# --- валидация ключа и доступ
|
||||
s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": "x"}, bearer(a_tok))
|
||||
check("нет Idempotency-Key -> 400", s == 400, str(s))
|
||||
for bad_key in ("bad key!", "a/b", "a" * 129, ""):
|
||||
s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": "x"}, {**bearer(a_tok), "Idempotency-Key": bad_key})
|
||||
check(f"неверный ключ {bad_key[:12]!r} -> 400", s == 400, str(s))
|
||||
s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": "один раз"}, H(c_tok, key))
|
||||
check("посторонний с тем же ключом -> 404 (доступ проверяется при повторе)", s == 404, str(s))
|
||||
s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": "x"}, {"Idempotency-Key": "k1"})
|
||||
check("без токена -> 401", s == 401, str(s))
|
||||
|
||||
# --- конкурентные повторы одного ключа (через LB попадают на разные реплики)
|
||||
key2 = "c-" + uuid.uuid4().hex
|
||||
res = []
|
||||
def fire(text="конкурентно"):
|
||||
s, h, b = api("POST", f"/chats/{cid}/messages", {"text": text}, H(a_tok, key2))
|
||||
res.append((s, h.get("x-instance-id"), js(b)))
|
||||
ts = [threading.Thread(target=fire) for _ in range(30)]
|
||||
[t.start() for t in ts]; [t.join() for t in ts]
|
||||
codes = sorted({r[0] for r in res})
|
||||
ids = {(r[2] or {}).get("id") for r in res}
|
||||
check("30 параллельных запросов с одним ключом: все 201 и одно и то же сообщение", codes == [201] and len(ids) == 1, f"{codes} {len(ids)}")
|
||||
check("в истории ровно одно такое сообщение", len([m for m in hist(cid, a_tok) if m["text"] == "конкурентно"]) == 1)
|
||||
print(f"INFO: параллельные повторы обслужили реплики: {sorted({r[1] for r in res})}")
|
||||
|
||||
key3 = "d-" + uuid.uuid4().hex
|
||||
res.clear()
|
||||
ts = [threading.Thread(target=lambda i=i: res.append(api("POST", f"/chats/{cid}/messages", {"text": f"вариант {i % 2}"}, H(a_tok, key3))[0])) for i in range(20)]
|
||||
[t.start() for t in ts]; [t.join() for t in ts]
|
||||
check("параллельно один ключ и два разных тела: победитель один, остальным другого тела -> 409",
|
||||
set(res) == {201, 409} and 1 <= res.count(201), str(sorted(set(res))))
|
||||
check("создано ровно одно сообщение из конкурирующих", len([m for m in hist(cid, a_tok) if m["text"].startswith("вариант")]) == 1)
|
||||
|
||||
# --- повтор после logout
|
||||
s, _, _ = api("DELETE", "/auth/sessions/current", headers=bearer(a_tok))
|
||||
s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": "один раз"}, H(a_tok, key))
|
||||
check("повтор с отозванным токеном -> 401", s == 401, str(s))
|
||||
|
||||
|
||||
def ttl_checks(api):
|
||||
name = api.user("ttl")[0]
|
||||
s, _, b = api("POST", "/auth/sessions", headers=basic(name, PW))
|
||||
d = js(b) or {}
|
||||
tok = d.get("token", "")
|
||||
s0, _, _ = api("GET", "/users/me", headers=bearer(tok))
|
||||
check("TTL: сразу после входа токен действует (200)", s0 == 200, str(s0))
|
||||
time.sleep(3.5)
|
||||
s1, h, _ = api("GET", "/users/me", headers=bearer(tok))
|
||||
check("TTL: через 3.5 с при SESSION_TTL_SECONDS=2 токен истёк (401)", s1 == 401 and h.get("www-authenticate", "").startswith("Bearer"), str(s1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--mode", choices=["main", "idem", "ttl"], default="main")
|
||||
ap.add_argument("--min-instances", type=int, default=2, help="сколько разных X-Instance-Id ожидается через LB")
|
||||
a = ap.parse_args()
|
||||
api = Api(a.base_url.rstrip("/"))
|
||||
if a.mode == "ttl":
|
||||
ttl_checks(api)
|
||||
elif a.mode == "idem":
|
||||
idempotency_checks(api, a.min_instances)
|
||||
else:
|
||||
main_checks(api)
|
||||
print(("FAIL: %d проверок не прошли: %s" % (len(fails), "; ".join(fails))) if fails else "PASS: все проверки режима '%s'" % a.mode)
|
||||
sys.exit(1 if fails else 0)
|
||||
@@ -0,0 +1,310 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Собственные проверки lab4 (вложения). Дополняют публичный smoke, ничего не ослабляют.
|
||||
|
||||
python student-tests/lab4_checks.py --base-url http://localhost:8080
|
||||
python student-tests/lab4_checks.py --base-url http://localhost:8080 --mode upload-stop --stop-hook scripts/stop-one.cmd
|
||||
|
||||
Только стандартная библиотека. Токены не печатаются.
|
||||
"""
|
||||
import argparse, base64, hashlib, http.client, io, json, os, shlex, struct, subprocess, sys, time, urllib.parse, uuid, zlib
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
import lab3_checks as L # noqa: E402 (общие помощники: call, check, Api, H, bearer, js, fails)
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
|
||||
|
||||
def mkpng(w, h):
|
||||
"""Валидный 1-битный PNG w x h: данные малы, а заявленное число пикселей большое."""
|
||||
def ch(t, b):
|
||||
return struct.pack(">I", len(b)) + t + b + struct.pack(">I", zlib.crc32(t + b) & 0xFFFFFFFF)
|
||||
row = b"\x00" * (1 + (w + 7) // 8)
|
||||
raw = row * h if w * h <= 50_000_000 else b"\x00"
|
||||
return (b"\x89PNG\r\n\x1a\n" + ch(b"IHDR", struct.pack(">IIBBBBB", w, h, 1, 0, 0, 0, 0))
|
||||
+ ch(b"IDAT", zlib.compress(raw, 9)) + ch(b"IEND", b""))
|
||||
|
||||
|
||||
JPEG_B64 = (
|
||||
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0d"
|
||||
"Hx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4e"
|
||||
"Hh4eHh4eHh7/wAARCAAwAEADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF"
|
||||
"BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVW"
|
||||
"V1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi"
|
||||
"4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAEC"
|
||||
"AxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVm"
|
||||
"Z2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq"
|
||||
"8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDzSiiivkT+iAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKA"
|
||||
"P//Z"
|
||||
)
|
||||
|
||||
|
||||
def jpeg_bytes():
|
||||
"""Готовый корректный baseline JPEG 64x48 (без зависимостей от Pillow)."""
|
||||
return base64.b64decode("".join(JPEG_B64))
|
||||
|
||||
|
||||
def upload(api, tok, chat, data, ctype="image/png", filename="a.png", extra_headers=None):
|
||||
path = f"/chats/{chat}/attachments?filename={urllib.parse.quote(filename, safe='')}"
|
||||
return api("POST", path, headers={**L.bearer(tok), "Content-Type": ctype, **(extra_headers or {})}, raw=data)
|
||||
|
||||
|
||||
def raw_upload(api, tok, chat, size, ctype="image/png", filename="big.png"):
|
||||
"""Загрузка size байт, когда сервер может ответить 413 и закрыть соединение, не дочитав тело."""
|
||||
u = urllib.parse.urlsplit(api.base)
|
||||
conn = http.client.HTTPConnection(u.hostname, u.port, timeout=30)
|
||||
conn.putrequest("POST", f"{u.path}/chats/{chat}/attachments?filename={filename}")
|
||||
for k, v in (("Authorization", "Bearer " + tok), ("Content-Type", ctype), ("Content-Length", str(size))):
|
||||
conn.putheader(k, v)
|
||||
conn.endheaders()
|
||||
try:
|
||||
sent = 0
|
||||
while sent < size:
|
||||
n = min(1 << 20, size - sent)
|
||||
conn.send(b"\x00" * n)
|
||||
sent += n
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
return conn.getresponse().status
|
||||
except (OSError, http.client.HTTPException) as e:
|
||||
return "нет ответа: " + type(e).__name__
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def setup(api):
|
||||
a = api.user("alice"); b = api.user("bob"); c = api.user("carol")
|
||||
s, _, body = api("POST", "/chats", {"title": "att", "member_ids": [a[1], b[1]]}, L.bearer(a[2]))
|
||||
chat = L.js(body)["id"]
|
||||
s, _, body = api("POST", "/chats", {"title": "att2", "member_ids": [a[1]]}, L.bearer(a[2]))
|
||||
return a, b, c, chat, L.js(body)["id"]
|
||||
|
||||
|
||||
def attach_checks(api):
|
||||
(an, aid, at), (bn, bid, bt), (cn, cid, ct), chat, other = setup(api)
|
||||
sha = hashlib.sha256(PNG).hexdigest()
|
||||
|
||||
# --- успешная загрузка и метаданные
|
||||
s, h, b = upload(api, at, chat, PNG, filename="фото №1.png")
|
||||
att = L.js(b) or {}
|
||||
L.check("загрузка PNG -> 201, status ready, ожидаемые поля",
|
||||
s == 201 and att.get("status") == "ready" and att.get("content_type") == "image/png"
|
||||
and att.get("size_bytes") == len(PNG) and att.get("sha256") == sha and att.get("variants") == []
|
||||
and att.get("filename") == "фото №1.png" and att.get("owner_id") == aid and att.get("chat_id") == chat, f"{s} {att}")
|
||||
check_id = att.get("id", "")
|
||||
L.check("в ответе есть X-Instance-Id и X-Request-Id", bool(h.get("x-instance-id")) and bool(h.get("x-request-id")))
|
||||
jpg = jpeg_bytes()
|
||||
if jpg:
|
||||
s, _, b = upload(api, at, chat, jpg, "image/jpeg", "p.jpg")
|
||||
j = L.js(b) or {}
|
||||
L.check("загрузка JPEG -> 201 и верный sha256", s == 201 and j.get("sha256") == hashlib.sha256(jpg).hexdigest(), str(s))
|
||||
s, _, b = upload(api, at, chat, mkpng(100, 100), "image/png", "x.png")
|
||||
L.check("созданный PNG другого размера -> 201", s == 201, str(s))
|
||||
|
||||
s, _, b = api("GET", f"/attachments/{check_id}", headers=L.bearer(bt))
|
||||
L.check("метаданные доступны другому участнику чата", s == 200 and (L.js(b) or {}).get("id") == check_id, str(s))
|
||||
s, h, b = api("GET", f"/attachments/{check_id}/content", headers=L.bearer(bt))
|
||||
L.check("скачивание: байты совпадают, Content-Type верный, nosniff", s == 200 and b == PNG
|
||||
and h.get("content-type") == "image/png" and h.get("x-content-type-options") == "nosniff", f"{s} {h.get('content-type')}")
|
||||
L.check("Content-Length равен размеру", h.get("content-length") == str(len(PNG)), str(h.get("content-length")))
|
||||
|
||||
# --- доступ
|
||||
L.check("метаданные постороннему -> 404", api("GET", f"/attachments/{check_id}", headers=L.bearer(ct))[0] == 404)
|
||||
L.check("содержимое постороннему -> 404", api("GET", f"/attachments/{check_id}/content", headers=L.bearer(ct))[0] == 404)
|
||||
L.check("без токена -> 401", api("GET", f"/attachments/{check_id}")[0] == 401)
|
||||
L.check("неверный UUID -> 400", api("GET", "/attachments/not-a-uuid", headers=L.bearer(at))[0] == 400)
|
||||
L.check("неизвестный UUID -> 404", api("GET", f"/attachments/{uuid.uuid4()}", headers=L.bearer(at))[0] == 404)
|
||||
L.check("загрузка в чужой чат -> 404", upload(api, ct, chat, PNG)[0] == 404)
|
||||
s, _, _ = api("POST", f"/chats/{chat}/attachments?filename=a.png", headers={"Content-Type": "image/png"}, raw=PNG)
|
||||
L.check("загрузка без токена -> 401", s == 401, str(s))
|
||||
L.check("загрузка в неверный UUID чата -> 400", upload(api, at, "not-a-uuid", PNG)[0] == 400)
|
||||
L.check("?variant=thumbnail (вариантов нет) -> 404", api("GET", f"/attachments/{check_id}/content?variant=thumbnail", headers=L.bearer(at))[0] == 404)
|
||||
L.check("?variant=bogus -> 400", api("GET", f"/attachments/{check_id}/content?variant=bogus", headers=L.bearer(at))[0] == 400)
|
||||
L.check("?variant=original -> 200", api("GET", f"/attachments/{check_id}/content?variant=original", headers=L.bearer(at))[0] == 200)
|
||||
|
||||
# --- имя файла
|
||||
for name, why in (("a/b.png", "слэш"), ("a\\b.png", "обратный слэш"), ("a%00b.png", "NUL"), ("a%0Ab.png", "перевод строки"),
|
||||
("", "пустое"), ("%20%20", "пробелы"), ("n" * 256, "256 символов")):
|
||||
s, _, _ = api("POST", f"/chats/{chat}/attachments?filename={name}", headers={**L.bearer(at), "Content-Type": "image/png"}, raw=PNG)
|
||||
L.check(f"filename: {why} -> 400", s == 400, str(s))
|
||||
s, _, _ = api("POST", f"/chats/{chat}/attachments", headers={**L.bearer(at), "Content-Type": "image/png"}, raw=PNG)
|
||||
L.check("filename не указан -> 400", s == 400, str(s))
|
||||
s, _, b = upload(api, at, chat, PNG, filename="n" * 255)
|
||||
L.check("filename из 255 символов -> 201", s == 201, str(s))
|
||||
s, _, b = upload(api, at, chat, PNG, filename="../../etc/passwd".replace("/", "_"))
|
||||
L.check("имя «../..» без разделителей принимается и не влияет на ключ объекта", s == 201, str(s))
|
||||
|
||||
# --- тип и содержимое
|
||||
L.check("Content-Type text/plain -> 415", upload(api, at, chat, PNG, "text/plain")[0] == 415)
|
||||
L.check("Content-Type image/gif -> 415", upload(api, at, chat, PNG, "image/gif")[0] == 415)
|
||||
L.check("PNG под видом image/jpeg -> 415", upload(api, at, chat, PNG, "image/jpeg")[0] == 415)
|
||||
L.check("текст под видом image/png -> 415", upload(api, at, chat, b"not an image at all" * 20)[0] == 415)
|
||||
L.check("пустое тело -> 415", upload(api, at, chat, b"")[0] == 415)
|
||||
bad = bytearray(PNG); bad[len(PNG) // 2] ^= 0xFF
|
||||
L.check("PNG с повреждённым блоком (CRC) -> 415", upload(api, at, chat, bytes(bad))[0] == 415)
|
||||
L.check("усечённый PNG -> 415", upload(api, at, chat, PNG[:-30])[0] == 415)
|
||||
L.check("PNG с мусором в конце -> 415", upload(api, at, chat, PNG + b"junk")[0] == 415)
|
||||
if jpg:
|
||||
L.check("усечённый JPEG -> 415", upload(api, at, chat, jpg[:-40], "image/jpeg")[0] == 415)
|
||||
L.check("JPEG под видом image/png -> 415", upload(api, at, chat, jpg, "image/png")[0] == 415)
|
||||
|
||||
# --- лимиты размера и числа пикселей
|
||||
s, _, _ = upload(api, at, chat, mkpng(8000, 5000))
|
||||
L.check("ровно 40 000 000 пикселей (8000x5000) -> 201", s == 201, str(s))
|
||||
L.check("40 005 000 пикселей (8001x5000) -> 413", upload(api, at, chat, mkpng(8001, 5000))[0] == 413)
|
||||
L.check("«бомба» 20000x20000 малого размера -> 413", upload(api, at, chat, mkpng(20000, 20000))[0] == 413)
|
||||
L.check("тело 10 MiB + 1 байт -> 413", raw_upload(api, at, chat, 10 * 1024 * 1024 + 1) == 413)
|
||||
|
||||
# --- сообщения с вложениями
|
||||
s, _, b = api("POST", f"/chats/{chat}/messages", {"text": "", "attachment_ids": [check_id]}, L.H(at))
|
||||
m = L.js(b) or {}
|
||||
L.check("сообщение только с вложением (text='') -> 201 с attachment_ids", s == 201 and m.get("attachment_ids") == [check_id], f"{s} {m}")
|
||||
s, _, b = api("POST", f"/chats/{chat}/messages", {"text": "привет", "attachment_ids": []}, L.H(at))
|
||||
L.check("attachment_ids=[] даёт обычное сообщение с пустым массивом", s == 201 and (L.js(b) or {}).get("attachment_ids") == [], str(s))
|
||||
s, _, b = api("POST", f"/chats/{chat}/messages", {"text": "без поля"}, L.H(at))
|
||||
L.check("без attachment_ids в ответе всё равно attachment_ids=[]", s == 201 and (L.js(b) or {}).get("attachment_ids") == [], str(s))
|
||||
L.check("пустой текст без вложений -> 400", api("POST", f"/chats/{chat}/messages", {"text": ""}, L.H(at))[0] == 400)
|
||||
L.check("пробельный текст без вложений -> 400", api("POST", f"/chats/{chat}/messages", {"text": " ", "attachment_ids": []}, L.H(at))[0] == 400)
|
||||
L.check("пробельный текст с вложением допустим -> 201", api("POST", f"/chats/{chat}/messages", {"text": " ", "attachment_ids": [check_id]}, L.H(at))[0] == 201)
|
||||
L.check("неизвестное вложение -> 404", api("POST", f"/chats/{chat}/messages", {"text": "x", "attachment_ids": [str(uuid.uuid4())]}, L.H(at))[0] == 404)
|
||||
L.check("attachment_ids не массив -> 400", api("POST", f"/chats/{chat}/messages", {"text": "x", "attachment_ids": check_id}, L.H(at))[0] == 400)
|
||||
L.check("attachment_ids с неверным UUID -> 400", api("POST", f"/chats/{chat}/messages", {"text": "x", "attachment_ids": ["zzz"]}, L.H(at))[0] == 400)
|
||||
L.check("повтор одного id в attachment_ids -> 400", api("POST", f"/chats/{chat}/messages", {"text": "x", "attachment_ids": [check_id, check_id]}, L.H(at))[0] == 400)
|
||||
ids = []
|
||||
for i in range(11):
|
||||
s, _, b = upload(api, at, chat, mkpng(8 + i, 8))
|
||||
ids.append((L.js(b) or {}).get("id"))
|
||||
L.check("11 вложений в сообщении -> 400", api("POST", f"/chats/{chat}/messages", {"text": "x", "attachment_ids": ids}, L.H(at))[0] == 400)
|
||||
s, _, b = api("POST", f"/chats/{chat}/messages", {"text": "десять", "attachment_ids": ids[:10]}, L.H(at))
|
||||
L.check("10 вложений -> 201 с сохранением порядка", s == 201 and (L.js(b) or {}).get("attachment_ids") == ids[:10], str(s))
|
||||
s, _, b = api("POST", f"/chats/{other}/attachments?filename=o.png", headers={**L.bearer(at), "Content-Type": "image/png"}, raw=PNG)
|
||||
foreign = (L.js(b) or {}).get("id")
|
||||
L.check("вложение другого чата в сообщении -> 404", api("POST", f"/chats/{chat}/messages", {"text": "x", "attachment_ids": [foreign]}, L.H(at))[0] == 404)
|
||||
L.check("участник может сослаться на вложение другого участника", api("POST", f"/chats/{chat}/messages", {"text": "моё", "attachment_ids": [check_id]}, L.H(bt))[0] == 201)
|
||||
|
||||
# --- идемпотентность с вложениями и история
|
||||
key = "att-" + uuid.uuid4().hex
|
||||
s1, _, b1 = api("POST", f"/chats/{chat}/messages", {"text": "один", "attachment_ids": [check_id]}, L.H(at, key))
|
||||
s2, _, b2 = api("POST", f"/chats/{chat}/messages", {"text": "один", "attachment_ids": [check_id]}, L.H(at, key))
|
||||
L.check("повтор с вложением и тем же ключом: тот же результат", s1 == s2 == 201 and L.js(b1) == L.js(b2), f"{s1}/{s2}")
|
||||
s3, _, _ = api("POST", f"/chats/{chat}/messages", {"text": "один", "attachment_ids": [ids[0]]}, L.H(at, key))
|
||||
L.check("тот же ключ с другим набором вложений -> 409", s3 == 409, str(s3))
|
||||
s4, _, _ = api("POST", f"/chats/{chat}/messages", {"text": "один"}, L.H(at, key))
|
||||
L.check("тот же ключ без вложений (иное тело) -> 409", s4 == 409, str(s4))
|
||||
s, _, b = api("GET", f"/chats/{chat}/messages?limit=100", headers=L.bearer(bt))
|
||||
items = (L.js(b) or {}).get("items", [])
|
||||
one = [m for m in items if m["text"] == "один"]
|
||||
L.check("в истории одно такое сообщение, attachment_ids присутствует у каждого сообщения",
|
||||
len(one) == 1 and one[0]["attachment_ids"] == [check_id] and all("attachment_ids" in m for m in items), str(len(one)))
|
||||
# скачивание вложения из сообщения вторым участником
|
||||
s, _, b = api("GET", f"/attachments/{one[0]['attachment_ids'][0]}/content", headers=L.bearer(bt))
|
||||
L.check("вложение из истории скачивается вторым участником", s == 200 and b == PNG, str(s))
|
||||
|
||||
|
||||
def upload_stop(api, hook, index=0):
|
||||
"""Загрузка -> остановка именно той реплики, что приняла файл -> скачивание через другую реплику.
|
||||
index выбирает, какая из двух реплик (по отсортированному X-Instance-Id) принимает файл и затем останавливается."""
|
||||
(an, aid, at), (bn, bid, bt), _, chat, _ = setup(api)
|
||||
ids = sorted({api("GET", "/users/me", headers=L.bearer(at))[1].get("x-instance-id") for _ in range(16)} - {None})
|
||||
L.check("через LB видны >= 2 реплик", len(ids) >= 2, str(ids))
|
||||
want = ids[index % len(ids)]
|
||||
att, h = {}, {}
|
||||
for _ in range(12): # round-robin: повторяем загрузку, пока файл не примет выбранная реплика
|
||||
s, h, b = upload(api, at, chat, PNG)
|
||||
att = L.js(b) or {}
|
||||
if s != 201 or h.get("x-instance-id") == want:
|
||||
break
|
||||
target = h.get("x-instance-id")
|
||||
L.check(f"файл принят выбранной репликой {target}", s == 201 and target == want, f"{s} {target} want={want}")
|
||||
s, _, b = api("POST", f"/chats/{chat}/messages", {"text": "до отказа", "attachment_ids": [att["id"]]}, L.H(at))
|
||||
mid = (L.js(b) or {}).get("id")
|
||||
t0 = time.time()
|
||||
# абсолютный путь: относительный «scripts/x.cmd» cmd.exe воспринимает как ключ «/x.cmd»; вывод читаем как байты
|
||||
r = subprocess.run([os.path.abspath(hook)], env={**os.environ, "TARGET_INSTANCE_ID": target}, capture_output=True, timeout=60)
|
||||
L.check(f"hook остановил реплику {target} (код {r.returncode}, {time.time() - t0:.1f} с)", r.returncode == 0,
|
||||
(r.stderr or b"")[-200:].decode("utf-8", "replace"))
|
||||
ok_at, instances = None, set()
|
||||
for _ in range(200):
|
||||
s, h, b = api("GET", f"/attachments/{att['id']}/content", headers=L.bearer(bt))
|
||||
if s == 200 and b == PNG:
|
||||
ok_at = time.time() - t0
|
||||
instances.add(h.get("x-instance-id"))
|
||||
break
|
||||
time.sleep(0.1)
|
||||
L.check("после остановки реплики вложение скачивается через другую реплику (байты те же)",
|
||||
ok_at is not None and target not in instances, f"{ok_at} {instances}")
|
||||
if ok_at is not None:
|
||||
print(f"INFO: вложение снова доступно через {ok_at:.2f} с после запуска hook (реплика {sorted(instances)})")
|
||||
s, _, b = api("GET", f"/chats/{chat}/messages", headers=L.bearer(bt))
|
||||
L.check("подтверждённое сообщение с вложением доступно", any(m["id"] == mid and m["attachment_ids"] == [att["id"]] for m in (L.js(b) or {}).get("items", [])))
|
||||
seen = {api("GET", f"/attachments/{att['id']}", headers=L.bearer(bt))[1].get("x-instance-id") for _ in range(20)}
|
||||
L.check("остановленная реплика больше не отвечает", target not in seen, str(seen))
|
||||
|
||||
|
||||
def s3_outage(api):
|
||||
"""Сбой S3 при живых API и PostgreSQL: вложения деградируют (503), остальное работает; после старта S3 всё возвращается."""
|
||||
stop = shlex.split(os.environ.get("S3_STOP_CMD", "docker compose stop s3"))
|
||||
start = shlex.split(os.environ.get("S3_START_CMD", "docker compose start s3"))
|
||||
(an, aid, at), (bn, bid, bt), _, chat, _ = setup(api)
|
||||
s, _, b = upload(api, at, chat, PNG)
|
||||
att = (L.js(b) or {}).get("id")
|
||||
L.check("до сбоя: загрузка -> 201", s == 201, str(s))
|
||||
subprocess.run(stop, cwd=ROOT, check=True, capture_output=True, timeout=180)
|
||||
t_stop = time.time()
|
||||
try:
|
||||
time.sleep(1)
|
||||
t0 = time.time()
|
||||
s, _, b = upload(api, at, chat, PNG)
|
||||
L.check("S3 остановлен: загрузка -> 503 (code unavailable), %.1f с" % (time.time() - t0),
|
||||
s == 503 and (L.js(b) or {}).get("error", {}).get("code") == "unavailable", f"{s} {b[:80]}")
|
||||
s, _, _ = api("GET", f"/attachments/{att}/content", headers=L.bearer(bt))
|
||||
L.check("S3 остановлен: скачивание -> 503, а не 500/зависание", s == 503, str(s))
|
||||
s, _, _ = api("GET", f"/attachments/{att}", headers=L.bearer(bt))
|
||||
L.check("S3 остановлен: метаданные (только PostgreSQL) -> 200", s == 200, str(s))
|
||||
s, _, _ = api("POST", f"/chats/{chat}/messages", {"text": "текст без S3"}, L.H(at))
|
||||
L.check("S3 остановлен: обычное сообщение -> 201", s == 201, str(s))
|
||||
s, _, _ = api("POST", f"/chats/{chat}/messages", {"text": "со ссылкой", "attachment_ids": [att]}, L.H(at))
|
||||
L.check("S3 остановлен: сообщение со старым вложением -> 201 (только PostgreSQL)", s == 201, str(s))
|
||||
s, _, _ = L.call(api.base.rsplit("/api/v1", 1)[0], "GET", "/health/ready")
|
||||
L.check("S3 остановлен: /health/ready остаётся 200 (S3 некритичен для текстового API)", s == 200, str(s))
|
||||
finally:
|
||||
subprocess.run(start, cwd=ROOT, check=True, capture_output=True, timeout=180)
|
||||
t1, ok = time.time(), None
|
||||
for _ in range(240):
|
||||
s, _, b = upload(api, at, chat, PNG)
|
||||
if s == 201:
|
||||
ok = time.time() - t1
|
||||
break
|
||||
time.sleep(1)
|
||||
L.check("после старта S3 загрузка снова -> 201 (через %s с)" % (("%.0f" % ok) if ok is not None else "?"), ok is not None)
|
||||
# у каждой реплики свой «предохранитель» (до S3_BREAKER_SECONDS после последнего сбоя): повторяем чтение, пока не вернётся 200
|
||||
t2, got, tries = time.time(), None, 0
|
||||
for tries in range(1, 61):
|
||||
s, _, b = api("GET", f"/attachments/{att}/content", headers=L.bearer(bt))
|
||||
if s == 200 and b == PNG:
|
||||
got = time.time() - t2
|
||||
break
|
||||
time.sleep(1)
|
||||
L.check("после старта S3 старое вложение скачивается, байты те же (через %s с, попыток: %d)"
|
||||
% (("%.1f" % got) if got is not None else "?", tries), got is not None)
|
||||
print("INFO: S3 был недоступен около %.0f с" % (time.time() - t_stop))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--mode", choices=["attach", "upload-stop", "s3-outage"], default="attach")
|
||||
ap.add_argument("--stop-hook", default="")
|
||||
ap.add_argument("--target-index", type=int, default=0, help="какая из реплик (по порядку X-Instance-Id) принимает файл и будет остановлена")
|
||||
a = ap.parse_args()
|
||||
api = L.Api(a.base_url.rstrip("/"))
|
||||
if a.mode == "upload-stop":
|
||||
upload_stop(api, a.stop_hook, a.target_index)
|
||||
elif a.mode == "s3-outage":
|
||||
s3_outage(api)
|
||||
else:
|
||||
attach_checks(api)
|
||||
print(("FAIL: %d проверок не прошли: %s" % (len(L.fails), "; ".join(L.fails))) if L.fails else "PASS: все проверки режима '%s'" % a.mode)
|
||||
sys.exit(1 if L.fails else 0)
|
||||
Reference in New Issue
Block a user