"""The tabs and the JSON API they call, against a temp database and FastAPI's
TestClient. No network — nothing here touches an ATS host or the queue's own
worker beyond starting and stopping it with the app."""
from __future__ import annotations
from collections.abc import Iterator
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.config import Config, ServerConfig
from app.main import create_app
from app.storage import Store
from app.web import MOVED, SETTINGS, TABS
from auth import AuthConfig
from desk.models import Item
class Clock:
"""A controllable `Store.clock`, for tests that need upserts to land at
distinct, known moments — see `test_storage.py`'s twin of this."""
def __init__(self) -> None:
self.at = datetime(2026, 9, 23, 9, 0, tzinfo=UTC)
def __call__(self) -> datetime:
return self.at
def tick(self, hours: float = 1) -> None:
self.at += timedelta(hours=hours)
def posting(source_id: str = "1", **raw: object) -> Item:
item = Item(source_id=source_id, location=f"https://boards.example/acme/{source_id}",
title="Senior Backend Engineer", body="Build things.",
published_at=datetime(2026, 9, 20, tzinfo=UTC), raw=dict(raw))
item.source = "ats"
return item
@pytest.fixture
def app(tmp_path: Path) -> FastAPI:
"""The database in `tmp_path` and the config passed in, so a test never
touches `roledesk.db` and two tests never share a jobs table."""
return create_app(Config(server=ServerConfig(host="127.0.0.1", port=0),
database=tmp_path / "roledesk.db"))
@pytest.fixture
def store(app: FastAPI) -> Store:
return app.state.store
@pytest.fixture
def queue(app: FastAPI) -> Any:
return app.state.queue
@pytest.fixture
def client(app: FastAPI) -> Iterator[TestClient]:
with TestClient(app) as c:
yield c
# ------------------------------------------------------------------- roles
def test_list_roles_filters_by_query_place_and_function(
client: TestClient, store: Store) -> None:
store.upsert_role(posting("1", company="Acme", place="Berlin", function="engineering"))
store.upsert_role(posting("2", company="Acme", place="Munich", function="sales"))
store.upsert_role(posting("3", company="Other", place="Berlin", function="engineering"))
res = client.get("/api/roles", params={"q": "engineer", "place": "Berlin"})
assert res.status_code == 200
assert {r["source_id"] for r in res.json()["items"]} == {"1", "3"}
res = client.get("/api/roles", params={"function": "sales"})
assert [r["source_id"] for r in res.json()["items"]] == ["2"]
res = client.get("/api/roles", params={"company": "other"})
assert [r["source_id"] for r in res.json()["items"]] == ["3"]
def test_list_roles_limit_is_bounded(client: TestClient, store: Store) -> None:
for i in range(3):
store.upsert_role(posting(str(i)))
assert len(client.get("/api/roles", params={"limit": 1}).json()["items"]) == 1
assert client.get("/api/roles", params={"limit": 0}).status_code == 422
assert client.get("/api/roles", params={"limit": 1001}).status_code == 422
def test_muted_roles_are_hidden_unless_show_muted(client: TestClient, store: Store) -> None:
store.add_company("Acme", key="acme")
store.upsert_role(posting("1", company="Acme"))
store.upsert_role(posting("2", company="Other"))
assert {r["source_id"] for r in client.get("/api/roles").json()["items"]} == {"1", "2"}
assert client.post("/api/companies/acme/affinity", json={"affinity": -1}).status_code == 200
assert {r["source_id"] for r in client.get("/api/roles").json()["items"]} == {"2"}
assert {r["source_id"] for r in
client.get("/api/roles", params={"show_muted": "true"}).json()["items"]} == {"1", "2"}
def test_muted_is_excluded_before_the_limit_not_after(
client: TestClient, store: Store) -> None:
"""A regression case: filtering a muted company out of an already
`LIMIT`-ed page can leave nothing to show, if that company happens to be
the newest thing in the database — exactly what a company with hundreds
of roles, all freshly (re-)pulled at once, produces."""
clock = Clock()
store.clock = clock
store.add_company("Acme", key="acme", affinity=-1)
store.upsert_role(posting("other", company="Other"))
clock.tick()
for i in range(3):
store.upsert_role(posting(f"a{i}", company="Acme"))
clock.tick()
res = client.get("/api/roles", params={"limit": 1})
assert [r["source_id"] for r in res.json()["items"]] == ["other"]
assert res.json()["total"] == 1
def test_list_roles_pages_by_offset_and_counts_the_total(
client: TestClient, store: Store) -> None:
clock = Clock()
store.clock = clock
for i in range(5):
store.upsert_role(posting(str(i)))
clock.tick()
first = client.get("/api/roles", params={"limit": 2}).json()
assert [r["source_id"] for r in first["items"]] == ["4", "3"]
assert first["total"] == 5
rest = client.get("/api/roles", params={"limit": 2, "offset": 4}).json()
assert [r["source_id"] for r in rest["items"]] == ["0"] and rest["total"] == 5
assert client.get("/api/roles", params={"offset": 9}).json() == {"items": [], "total": 5}
assert client.get("/api/roles", params={"offset": -1}).status_code == 422
assert len(client.get("/api/roles").json()["items"]) == 5 # default 60
def test_a_vote_is_set_cleared_and_filtered_on(client: TestClient, store: Store) -> None:
for sid in ("liked", "passed", "fine", "open"):
store.upsert_role(posting(sid))
uid = {r.source_id: r.uid for r in store.roles()}
res = client.post(f"/api/roles/{uid['liked']}/vote", json={"value": 1})
assert res.status_code == 200
assert res.json()["vote"] == 1 and res.json()["voted_at"] is not None
client.post(f"/api/roles/{uid['passed']}/vote", json={"value": -1})
client.post(f"/api/roles/{uid['fine']}/vote", json={"value": 0})
def judged(value: str) -> set[str]:
page = client.get("/api/roles", params={"judged": value}).json()
return {r["source_id"] for r in page["items"]}
assert judged("liked") == {"liked"}
assert judged("passed") == {"passed"}
assert judged("unjudged") == {"open"}
assert judged("") == {"liked", "passed", "fine", "open"} # a pass is not hidden
assert client.get("/api/roles", params={"judged": "maybe"}).status_code == 422
cleared = client.delete(f"/api/roles/{uid['liked']}/vote")
assert cleared.status_code == 200
assert cleared.json()["vote"] is None and cleared.json()["voted_at"] is None
assert judged("unjudged") == {"open", "liked"}
assert client.post(f"/api/roles/{uid['open']}/vote",
json={"value": 2}).status_code == 422
assert client.post("/api/roles/nope/vote", json={"value": 1}).status_code == 404
assert client.delete("/api/roles/nope/vote").status_code == 404
def test_a_vote_moves_a_role_in_the_ranking_at_once(
client: TestClient, store: Store) -> None:
for sid in ("a", "b", "c"):
store.upsert_role(posting(sid))
uid = {r.source_id: r.uid for r in store.roles()}
agent = store.save_agent("A")
store.replace_scores(agent.id, [(uid["a"], 0.9, ""), (uid["b"], 0.6, ""),
(uid["c"], 0.55, "")])
def ranked() -> list[tuple[str, float]]:
page = client.get("/api/roles", params={"agent": agent.id}).json()
return [(r["source_id"], round(r["score"], 3)) for r in page["items"]]
assert ranked() == [("a", 0.9), ("b", 0.6), ("c", 0.55)]
client.post(f"/api/roles/{uid['a']}/vote", json={"value": -1})
client.post(f"/api/roles/{uid['c']}/vote", json={"value": 1})
assert ranked() == [("c", 0.66), ("b", 0.6), ("a", 0.45)]
client.post(f"/api/roles/{uid['b']}/vote", json={"value": 0})
client.post(f"/api/roles/{uid['a']}/vote", json={"value": 1})
assert ranked() == [("a", 1.0), ("c", 0.66), ("b", 0.6)] # capped at 1
def test_read_state_is_set_and_cleared_over_the_api(client: TestClient, store: Store) -> None:
store.upsert_role(posting("1"))
uid = posting("1").uid
res = client.post(f"/api/roles/{uid}/read")
assert res.status_code == 200
assert res.json()["read_at"] is not None
res = client.delete(f"/api/roles/{uid}/read")
assert res.status_code == 200
assert res.json()["read_at"] is None
assert client.post("/api/roles/nope/read").status_code == 404
assert client.delete("/api/roles/nope/read").status_code == 404
def test_list_roles_filters_by_include_read(client: TestClient, store: Store) -> None:
store.upsert_role(posting("1"))
store.upsert_role(posting("2"))
uid = posting("1").uid
client.post(f"/api/roles/{uid}/read")
all_ = client.get("/api/roles").json()
assert {r["source_id"] for r in all_["items"]} == {"1", "2"}
unread = client.get("/api/roles", params={"include_read": "false"}).json()
assert {r["source_id"] for r in unread["items"]} == {"2"}
assert unread["total"] == 1
def test_list_roles_filters_by_tags_any_and_all(client: TestClient, store: Store) -> None:
store.upsert_role(posting("1"))
store.upsert_role(posting("2"))
uid = {r.source_id: r.uid for r in store.roles()}
store.set_tags(uid["1"], ["python", "backend"])
store.set_tags(uid["2"], ["python", "frontend"])
res = client.get("/api/roles", params={"tags": ["python"]})
assert {r["source_id"] for r in res.json()["items"]} == {"1", "2"}
both = client.get("/api/roles", params={"tags": ["python", "backend"],
"tag_mode": "all"})
assert {r["source_id"] for r in both.json()["items"]} == {"1"}
[item] = both.json()["items"]
assert item["tags"] == ["backend", "python"]
def test_filters_lists_tag_counts_and_respects_show_muted(
client: TestClient, store: Store) -> None:
store.add_company("Hidden", key="hidden", affinity=-1)
store.upsert_role(posting("1", company="Acme"))
store.upsert_role(posting("2", company="Hidden"))
uid = {r.source_id: r.uid for r in store.roles(hide_muted=False)}
store.set_tags(uid["1"], ["python"])
store.set_tags(uid["2"], ["python"])
res = client.get("/api/filters")
assert res.status_code == 200
assert res.json() == {"tags": [{"tag": "python", "count": 1, "unread": 1}]}
muted = client.get("/api/filters", params={"show_muted": "true"})
assert muted.json() == {"tags": [{"tag": "python", "count": 2, "unread": 2}]}
def test_one_role_and_its_read_page(client: TestClient, store: Store) -> None:
store.upsert_role(posting("1", company="Acme", place="Berlin"))
uid = posting("1").uid
res = client.get(f"/api/roles/{uid}")
assert res.status_code == 200
body = res.json()
assert (body["uid"], body["company"], body["description"]) == (uid, "Acme",
"Build things.")
assert body["vote"] is None and body["summary"] == "" and body["article_text"] == ""
assert client.get("/api/roles/nope").status_code == 404
page = client.get(f"/roles/{uid}")
assert page.status_code == 200
assert '
' in page.text and "/static/roles.js" in page.text
missing = client.get("/roles/nope")
assert missing.status_code == 404 and "text/html" in missing.headers["content-type"]
def test_the_roles_page_offers_the_judged_filter_and_hidden_companies(
client: TestClient) -> None:
page = client.get("/").text
assert 'id="f-judged"' in page and " None:
sub = store.add_subscription("ats", "greenhouse:acme", company="Acme", board="greenhouse")
store.add_company("Acme", key="acme")
store.upsert_role(posting("1", company="Acme"), sub)
store.add_company("Other", key="other") # known only from a search: no board
res = client.get("/api/companies")
assert res.status_code == 200
[row] = [c for c in res.json() if c["key"] == "acme"]
assert row == {"key": "acme", "name": "Acme", "board": "greenhouse",
"subscription_id": sub.id, "on": True, "affinity": 0, "open_roles": 1}
[other] = [c for c in res.json() if c["key"] == "other"]
assert (other["board"], other["subscription_id"], other["on"]) == ("", None, None)
def test_set_affinity_validates_updates_and_enqueues_a_score(
client: TestClient, store: Store, queue: Any) -> None:
store.add_company("Acme", key="acme")
res = client.post("/api/companies/acme/affinity", json={"affinity": 2})
assert res.status_code == 200
assert res.json()["affinity"] == 2
assert store.company("acme").affinity == 2 # type: ignore[union-attr]
assert queue.jobs.last("score", states=("queued", "running", "done")) is not None
assert client.post("/api/companies/acme/affinity", json={"affinity": 9}).status_code == 422
assert client.post("/api/companies/nope/affinity", json={"affinity": 1}).status_code == 404
# ----------------------------------------------------------- applications
def test_save_creates_an_application_with_a_saved_event(
client: TestClient, store: Store) -> None:
store.upsert_role(posting("1", company="Acme", place="Berlin"))
uid = posting("1").uid
res = client.post("/api/applications", json={"role_uid": uid, "status": "saved"})
assert res.status_code == 201
body = res.json()
assert body["role_uid"] == uid
assert body["status"] == "saved"
assert body["company_key"] == "acme"
# No placeholder: a next step is the CLI's to set.
assert body["next_action"] == "" and body["next_date"] is None
events = store.application_events(body["id"])
assert [e.status for e in events] == ["saved"]
# Saving the same role again returns the existing row rather than a
# second one.
again = client.post("/api/applications", json={"role_uid": uid, "status": "saved"})
assert again.json()["id"] == body["id"]
listed = client.get("/api/applications").json()
assert [a["id"] for a in listed] == [body["id"]]
assert listed[0]["role_title"] == "Senior Backend Engineer"
def test_save_an_unknown_role_is_refused(client: TestClient) -> None:
res = client.post("/api/applications", json={"role_uid": "nope", "status": "saved"})
assert res.status_code == 404
def test_set_status_validates_and_writes_an_event(
client: TestClient, store: Store) -> None:
store.upsert_role(posting("1", company="Acme"))
uid = posting("1").uid
saved = client.post("/api/applications", json={"role_uid": uid}).json()
res = client.post(f"/api/applications/{saved['id']}/status", json={"status": "applied"})
assert res.status_code == 200
assert res.json()["status"] == "applied"
assert [e.status for e in store.application_events(saved["id"])] == ["saved", "applied"]
assert client.post(f"/api/applications/{saved['id']}/status",
json={"status": "ghosted"}).status_code == 422
assert client.post("/api/applications/nope/status",
json={"status": "applied"}).status_code == 404
def test_unsave_drops_a_saved_application_and_refuses_one_that_moved_on(
client: TestClient, store: Store) -> None:
store.upsert_role(posting("1", company="Acme"))
store.upsert_role(posting("2", company="Acme"))
first = client.post("/api/applications", json={"role_uid": posting("1").uid}).json()
second = client.post("/api/applications", json={"role_uid": posting("2").uid}).json()
assert client.delete(f"/api/applications/{first['id']}").status_code == 204
assert store.application(first["id"]) is None
assert store.application_events(first["id"]) == []
assert client.delete(f"/api/applications/{first['id']}").status_code == 404
client.post(f"/api/applications/{second['id']}/status", json={"status": "applied"})
refused = client.delete(f"/api/applications/{second['id']}")
assert refused.status_code == 409 and "withdrawn" in refused.json()["detail"]
assert store.application(second["id"]) is not None
def test_the_applications_page_has_no_next_column(client: TestClient) -> None:
page = client.get("/applications").text
assert "
Next
" not in page and "
Saved
" in page
# -------------------------------------------------------------------- tabs
def test_every_page_renders_with_the_whole_nav(client: TestClient) -> None:
assert [t.label for t in TABS] == ["Roles", "Applications"]
assert [t.label for t in SETTINGS] == ["Ranking", "Searches", "Companies", "Pulls",
"Messages", "Account"]
assert all(t.path.startswith("/settings/") for t in SETTINGS)
for tab in (*TABS, *SETTINGS):
res = client.get(tab.path)
assert res.status_code == 200, f"{tab.path} answered {res.status_code}"
assert "roledesk" in res.text
for other in TABS:
assert f">{other.label}" in res.text
assert 'href="/settings" class="icon' in res.text
assert '' in res.text
def test_the_cog_and_one_sub_tab_are_current_on_a_settings_page(client: TestClient) -> None:
page = client.get("/settings/pulls").text
assert 'class="icon active"' in page
for tab in SETTINGS:
assert f">{tab.label}" in page
assert page.count('aria-current="page"') == 1
current = page.index('aria-current="page"')
assert page.rindex('href="', 0, current) == page.index('href="/settings/pulls"')
assert 'class="icon active"' not in client.get("/").text
def test_settings_is_ranking(client: TestClient) -> None:
res = client.get("/settings", follow_redirects=False)
assert res.status_code == 302 and res.headers["location"] == "/settings/ranking"
@pytest.mark.parametrize(("old", "new"), sorted(MOVED.items()))
def test_an_old_tab_moves_permanently_and_keeps_its_query(
client: TestClient, old: str, new: str) -> None:
res = client.get(old, follow_redirects=False)
assert res.status_code == 301 and res.headers["location"] == new
res = client.get(f"{old}?agent=3&q=a+b", follow_redirects=False)
assert res.status_code == 301 and res.headers["location"] == f"{new}?agent=3&q=a+b"
assert client.get(old).status_code == 200
def test_each_page_loads_only_its_own_script(client: TestClient) -> None:
scripts = {"roles.js", "applications.js", "ranking.js", "companies.js", "sources.js",
"jobs.js", "messages.js"}
for path, container, script in [
("/", 'id="roles-list"', "roles.js"),
("/applications", 'id="applications-list"', "applications.js"),
("/settings/ranking", 'id="ranking-form"', "ranking.js"),
("/settings/searches", 'id="searches-list"', "sources.js"),
("/settings/companies", 'id="companies-list"', "companies.js"),
("/settings/pulls", 'id="kinds"', "jobs.js"),
("/settings/messages", 'id="notices"', "messages.js")]:
page = client.get(path).text
assert container in page, path
assert [s for s in scripts if f"/static/{s}" in page] == [script], path
# toasts.js before app.js before the page's own script: `api()` needs
# `window.toast`, and every page script needs `api()` and the helpers.
assert page.index("toasts.js") < page.index("app.js") < page.index(f"/static/{script}")
assert client.get(f"/static/{script}").status_code == 200
assert "ROLEDESK_STATUSES" in client.get("/applications").text
def test_the_ranking_page_edits_one_ranking(client: TestClient) -> None:
page = client.get("/settings/ranking").text
assert 'id="a-intent"' in page and " None:
page = client.get("/settings/searches").text
assert 'id="searches-list"' in page
assert 'value="1" selected>Region Hovedstaden' in page # from plugins.search
# Boards and the prune tool moved to Companies; a search has no board.
assert 'id="boards-list"' not in page and 'id="prune-form"' not in page
assert 'id="pull-now"' not in page # moved to Pulls
def test_the_companies_page_offers_the_follow_form_and_the_prune_tool(
client: TestClient) -> None:
page = client.get("/settings/companies").text
assert 'id="companies-list"' in page
assert 'id="b-host"' in page and 'id="b-slug"' in page and 'id="b-name"' in page
assert '