creative-brain-os / tests /test_phase3_platform.py
kpranav022's picture
Claude Fable 5.1
Ask one question at a time, show the wait, let the brief lead, and keep refusals, faces and voices in hand
af66f2f
Raw History Blame Contribute Delete
5.6 kB
"""Phase 3 platform: the production media guard, rediss:// TLS, and start.sh roles."""
from __future__ import annotations
import asyncio
import os
import shutil
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import pytest
from app.core.config import settings
from app.main import app, lifespan
from app.tasks.signals import check_media_backend
ROOT = Path(__file__).resolve().parents[1]
def _start_api() -> None:
async def run() -> None:
async with lifespan(app):
pass
# Own thread: an earlier test in the suite can leave a loop running on this one.
with ThreadPoolExecutor(1) as pool:
pool.submit(asyncio.run, run()).result()
@pytest.mark.parametrize(
("env", "backend", "refuses"),
[("production", "local", True), ("development", "local", False), ("production", "r2", False)],
)
def test_production_needs_r2(monkeypatch, env, backend, refuses):
monkeypatch.setattr(settings, "app_env", env)
monkeypatch.setattr(settings, "storage_backend", backend)
if refuses:
with pytest.raises(RuntimeError, match="STORAGE_BACKEND=r2"):
_start_api()
# SystemExit: Celery swallows an Exception raised by a signal handler.
with pytest.raises(SystemExit, match="STORAGE_BACKEND=r2"):
check_media_backend()
else:
_start_api()
check_media_backend()
@pytest.mark.parametrize(
("url", "reqs"),
[
("rediss://default:pw@example.upstash.io:6379", 2), # CERT_REQUIRED by default
("rediss://default:pw@example.upstash.io:6379?ssl_cert_reqs=none", 0), # URL wins
("redis://localhost:6379/0", None),
],
)
def test_celery_tls_redis(url, reqs):
# A fresh interpreter: the Celery app is built once, at import.
code = (
"from app.tasks.celery_app import celery_app as a\n"
"print(a.backend.connparams.get('ssl_cert_reqs'))\n"
"ssl = a.connection_for_write().ssl\n"
"print(int(ssl['ssl_cert_reqs']) if ssl else None)\n"
)
out = subprocess.run(
[sys.executable, "-c", code], cwd=ROOT, env={**os.environ, "REDIS_URL": url},
capture_output=True, text=True, check=True,
).stdout.split()
assert out[-2:] == [str(reqs), str(reqs)]
def test_start_sh_syntax():
subprocess.run(["bash", "-n", str(ROOT / "start.sh")], check=True)
def _run_start(
tmp_path: Path, expect: int = 1, stubs: tuple[str, ...] = (), readonly: bool = False, **env: str
) -> tuple[int, list[str]]:
"""Run a copy of start.sh with redis-server, celery and uvicorn stubbed to log
their argv, so nothing real starts. Waits (briefly) for `expect` log lines:
in the all role the celery stub is backgrounded and may log after exit."""
bin_dir = tmp_path / "bin"
bin_dir.mkdir(parents=True)
log = tmp_path / "calls.log"
for name in ("redis-server", "celery", "uvicorn"):
stub = bin_dir / name
stub.write_text(f'#!/usr/bin/env bash\necho "{name} $*" >> "{log}"\n')
stub.chmod(0o755)
for name in stubs: # extra commands that just fail
(bin_dir / name).write_text("#!/usr/bin/env bash\nexit 1\n")
(bin_dir / name).chmod(0o755)
script_dir = tmp_path / "app"
script_dir.mkdir()
shutil.copy(ROOT / "start.sh", script_dir / "start.sh")
if readonly: # like a root-owned /app under a non-root user
script_dir.chmod(0o555)
base = {"PATH": f"{bin_dir}:/usr/bin:/bin", "HOME": str(tmp_path)}
proc = subprocess.run(
["bash", str(script_dir / "start.sh")], env={**base, **env}, capture_output=True, timeout=30, check=False,
)
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
calls = log.read_text().splitlines() if log.exists() else []
if len(calls) >= expect:
break
time.sleep(0.05)
return proc.returncode, sorted(calls)
def test_start_sh_roles(tmp_path):
worker = "celery -A app.tasks.celery_app:celery_app worker -l INFO -Q creative"
celery = f"{worker} --concurrency 4" # four at a time by default: renders wait on fal
uvicorn = "uvicorn app.main:app --host 0.0.0.0 --port 7860"
code, calls = _run_start(tmp_path / "all", expect=3)
redis = "redis-server --daemonize yes --save --appendonly yes --dir {}"
assert code == 0 and calls == sorted([celery, redis.format(tmp_path / "all" / "app" / "redis-data"), uvicorn])
# Unwritable script dir: falls back to /tmp.
code, calls = _run_start(tmp_path / "ro", expect=3, readonly=True)
(tmp_path / "ro" / "app").chmod(0o755)
assert code == 0 and calls == sorted([celery, redis.format("/tmp/redis-data"), uvicorn])
# No writable dir at all: starts anyway, without persistence.
code, calls = _run_start(tmp_path / "none", expect=3, stubs=("mkdir",))
assert code == 0 and calls == sorted(
[celery, "redis-server --daemonize yes --save --appendonly no", uvicorn]
)
# An external Redis: the bundled one stays off.
_, calls = _run_start(tmp_path / "ext", expect=2, REDIS_URL="rediss://x.upstash.io:6379")
assert calls == [celery, uvicorn]
_, calls = _run_start(tmp_path / "api", PROCESS_ROLE="api", PORT="8000")
assert calls == ["uvicorn app.main:app --host 0.0.0.0 --port 8000"]
_, calls = _run_start(tmp_path / "worker", PROCESS_ROLE="worker", WORKER_CONCURRENCY="2")
assert calls == [f"{worker} --concurrency 2"]
code, calls = _run_start(tmp_path / "bad", expect=0, PROCESS_ROLE="web")
assert code == 1 and calls == []