Files
mtusi2026lab5/tests/crash_grade5.py
T
2026-11-12 15:32:10 +03:00

130 lines
3.1 KiB
Python

import json
import subprocess
import sys
import time
from pathlib import Path
from client import Client, check
ROOT = Path(__file__).resolve().parents[1]
OVERRIDE = ROOT / "compose.fault.yaml"
POINTS = ("before_side_effect", "after_side_effect", "before_ack")
CONTAINER = "mtusi2026lab5-worker-1"
def command(*args):
return subprocess.run(
args,
cwd=ROOT,
capture_output=True,
text=True,
check=True,
)
def configure(point):
OVERRIDE.write_text(
"services:\n"
" worker:\n"
" environment:\n"
' FAULT_INJECTION_ENABLED: "1"\n'
f" FAULT_INJECTION_POINT: {point}\n",
encoding="utf-8",
)
command(
"docker", "compose",
"-f", "compose.yaml",
"-f", "compose.fault.yaml",
"up", "-d", "--force-recreate", "worker",
)
def restore():
command(
"docker", "compose",
"up", "-d", "--force-recreate", "worker",
)
def restart_count():
result = command(
"docker", "inspect",
"-f", "{{.RestartCount}}",
CONTAINER,
)
return int(result.stdout.strip())
def crash_logged(point):
result = command(
"docker", "logs", CONTAINER,
)
return f"FAULT INJECTION: {point}" in result.stderr + result.stdout
def run_case(point):
print(f"RUN: {point}", flush=True)
configure(point)
client = Client()
alice, bob, _, chat = client.bootstrap()
attachment, original = client.attachment(alice, chat)
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
if restart_count() >= 1 and crash_logged(point):
break
time.sleep(0.5)
else:
raise AssertionError(f"{point}: worker did not crash")
ready = client.wait_ready(bob, attachment, wait_seconds=150)
check(ready["status"] == "ready", f"{point}: not ready")
content = client.call(
"GET",
f"/api/v1/attachments/{attachment['id']}/content",
actor=bob,
)
check(content["bytes"] == original, f"{point}: original changed")
for variant in ("thumbnail", "crop", "optimized"):
response = client.call(
"GET",
f"/api/v1/attachments/{attachment['id']}/content?variant={variant}",
actor=bob,
)
check(bool(response["bytes"]), f"{point}: {variant} is empty")
check(restart_count() == 1, f"{point}: unexpected restart count")
print(
f"PASS: {point}, recovered, original and variants intact",
flush=True,
)
def main():
try:
for point in POINTS:
run_case(point)
finally:
print("Restoring normal worker configuration...", flush=True)
restore()
print("FAULT INJECTION DISABLED", flush=True)
if __name__ == "__main__":
try:
main()
except (AssertionError, subprocess.CalledProcessError, OSError) as exc:
print(f"FAIL: {exc}", file=sys.stderr)
raise SystemExit(1)