Files
jobboard/pipeline/tests/test_connect.py
T
WolfandClaude Fable 5.1 3a240e51df Pull pipeline/ from boilerplate a80ad8a: cadence picker, queue badge, label refresh
The schedule cadence is a picker, the add row is behind a button and off
here, a running-jobs chip with Kill and Stop run sits in every header, and
a declared schedule's label is refreshed at startup.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 16:22:46 +02:00

116 lines
4.1 KiB
Python

"""The web face of the queue, from an app that has written nothing but `connect`.
python -m pytest pipeline/tests/test_web.py -q
"""
from __future__ import annotations
import sys
import tempfile
import time
from contextlib import asynccontextmanager
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
pytest.importorskip("fastapi")
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pipeline import NULL, Jobs, RunContext, job
from pipeline.web import connect, jobs_router
@job("w_hello", "Saying hello")
def w_hello(config, store, *, context: RunContext = NULL, name: str = "") -> dict:
context.progress(1, 1, f"greeting {name}")
return {"said": f"hello {name}", "config": config["app"]}
@pytest.fixture
def jobs():
with tempfile.TemporaryDirectory() as tmp:
yield Jobs(Path(tmp) / "web.db")
def settled(client: TestClient, job_id: int, timeout: float = 10.0) -> dict:
"""The job as the HTTP API reports it, once it has finished."""
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
snap = client.get("/api/jobs").json()
for row in snap["recent"]:
if row["id"] == job_id:
return row
time.sleep(0.05)
raise AssertionError(f"job {job_id} did not finish")
def test_connect_is_the_whole_of_the_wiring(jobs):
"""Routes, socket and a running worker, from one call.
The app below has nothing else: no lifespan, no broadcaster, no router of
its own. A job enqueued over HTTP runs to `done` because the worker came up
with the app, and the socket hands a new tab the current state on connect.
"""
app = FastAPI()
queue = connect(app, jobs, {"app": "tiny"}, None)
assert app.state.queue is queue
with TestClient(app) as client:
made = client.post("/api/jobs", json={"kind": "w_hello",
"payload": {"name": "you"}})
assert made.status_code == 202, made.text
ended = settled(client, made.json()["id"])
assert ended["state"] == "done"
assert ended["result"] == {"said": "hello you", "config": "tiny"}
with client.websocket_connect("/ws/jobs") as socket:
hello = socket.receive_json()
assert hello["type"] == "jobs"
assert any(row["id"] == ended["id"] for row in hello["recent"])
assert queue._task is None or queue._task.done(), "and it stopped with the app"
def test_connect_keeps_the_apps_own_lifespan(jobs):
"""An app with startup code of its own keeps it, and the worker is already
up when that code runs — so startup code may enqueue."""
seen: list[str] = []
@asynccontextmanager
async def lifespan(app: FastAPI):
seen.append("app started")
app.state.queue.enqueue("w_hello", {"name": "from startup"})
yield
seen.append("app stopped")
app = FastAPI(lifespan=lifespan)
connect(app, jobs, {"app": "tiny"}, None)
with TestClient(app) as client:
# By id: the snapshot reads live and recent jobs separately, so a job
# that finishes in between is listed in both.
snap = client.get("/api/jobs").json()
(job_id,) = {r["id"] for r in snap["queued"] + snap["running"]
+ snap["recent"] if r["kind"] == "w_hello"}
assert settled(client, job_id)["state"] == "done"
assert seen == ["app started", "app stopped"]
def test_the_element_is_served_by_the_queues_own_router():
"""Two lines in a template and a new app has a job list. Served from a
route, because a router cannot mount a static directory and needing the
app to mount one is the setup the element exists to remove."""
app = FastAPI()
app.include_router(jobs_router)
answer = TestClient(app).get("/_jobs/jobs.js")
assert answer.status_code == 200
assert answer.headers["content-type"].startswith("text/javascript")
assert 'customElements.define("desk-jobs"' in answer.text
# The top bar's chip rides in the same file, so it needs no route.
assert 'customElements.define("desk-queue"' in answer.text