laba 5 mark 4
This commit is contained in:
@@ -0,0 +1,158 @@
|
||||
"""Shared helpers for the student's explicit lab5 checks; never log tokens."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from uuid import UUID
|
||||
|
||||
from PIL import Image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
|
||||
|
||||
def encoded(image: Image.Image, format: str = "PNG", **options) -> bytes:
|
||||
output = io.BytesIO()
|
||||
image.save(output, format=format, **options)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def upload(client, actor, chat, content, *, filename="sample.png", mime="image/png"):
|
||||
from urllib.parse import quote
|
||||
result = client.call(
|
||||
"POST", f"/api/v1/chats/{chat['id']}/attachments?filename={quote(filename, safe='')}",
|
||||
202, actor=actor, raw=content, headers={"Content-Type": mime}, schema="Attachment",
|
||||
)["json"]
|
||||
check(result["status"] == "queued", "upload must return its queued snapshot")
|
||||
check(result["variants"] == [], "queued snapshot must not expose partial variants")
|
||||
return result
|
||||
|
||||
|
||||
def metadata(client, actor, attachment_id):
|
||||
return client.call("GET", f"/api/v1/attachments/{attachment_id}", actor=actor,
|
||||
schema="Attachment")["json"]
|
||||
|
||||
|
||||
def wait_until(predicate, message, timeout=90, interval=0.3):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
value = predicate()
|
||||
if value:
|
||||
return value
|
||||
time.sleep(interval)
|
||||
raise Failure(message)
|
||||
|
||||
|
||||
class Stand:
|
||||
"""Control only containers bearing this lab's Compose project label."""
|
||||
|
||||
def __init__(self):
|
||||
self.project = os.environ.get("COMPOSE_PROJECT", "messenger-lab5")
|
||||
|
||||
@staticmethod
|
||||
def docker(*args, stdin=None, timeout=70):
|
||||
process = subprocess.run(["docker", *args], input=stdin, text=True,
|
||||
capture_output=True, timeout=timeout)
|
||||
# Docker command output can contain secrets: do not echo it on errors.
|
||||
if process.returncode:
|
||||
raise Failure(f"docker {args[0]} failed (exit {process.returncode})")
|
||||
return process.stdout.strip()
|
||||
|
||||
def ids(self, service, *, all=True):
|
||||
args = ["ps", "-q"]
|
||||
if all:
|
||||
args.append("-a")
|
||||
args += ["--filter", f"label=com.docker.compose.project={self.project}",
|
||||
"--filter", f"label=com.docker.compose.service={service}"]
|
||||
return self.docker(*args).split()
|
||||
|
||||
def one(self, service):
|
||||
ids = self.ids(service)
|
||||
check(len(ids) == 1, f"expected one {service} container")
|
||||
return ids[0]
|
||||
|
||||
def stop(self, *services):
|
||||
ids = [cid for service in services for cid in self.ids(service)]
|
||||
check(bool(ids), "containers to stop were not found")
|
||||
self.docker("stop", "--time", "3", *ids)
|
||||
|
||||
def start(self, *services):
|
||||
ids = [cid for service in services for cid in self.ids(service)]
|
||||
check(bool(ids), "containers to start were not found")
|
||||
self.docker("start", *ids)
|
||||
|
||||
def restart(self, *services):
|
||||
ids = [cid for service in services for cid in self.ids(service)]
|
||||
self.docker("restart", "--time", "3", *ids)
|
||||
|
||||
def sql(self, statement):
|
||||
return self.docker("exec", "-i", self.one("db"), "psql", "-U", "messenger",
|
||||
"-d", "messenger", "-v", "ON_ERROR_STOP=1", "-tA",
|
||||
stdin=statement)
|
||||
|
||||
def row(self, attachment_id):
|
||||
aid = str(UUID(attachment_id))
|
||||
value = self.sql(f"SELECT row_to_json(a) FROM attachments a WHERE id='{aid}';")
|
||||
check(bool(value), "attachment row disappeared")
|
||||
return json.loads(value)
|
||||
|
||||
def operator(self, *args):
|
||||
# Use a running API image so stopping worker/publisher is supported.
|
||||
apis = self.ids("api", all=False)
|
||||
check(bool(apis), "no API available for operator command")
|
||||
return self.docker("exec", apis[0], "python", "-m", "app.operator", *args)
|
||||
|
||||
def objects_exist(self, keys):
|
||||
code = """
|
||||
import asyncio, json, sys
|
||||
from app.storage import storage
|
||||
async def main():
|
||||
await storage.start()
|
||||
try:
|
||||
print(json.dumps([await storage.exists(key) for key in json.load(sys.stdin)]))
|
||||
finally:
|
||||
await storage.close()
|
||||
asyncio.run(main())
|
||||
"""
|
||||
apis = self.ids("api", all=False)
|
||||
return json.loads(self.docker("exec", "-i", apis[0], "python", "-c", code,
|
||||
stdin=json.dumps(keys)))
|
||||
|
||||
def replace_object(self, key, content, mime="image/png"):
|
||||
"""Explicit fault-test operation; key must come from this test's DB row."""
|
||||
import base64
|
||||
code = """
|
||||
import asyncio, base64, io, json, sys
|
||||
from app.storage import storage
|
||||
async def main():
|
||||
key, encoded, mime = json.load(sys.stdin)
|
||||
content = base64.b64decode(encoded)
|
||||
await storage.start()
|
||||
try:
|
||||
await storage.put(key, io.BytesIO(content), len(content), mime)
|
||||
finally:
|
||||
await storage.close()
|
||||
asyncio.run(main())
|
||||
"""
|
||||
self.docker("exec", "-i", self.ids("api", all=False)[0], "python", "-c", code,
|
||||
stdin=json.dumps([key, base64.b64encode(content).decode(), mime]))
|
||||
|
||||
def ready(self):
|
||||
for service in ("db", "broker", "api", "lb"):
|
||||
for cid in self.ids(service):
|
||||
raw = self.docker("inspect", "--format", "{{json .State}}", cid)
|
||||
state = json.loads(raw)
|
||||
if not state.get("Running"):
|
||||
return False
|
||||
if "Health" in state and state["Health"]["Status"] != "healthy":
|
||||
return False
|
||||
return True
|
||||
|
||||
def wait_ready(self):
|
||||
wait_until(self.ready, "stand did not recover readiness", timeout=90)
|
||||
Reference in New Issue
Block a user