Files
mtusi2026lab6/student_tests/test_worker_lifecycle.py
T

145 lines
5.5 KiB
Python

"""Демонстрация: worker остановлен → 202 queued → worker запущен → ready.
Требует docker compose. Запуск:
python3 student_tests/test_worker_lifecycle.py --base-url http://localhost:8080
"""
from __future__ import annotations
import base64
import json
import subprocess
import sys
import time
import urllib.error
import urllib.request
import uuid
from pathlib import Path
BASE = (
sys.argv[sys.argv.index("--base-url") + 1]
if "--base-url" in sys.argv
else "http://localhost:8080"
)
ROOT = Path(__file__).resolve().parent.parent
def call(method, path, headers=None, body=None, raw=None):
data = None
h = dict(headers or {})
if body is not None:
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
h["Content-Type"] = "application/json"
elif raw is not None:
data = raw
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
try:
resp = urllib.request.urlopen(req, timeout=30)
payload = resp.read()
return resp.status, json.loads(payload) if payload else None, dict(resp.headers)
except urllib.error.HTTPError as e:
payload = e.read()
try:
return e.code, json.loads(payload) if payload else None, dict(e.headers)
except Exception:
return e.code, None, dict(e.headers)
def compose(*args, check=True):
return subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
check=check, capture_output=True, text=True, cwd=str(ROOT),
)
def main():
# 1. Регистрация, логин, чат
username = "lifecycle_" + uuid.uuid4().hex[:10]
password = "lifecycle-pass-1234567890"
code, user, _ = call("POST", "/api/v1/users", body={
"username": username, "display_name": "Lifecycle", "password": password,
})
assert code == 201, f"register failed: {code} {user}"
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
code, session, _ = call("POST", "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + cred})
assert code == 201, f"login failed: {code}"
token = session["token"]
code, chat, _ = call("POST", "/api/v1/chats",
headers={"Authorization": "Bearer " + token},
body={"title": "Lifecycle", "member_ids": [user["id"]]})
assert code == 201, f"chat failed: {code}"
chat_id = chat["id"]
# 2. Остановить worker
compose("stop", "worker")
print("worker stopped")
try:
# 3. Upload — 202 queued
fixture = (ROOT / "tests/fixtures/sample.png").read_bytes()
code, att, _ = call(
"POST",
f"/api/v1/chats/{chat_id}/attachments?filename=sample.png",
headers={"Authorization": "Bearer " + token, "Content-Type": "image/png"},
raw=fixture,
)
assert code == 202, f"upload expected 202, got {code}"
assert att["status"] == "queued", f"expected queued, got {att['status']}"
att_id = att["id"]
print(f"upload: 202 queued ({att_id})")
# 4. Через 3 секунды — всё ещё queued
time.sleep(3)
code, att, _ = call("GET", f"/api/v1/attachments/{att_id}",
headers={"Authorization": "Bearer " + token})
assert code == 200, f"get failed: {code}"
assert att["status"] == "queued", f"expected queued, got {att['status']}"
print(f"after 3s: still queued")
# 5. Запустить worker
try:
compose("up", "-d", "--no-deps", "worker")
except subprocess.CalledProcessError as exc:
print(f"START FAILED: {exc.stderr}", file=sys.stderr)
raise
# 6. Ждём ready (до 60 сек)
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
code, att, _ = call("GET", f"/api/v1/attachments/{att_id}",
headers={"Authorization": "Bearer " + token})
if code == 200 and att["status"] == "ready":
break
if code == 200 and att["status"] == "failed":
raise AssertionError(f"attachment failed: {att['error_code']}")
time.sleep(0.5)
else:
raise AssertionError("attachment did not become ready in 60s")
# 7. Проверяем variants
variants = [v for v in att["variants"] if v["name"] == "thumbnail"]
assert len(variants) == 1, f"expected 1 thumbnail, got {len(variants)}"
v = variants[0]
assert (v["width"], v["height"]) == (256, 160), \
f"thumbnail dimensions wrong: {v['width']}x{v['height']}"
print(f"after worker start: ready, thumbnail {v['width']}x{v['height']}")
# 8. Скачиваем thumbnail (бинарный ответ)
req = urllib.request.Request(
BASE + f"/api/v1/attachments/{att_id}/content?variant=thumbnail",
headers={"Authorization": "Bearer " + token},
)
try:
resp = urllib.request.urlopen(req, timeout=30)
except urllib.error.HTTPError as e:
raise AssertionError(f"thumbnail download failed: {e.code}")
thumb_bytes = resp.read()
assert thumb_bytes[:2] == b"\xff\xd8", "not a JPEG"
print(f"thumbnail downloaded: {len(thumb_bytes)} bytes, JPEG")
finally:
# 9. Гарантированно вернуть worker
compose("up", "-d", "--no-deps", "worker", check=False)
if __name__ == "__main__":
main()