"""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
import json
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.models import LADDER, RUNGS
from app.models import excerpt as models_excerpt
from app.storage import Store
from app.web import SETTINGS, TABS
from app.web.api import _score_after_change
from app.web.pages import SECTIONS
from auth import AuthConfig
from desk.models import Item
from prepped import upsert
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:
upsert(store, posting("1", company="Acme", place="Berlin", function="engineering"))
upsert(store, posting("2", company="Acme", place="Munich", function="sales"))
upsert(store, posting("3", company="Other", place="Berlin", function="engineering"))
uid = {r.source_id: r.uid for r in store.roles()}
res = client.get("/api/roles", params={"q": "engineer", "place": "Berlin"})
assert res.status_code == 200
assert {r["uid"] for r in res.json()["items"]} == {uid["1"], uid["3"]}
res = client.get("/api/roles", params={"function": "sales"})
assert [r["uid"] for r in res.json()["items"]] == [uid["2"]]
res = client.get("/api/roles", params={"company": "other"})
assert [r["uid"] for r in res.json()["items"]] == [uid["3"]]
def test_list_roles_filters_by_company_keys_places_and_seniority(
client: TestClient, store: Store) -> None:
for sid, company, place, title in (
("kbh", "Acme", "København K", "Senior Engineer"),
("malmo", "Acme", "Malmö", "Engineer"),
("billund", "Other", "Billund, Denmark", "Junior Engineer"),
("berlin", "Other", "Berlin", "Senior Engineer")):
item = posting(sid, company=company, place=place)
item.title = title
upsert(store, item)
uid = {r.source_id: r.uid for r in store.roles()}
def shown(**params: Any) -> set[str]:
res = client.get("/api/roles", params=params)
assert res.status_code == 200, res.text
assert res.json()["total"] == len(res.json()["items"])
return {sid for sid, u in uid.items() if u in {r["uid"] for r in res.json()["items"]}}
assert shown(company_keys=["acme"]) == {"kbh", "malmo"}
assert shown(company_keys=["acme", "other"]) == set(uid)
assert shown(places=["country:DK"]) == {"kbh", "billund"}
assert shown(places=["country:DK", "region:skane"]) == {"kbh", "billund", "malmo"}
assert shown(places=["place:kobenhavn"]) == {"kbh"}
assert shown(places=["Lund"]) == set() # not Billund
assert shown(level_from="senior", level_to="senior") == {"kbh", "berlin", "malmo"}
assert shown(level_from="senior", level_to="senior",
seniority_unknown="false") == {"kbh", "berlin"}
assert shown(level_from="junior", level_to="senior", seniority_unknown="false",
company_keys=["other"]) == {"billund", "berlin"}
res = client.get("/api/roles", params={"places": ["region:atlantis"]})
assert res.status_code == 422 and "region:atlantis" in res.json()["detail"]
res = client.get("/api/roles", params={"level_from": "boss"})
assert res.status_code == 422 and "boss" in res.json()["detail"]
res = client.get("/api/roles", params={"level_to": "boss"})
assert res.status_code == 422 and "level_to" in res.json()["detail"]
res = client.get("/api/roles", params={"track": "both"})
assert res.status_code == 422 and "both" in res.json()["detail"]
# The repeated `seniority` of the chip row is not a parameter any more.
assert shown(seniority=["junior"]) == set(uid)
def test_list_roles_filters_by_a_range_of_rungs_and_a_track(
client: TestClient, store: Store) -> None:
for sid, title in (("junior", "Junior Engineer"), ("senior", "Senior Engineer"),
("staff", "Staff Engineer"), ("manager", "Engineering Manager"),
("director", "Director of Engineering"), ("none", "Engineer")):
item = posting(sid)
item.title = title
upsert(store, item)
uid = {r.source_id: r.uid for r in store.roles()}
def shown(**params: Any) -> set[str]:
res = client.get("/api/roles", params=params)
assert res.status_code == 200, res.text
found = {r["uid"] for r in res.json()["items"]}
return {sid for sid, u in uid.items() if u in found}
everyone = set(uid)
assert shown() == everyone
# A range: a bound alone is open on the other side; no level passes.
assert shown(level_from="staff") == {"staff", "manager", "director", "none"}
assert shown(level_to="senior") == {"junior", "senior", "none"}
assert shown(level_from="senior", level_to="staff",
seniority_unknown="false") == {"senior", "staff", "manager"}
# A track keeps its own side and the rungs under Staff, which have none.
assert shown(track="ic", seniority_unknown="false") == {"junior", "senior", "staff"}
assert shown(track="people", seniority_unknown="false") == {
"junior", "senior", "manager", "director"}
# Both together.
assert shown(level_from="staff", track="people",
seniority_unknown="false") == {"manager", "director"}
assert shown(level_from="staff", track="ic", seniority_unknown="false") == {"staff"}
# `seniority_unknown` alone changes nothing: no bound, no track, no filter.
assert shown(seniority_unknown="false") == everyone
def test_role_facets_count_each_facet_under_the_other_filters(
client: TestClient, store: Store) -> None:
for sid, title, raw in (("a", "Senior Engineer", {"salary_min": 70000}),
("b", "Senior Engineer", {}),
("c", "Engineer", {"salary_text": "EUR 50 per hour"})):
item = posting(sid, **raw)
item.title = title
upsert(store, item)
res = client.get("/api/roles/facets",
params={"level_from": "senior", "level_to": "senior",
"seniority_unknown": "false", "pay": "stated"})
assert res.status_code == 200
body = res.json()
levels = {f["value"]: f["count"] for f in body["seniority"]}
assert (levels["senior"], levels[""], levels["junior"]) == (1, 1, 0) # a and c pay
assert body["pay"] == [{"value": "normalised", "count": 1}, # a and b are senior
{"value": "stated", "count": 0}, {"value": "", "count": 1}]
assert client.get("/api/roles/facets", params={"places": ["country:ZZ"]}).status_code == 422
assert client.get("/api/roles/facets", params={"track": "boss"}).status_code == 422
# A track counts the same levels; the facet leaves its own filter out.
res = client.get("/api/roles/facets", params={"track": "people"})
assert res.status_code == 200
assert {f["value"]: f["count"] for f in res.json()["seniority"]}["senior"] == 2
def test_suggest_companies_folds_the_name_and_leaves_out_the_hidden(
client: TestClient, store: Store) -> None:
for sid, company in (("1", "Ørsted"), ("2", "Ørsted"), ("3", "Data Minds"),
("4", "Big Data Corp"), ("5", "Big Data Corp"), ("6", "Big Data Corp"),
("7", "Metadata Ltd"), ("8", "Hidden Data")):
upsert(store, posting(sid, company=company))
agent = store.save_agent("A")
store.set_affinity(agent.id, "hidden-data", -1)
store.set_affinity(agent.id, "ørsted", 2)
def suggest(q: str, **params: Any) -> list[dict[str, Any]]:
res = client.get("/api/suggest/companies", params={"q": q, **params})
assert res.status_code == 200
return res.json()
assert suggest("orsted") == [{"key": "ørsted", "name": "Ørsted", "count": 2,
"affinity": 2}]
# A word prefix, not a substring: Metadata is not found; by open roles.
assert [c["name"] for c in suggest("data")] == ["Big Data Corp", "Data Minds"]
assert [c["name"] for c in suggest("big da")] == ["Big Data Corp"]
assert [c["name"] for c in suggest("data", limit=1)] == ["Big Data Corp"]
assert suggest("") == []
# Another agent hid nothing.
other = store.save_agent("B")
assert "Hidden Data" in [c["name"] for c in suggest("data", agent=other.id)]
def test_suggest_places_and_read_labels_back(client: TestClient, store: Store) -> None:
for sid, place in (("1", "Malmö"), ("2", "Malmö"), ("3", "Lund"),
("4", "København K"), ("5", "Kolding")):
upsert(store, posting(sid, place=place))
res = client.get("/api/suggest/places", params={"q": "ska"})
assert res.status_code == 200
assert res.json()[0] == {"token": "region:skane", "label": "Skåne", "kind": "region",
"count": 3}
tokens = [s["token"] for s in client.get("/api/suggest/places",
params={"q": "kob"}).json()]
assert "place:kobenhavn" in tokens
assert client.get("/api/suggest/places", params={"q": ""}).json() == []
res = client.get("/api/places/labels",
params={"tokens": ["country:DK", "region:skane", "place:malmo",
"region:atlantis"]})
assert res.json() == [{"token": "country:DK", "label": "Denmark"},
{"token": "region:skane", "label": "Skåne"},
{"token": "place:malmo", "label": "Malmö"}]
def test_list_roles_exposes_and_filters_by_pay(client: TestClient, store: Store) -> None:
"""`salary_text` and `salary_state` (app/models.py) are on every role the
API serves, and `pay` (`Store.PAY`) filters the feed by it, in SQL before
`limit` like the other filters."""
upsert(store, posting("normalised", salary_min=70000, salary_max=90000,
currency="EUR", salary_text="EUR 70,000 to 90,000 per year"))
upsert(store, posting("stated", salary_text="USD 45 to 60 per hour"))
upsert(store, posting("none"))
uid = {r.source_id: r.uid for r in store.roles()}
items = {r["uid"]: r for r in client.get("/api/roles").json()["items"]}
assert items[uid["normalised"]]["salary_text"] == "EUR 70,000 to 90,000 per year"
assert items[uid["normalised"]]["salary_state"] == "normalised"
assert items[uid["stated"]]["salary_state"] == "stated"
assert items[uid["none"]]["salary_state"] == ""
res = client.get("/api/roles", params={"pay": "stated"})
assert {r["uid"] for r in res.json()["items"]} == {uid["normalised"], uid["stated"]}
res = client.get("/api/roles", params={"pay": "normalised"})
assert [r["uid"] for r in res.json()["items"]] == [uid["normalised"]]
res = client.get("/api/roles", params={"pay": "stated_only"})
assert [r["uid"] for r in res.json()["items"]] == [uid["stated"]]
assert client.get("/api/roles", params={"pay": "bogus"}).status_code == 422
def test_list_roles_limit_is_bounded(client: TestClient, store: Store) -> None:
for i in range(3):
upsert(store, 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")
upsert(store, posting("1", company="Acme"))
upsert(store, posting("2", company="Other"))
agent = store.save_agent("A")
other = store.save_agent("B")
uid = {r.source_id: r.uid for r in store.roles()}
def shown(**params: Any) -> set[str]:
return {r["uid"] for r in client.get("/api/roles", params=params).json()["items"]}
assert shown() == {uid["1"], uid["2"]}
# No agent in the body: the default agent's, which is also who a list
# without `agent` hides for.
assert client.post("/api/companies/acme/affinity", json={"affinity": -1}).status_code == 200
assert shown() == {uid["2"]}
assert shown(show_muted="true") == {uid["1"], uid["2"]}
assert shown(agent=agent.id, order="newest") == {uid["2"]}
# Hidden is per agent: the other agent still sees Acme.
assert shown(agent=other.id, order="newest") == {uid["1"], uid["2"]}
assert [c["affinity"] for c in client.get("/api/companies").json()] == [-1]
assert [c["affinity"] for c in
client.get("/api/companies", params={"agent": other.id}).json()] == [0]
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")
store.set_affinity(store.save_agent("A").id, "acme", -1)
upsert(store, posting("other", company="Other"))
clock.tick()
for i in range(3):
upsert(store, posting(f"a{i}", company="Acme"))
clock.tick()
uid = {r.source_id: r.uid for r in store.roles()}
res = client.get("/api/roles", params={"limit": 1})
assert [r["uid"] for r in res.json()["items"]] == [uid["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):
upsert(store, posting(str(i)))
clock.tick()
uid = {r.source_id: r.uid for r in store.roles()}
first = client.get("/api/roles", params={"limit": 2}).json()
assert [r["uid"] for r in first["items"]] == [uid["4"], uid["3"]]
assert first["total"] == 5
rest = client.get("/api/roles", params={"limit": 2, "offset": 4}).json()
assert [r["uid"] for r in rest["items"]] == [uid["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"):
upsert(store, posting(sid))
uid = {r.source_id: r.uid for r in store.roles()}
agent = store.save_agent("A")
# No `agent` in the body: the default agent's vote.
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
assert store.votes(agent.id) == {uid["liked"]: 1}
client.post(f"/api/roles/{uid['passed']}/vote", json={"value": -1, "agent": agent.id})
client.post(f"/api/roles/{uid['fine']}/vote", json={"value": 0})
def judged(value: str, **params: Any) -> set[str]:
page = client.get("/api/roles", params={"judged": value, **params}).json()
return {r["uid"] for r in page["items"]}
assert judged("liked") == {uid["liked"]}
assert judged("passed") == {uid["passed"]}
assert judged("unjudged") == {uid["open"]}
assert judged("") == {uid["liked"], uid["passed"], uid["fine"], uid["open"]} # a pass is not hidden
assert judged("liked", agent=agent.id, order="newest") == {uid["liked"]}
assert client.get("/api/roles", params={"judged": "maybe"}).status_code == 422
assert client.get(f"/api/roles/{uid['liked']}").json()["vote"] == 1
assert client.get(f"/api/roles/{uid['liked']}", params={"agent": agent.id}).json()["vote"] == 1
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") == {uid["open"], uid["liked"]}
cleared = client.delete(f"/api/roles/{uid['passed']}/vote", params={"agent": agent.id})
assert cleared.status_code == 200 and cleared.json()["vote"] is None
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
assert client.post(f"/api/roles/{uid['open']}/vote",
json={"value": 1, "agent": 999}).status_code == 404
assert client.delete(f"/api/roles/{uid['open']}/vote", params={"agent": 999}).status_code == 404
def test_votes_are_per_agent_over_the_api(client: TestClient, store: Store) -> None:
upsert(store, posting("1"))
uid = posting("1").uid
one = store.save_agent("One")
two = store.save_agent("Two")
assert client.post(f"/api/roles/{uid}/vote", json={"value": 1, "agent": one.id}).json()["vote"] == 1
assert client.post(f"/api/roles/{uid}/vote", json={"value": -1, "agent": two.id}).json()["vote"] == -1
assert client.get(f"/api/roles/{uid}", params={"agent": one.id}).json()["vote"] == 1
assert client.get(f"/api/roles/{uid}", params={"agent": two.id}).json()["vote"] == -1
assert client.get(f"/api/roles/{uid}").json()["vote"] == 1 # the default's
assert client.get(f"/api/roles/{uid}", params={"agent": 999}).status_code == 404
def listed(**params: Any) -> list[int | None]:
return [r["vote"] for r in client.get("/api/roles", params=params).json()["items"]]
assert listed(agent=one.id, order="newest") == [1]
assert listed(agent=two.id, order="newest") == [-1]
assert listed() == [1]
def test_a_vote_or_an_affinity_needs_an_agent_to_belong_to(
client: TestClient, store: Store) -> None:
"""Nothing to vote as: a 422 with a sentence, not a vote that lands
nowhere. Reading is fine, everything is simply unjudged and neutral."""
upsert(store, posting("1"))
store.add_company("Acme", key="acme")
uid = posting("1").uid
res = client.post(f"/api/roles/{uid}/vote", json={"value": 1})
assert res.status_code == 422 and "Settings" in res.json()["detail"]
assert client.delete(f"/api/roles/{uid}/vote").status_code == 422
assert client.post("/api/companies/acme/affinity", json={"affinity": 1}).status_code == 422
assert client.get(f"/api/roles/{uid}").json()["vote"] is None
assert client.get("/api/roles").json()["items"][0]["vote"] is None
assert client.get("/api/companies").json()[0]["affinity"] == 0
def test_roles_with_an_agent_can_be_ordered_newest_and_keep_the_votes(
client: TestClient, store: Store) -> None:
clock = Clock()
store.clock = clock
for sid in ("1", "2", "3"):
upsert(store, posting(sid))
clock.tick()
uid = {r.source_id: r.uid for r in store.roles()}
agent = store.save_agent("A")
store.replace_scores(agent.id, [(uid["1"], 0.9, ""), (uid["2"], 0.1, "")]) # 3 unscored
store.set_vote(agent.id, uid["1"], 1)
page = client.get("/api/roles", params={"agent": agent.id, "order": "newest"}).json()
assert [r["uid"] for r in page["items"]] == [uid["3"], uid["2"], uid["1"]]
assert [r["score"] for r in page["items"]] == [None, None, None]
assert [r["vote"] for r in page["items"]] == [None, None, 1]
assert page["total"] == 3
scored = client.get("/api/roles", params={"agent": agent.id, "order": "score"}).json()
assert [r["uid"] for r in scored["items"]] == [uid["1"], uid["2"]]
assert client.get("/api/roles", params={"agent": agent.id,
"order": "best"}).status_code == 422
def test_a_vote_moves_a_role_in_the_ranking_at_once(
client: TestClient, store: Store) -> None:
for sid in ("a", "b", "c"):
upsert(store, posting(sid))
uid = {r.source_id: r.uid for r in store.roles()}
label = {v: k for k, v in uid.items()}
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 [(label[r["uid"]], 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:
upsert(store, 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:
upsert(store, posting("1"))
upsert(store, posting("2"))
ids = {r.source_id: r.uid for r in store.roles()}
uid = posting("1").uid
client.post(f"/api/roles/{uid}/read")
all_ = client.get("/api/roles").json()
assert {r["uid"] for r in all_["items"]} == {ids["1"], ids["2"]}
unread = client.get("/api/roles", params={"include_read": "false"}).json()
assert {r["uid"] for r in unread["items"]} == {ids["2"]}
assert unread["total"] == 1
def test_list_roles_filters_by_tags_any_and_all(client: TestClient, store: Store) -> None:
upsert(store, posting("1"))
upsert(store, 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["uid"] for r in res.json()["items"]} == {uid["1"], uid["2"]}
both = client.get("/api/roles", params={"tags": ["python", "backend"],
"tag_mode": "all"})
assert {r["uid"] for r in both.json()["items"]} == {uid["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")
agent = store.save_agent("A") # the default agent, whose hidden companies count
store.set_affinity(agent.id, "hidden", -1)
upsert(store, posting("1", company="Acme"))
upsert(store, 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:
upsert(store, 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:
upsert(store, posting("1"))
uid = posting("1").uid
for page in (client.get("/").text, client.get(f"/roles/{uid}").text):
marker = "window.ROLEDESK_LADDER = "
start = page.index(marker) + len(marker)
ladder = json.loads(page[start:page.index(";\n", start)])
assert ladder["rungs"] == list(RUNGS)
assert ladder["levels"] == {level: list(place) for level, place in LADDER.items()}
for name in ("f-level-from", "f-level-to", "f-track"):
assert f'id="{name}"' in page
assert 'id="f-seniority"' not in page
# --------------------------------------------------------------- companies
def test_companies_lists_board_and_open_role_count(
client: TestClient, store: Store) -> None:
sub = store.add_subscription("ats", "greenhouse:acme", company="Acme", board="greenhouse")
store.add_company("Acme", key="acme", ats="greenhouse", country="DK")
upsert(store, posting("1", company="Acme"), sub)
store.add_company("Other", key="other", domain="other.example") # no board found
store.add_company("Novo", key="novo", ats="taleo", # followed, not readable
careers_url="https://novo.example/careers")
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", "notes": "", "board": "greenhouse",
"subscription_id": sub.id, "on": True, "affinity": 0, "open_roles": 1,
"ats": "greenhouse", "ats_slug": "", "careers_url": "",
"country": "DK", "city": "", "domain": "", "watch": None,
"careers_opened_at": "", "failing_since": "", "failing_reason": "",
"from_search": False, "hand_reason": "", "by_hand": False,
"all_countries": False, "all_roles": False,
"reach_params": {}, "reach": "size not known yet: sized on the next pull",
"size": None, "size_checked": ""}
[other] = [c for c in res.json() if c["key"] == "other"]
assert (other["board"], other["subscription_id"], other["on"], other["ats"]) == (
"", None, None, "")
[novo] = [c for c in res.json() if c["key"] == "novo"]
assert (novo["board"], novo["subscription_id"], novo["ats"], novo["careers_url"]) == (
"", None, "taleo", "https://novo.example/careers")
assert not any(c["from_search"] for c in res.json())
# Companies with no board shown, unread or not, are the list checked by hand.
assert {c["key"] for c in res.json() if c["by_hand"]} == {"other", "novo"}
def test_judging_a_company_known_only_from_a_search_creates_its_row(
client: TestClient, store: Store) -> None:
"""Jobindex and Adzuna employers have roles and no company row. The first
affinity change makes a minimal one, named by its roles, which the
Companies list marks `from_search`, unlike a followed company without a
board, and a company whose board was detached."""
store.save_agent("A")
search = store.add_subscription("search", "jobindex:cph", label="cph", board="jobindex")
for i, name in enumerate(("Novo Nordisk A/S", "Novo Nordisk A/S", "NOVO NORDISK A/S")):
item = posting(f"n{i}", company=name)
item.source = "search"
upsert(store, item, search)
key = "novo-nordisk"
assert store.company(key) is None
res = client.post(f"/api/companies/{key}/affinity", json={"affinity": -1})
assert res.status_code == 200, res.text
assert (res.json()["name"], res.json()["affinity"]) == ("Novo Nordisk A/S", -1)
assert client.post("/api/companies/nobody/affinity", json={"affinity": 1}).status_code == 404
store.add_company("Pleo", key="pleo", domain="pleo.io") # followed, no board found
sub = store.add_subscription("ats", "lever:gone", company="Gone", board="lever")
store.add_company("Gone", key="gone")
store.set_company_board("gone", "") # detached
assert not store.subscription(sub.id).show # type: ignore[union-attr]
rows = {c["key"]: c for c in client.get("/api/companies").json()}
assert rows["gone"]["board"] == ""
assert rows[key]["from_search"] and rows[key]["open_roles"] == 3
assert (rows[key]["board"], rows[key]["ats"], rows[key]["careers_url"]) == ("", "", "")
assert not rows["pleo"]["from_search"] and not rows["gone"]["from_search"]
def test_companies_say_since_when_a_board_fails(client: TestClient, store: Store,
capsys: pytest.CaptureFixture[str],
monkeypatch: pytest.MonkeyPatch) -> None:
"""What the pull recorded, on `/api/companies` and beside `app companies
check`'s live result."""
import plugins.ats as ats
from app.cli import check_companies
store.add_subscription("ats", "greenhouse:acme", company="Acme", board="greenhouse")
store.add_company("Acme", key="acme", ats="greenhouse")
store.state["ats:failing:greenhouse:acme"] = json.dumps(
{"since": "2026-09-01T06:00:00+00:00", "reason": "404 Not Found"})
[row] = client.get("/api/companies").json()
assert (row["failing_since"], row["failing_reason"]) == (
"2026-09-01T06:00:00+00:00", "404 Not Found")
monkeypatch.setattr(ats, "fetch_board", lambda target: ([{"source_id": "1"}], True))
assert check_companies(store) == 0
assert capsys.readouterr().out.splitlines() == [
"greenhouse:acme (greenhouse:acme): now 1 roles; "
"pull: failing since 2026-09-01: 404 Not Found",
"checked 1 boards, 0 dead, 1 failing in the pull",
]
def test_set_affinity_validates_updates_and_enqueues_a_score(
client: TestClient, store: Store, queue: Any) -> None:
store.add_company("Acme", key="acme")
agent = store.save_agent("A")
other = store.save_agent("B")
# No `agent` in the body: the default agent's affinity.
res = client.post("/api/companies/acme/affinity", json={"affinity": 2})
assert res.status_code == 200
assert res.json()["affinity"] == 2
assert store.company("acme", agent.id).affinity == 2 # type: ignore[union-attr]
assert store.company("acme", other.id).affinity == 0 # type: ignore[union-attr]
assert queue.jobs.get(res.json()["score_job"]).kind == "score"
res = client.post("/api/companies/acme/affinity", json={"affinity": -1, "agent": other.id})
assert res.status_code == 200 and res.json()["affinity"] == -1
assert store.company("acme", agent.id).affinity == 2 # type: ignore[union-attr]
assert [c["affinity"] for c in client.get("/api/companies", params={"agent": other.id}).json()] == [-1]
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
assert client.post("/api/companies/acme/affinity",
json={"affinity": 1, "agent": 999}).status_code == 404
assert client.get("/api/companies", params={"agent": 999}).status_code == 404
def test_a_score_asked_for_during_a_run_is_one_follow_up_after_it(queue: Any) -> None:
"""No worker runs here (no client), so the test moves the jobs itself."""
first = _score_after_change(queue)
assert first is not None and first.dedup_key == "score"
assert _score_after_change(queue).id == first.id # queued: it will read the change
assert queue.jobs.claim({"cpu": 1}).id == first.id
during = {_score_after_change(queue).id for _ in range(10)}
assert len(during) == 1 and first.id not in during
follow = queue.jobs.get(during.pop())
assert (follow.depends_on, follow.after, follow.dedup_key) == (
[first.id], "done", f"score:after:{first.id}")
queue.jobs.finish(first.id, "done")
assert _score_after_change(queue).id == follow.id # queued, not started: still the one
assert queue.jobs.claim({"cpu": 1}).id == follow.id
after = _score_after_change(queue)
assert after.id not in (first.id, follow.id) and after.dedup_key == "score"
def test_post_score_answers_with_the_job_to_wait_for(client: TestClient, queue: Any) -> None:
res = client.post("/api/score")
assert res.status_code == 200
assert queue.jobs.get(res.json()["id"]).kind == "score"
# ------------------------------------------------------------- watchlist
def test_the_watchlist_rating_is_global_and_leaves_affinity_alone(
client: TestClient, store: Store) -> None:
store.add_company("Acme", ats="workday")
agent = store.save_agent("A")
store.set_affinity(agent.id, "acme", 1)
for watch, stored in ((True, 1), (False, 0), (None, None)):
res = client.post("/api/companies/acme/watch", json={"watch": watch})
assert res.status_code == 200 and res.json()["watch"] == stored
listed = client.get("/api/companies").json()[0]
assert (listed["watch"], listed["affinity"]) == (stored, 1)
def test_the_careers_page_is_set_cleared_and_must_be_a_web_address(
client: TestClient, store: Store) -> None:
store.add_company("Acme")
res = client.post("/api/companies/acme/careers", json={"careers_url": "https://a.example/jobs"})
assert res.status_code == 200 and res.json()["careers_url"] == "https://a.example/jobs"
for bad in ("javascript:alert(1)", "a.example/jobs", "ftp://a.example"):
assert client.post("/api/companies/acme/careers",
json={"careers_url": bad}).status_code == 422
assert store.company("acme").careers_url == "https://a.example/jobs"
cleared = client.post("/api/companies/acme/careers", json={"careers_url": ""})
assert cleared.status_code == 200 and store.company("acme").careers_url == ""
def test_opening_the_careers_page_stamps_the_time(client: TestClient, store: Store) -> None:
store.add_company("Acme")
assert client.get("/api/companies").json()[0]["careers_opened_at"] == ""
res = client.post("/api/companies/acme/opened")
assert res.status_code == 200
assert res.json()["careers_opened_at"] == store.company("acme").careers_opened_at != ""
assert client.get("/api/companies").json()[0]["careers_opened_at"] != ""
def test_the_watchlist_endpoints_404_for_an_unknown_company(client: TestClient) -> None:
assert client.post("/api/companies/nope/watch", json={"watch": True}).status_code == 404
assert client.post("/api/companies/nope/careers",
json={"careers_url": "https://a.example"}).status_code == 404
assert client.post("/api/companies/nope/opened").status_code == 404
# ----------------------------------------------------------- applications
def test_save_creates_an_application_with_a_saved_event(
client: TestClient, store: Store) -> None:
upsert(store, 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:
upsert(store, 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:
upsert(store, posting("1", company="Acme"))
upsert(store, 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", "Watchlist"]
assert [t.label for t in SETTINGS] == ["Search agents", "Sources", "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_rail_entry_are_current_on_a_settings_page(client: TestClient) -> None:
page = client.get("/settings/sources").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/sources"')
assert 'class="icon active"' not in client.get("/").text
def test_every_settings_page_has_the_rail_and_not_the_tab_row(client: TestClient) -> None:
"""The rail replaces the `
Settings
` and the sub-tab row: every
page, then the Sources sections indented under Sources, from any page."""
for tab in SETTINGS:
page = client.get(tab.path).text
assert '