Files
jobboard/auth/tests/harness.py
T

108 lines
3.6 KiB
Python

"""An app to lock, built here rather than imported.
`auth/` has to survive being copied into a project that has never heard of this
one, so its tests are not allowed to reach for `app/` or `pipeline/` either --
`tests/test_coupling.py` reads the imports of every file under this folder and
says so. What they need is a FastAPI app with a page, an API route, a socket,
and a couple of neighbours to prove the open list is matched the way it claims.
That is this file, and it is nine routes and a stand-in for the broadcaster
the socket subscribes to.
A module rather than a conftest fixture because two tests build the same
database twice, to see what a restart does, and a fixture cannot be asked for
twice in one test.
"""
from __future__ import annotations
import os
from collections.abc import Iterable
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import PlainTextResponse
from auth import AuthConfig, AuthStore, confirm_current, connect
class Bus:
"""What `auth.close_ended_sockets` reads off `app.state.bus`: the open
sockets and a way to close some. A stand-in for `pipeline.web.broadcaster.
Broadcaster`, which this folder may not import, with its two members."""
def __init__(self) -> None:
self.held: set[WebSocket] = set()
@property
def sockets(self) -> tuple[WebSocket, ...]:
return tuple(self.held)
async def close(self, sockets: Iterable[WebSocket], code: int, reason: str = "") -> int:
gone = [ws for ws in sockets if ws in self.held]
for ws in gone:
self.held.discard(ws)
await ws.close(code, reason)
return len(gone)
def build(db: str | os.PathLike[str], *, host: str = "0.0.0.0",
**settings: object) -> FastAPI:
"""One app, locked or not depending on what it is told the server binds."""
app = FastAPI()
connect(app, AuthStore(db), AuthConfig(**settings), host=host,
open=("/static/",), stylesheet="/static/app.css")
app.state.bus = bus = Bus()
@app.get("/", response_class=PlainTextResponse)
def front() -> str:
return "the front page"
@app.get("/deep/page", response_class=PlainTextResponse)
def deep() -> str:
return "a page someone bookmarked"
@app.get("/api/thing")
def thing() -> dict[str, bool]:
return {"ok": True}
@app.post("/thing/replace")
def replace(request: Request) -> dict[str, bool]:
"""A route that swaps the database as a file would: the current
password first, in its header, before any body."""
confirm_current(request)
return {"ok": True}
@app.get("/health")
def health() -> dict[str, bool]:
return {"ok": True}
# The neighbours, so "matched whole, not as a prefix" is proved against
# routes that exist rather than against two 404s.
@app.get("/healthz")
def healthz() -> dict[str, bool]:
return {"ok": True}
@app.get("/loginx", response_class=PlainTextResponse)
def loginx() -> str:
return "not the login page"
@app.get("/static/app.css", response_class=PlainTextResponse)
def stylesheet() -> str:
return "body { }"
@app.websocket("/ws/jobs")
async def socket(ws: WebSocket) -> None:
"""Held open until the client leaves or the bus closes it, as the
app's `/ws/jobs` is."""
await ws.accept()
bus.held.add(ws)
try:
await ws.send_json({"type": "jobs"})
while True:
await ws.receive_text()
except WebSocketDisconnect:
pass
finally:
bus.held.discard(ws)
return app