"""What the JSON API and the config decide, that the reviews of 2026-09-30 found wrong: a board's reach stored as ISO codes, an empty seniority range, Fetch text answering as the viewing agent, the model a stage will use, and a starter search on any reader. No network.""" from __future__ import annotations from collections.abc import Iterator from datetime import UTC, datetime from pathlib import Path import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from app import config as config_mod from app.config import Config, ConfigError, ServerConfig from app.main import create_app from app.storage import Store from desk.models import Item from prepped import upsert ROOT = Path(__file__).resolve().parents[1] @pytest.fixture def app(tmp_path: Path) -> FastAPI: 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 client(app: FastAPI) -> Iterator[TestClient]: with TestClient(app) as c: yield c def _role(store: Store, source_id: str = "1", title: str = "Senior Backend Engineer") -> str: item = Item(source_id=source_id, location=f"https://boards.example/acme/{source_id}", title=title, body="A teaser.", published_at=datetime(2026, 9, 20, tzinfo=UTC), raw={}) item.source = "ats" upsert(store, item) return item.uid # ---------------------------------------------------------- a board's reach @pytest.fixture def board(store: Store) -> int: return store.add_subscription("ats", "greenhouse:acme", label="Acme", company="Acme", board="greenhouse").id def test_the_reach_countries_are_stored_as_iso_codes( client: TestClient, store: Store, board: int) -> None: res = client.post(f"/api/sources/{board}/reach", json={"mode": "own", "countries": ["UK", "Germany", "dk"]}) assert res.status_code == 200, res.text sub = store.subscription(board) assert sub is not None and sub.params["countries"] == ["DE", "DK", "GB"] def test_a_reach_country_that_is_none_is_refused( client: TestClient, store: Store, board: int) -> None: res = client.post(f"/api/sources/{board}/reach", json={"mode": "own", "countries": ["Atlantis"]}) assert res.status_code == 422 and "Atlantis" in res.text sub = store.subscription(board) assert sub is not None and "countries" not in sub.params def test_a_company_row_names_its_attached_board_in_full( client: TestClient, store: Store, board: int) -> None: """The Replace-board confirm compares the typed `host:slug` with this, not with `board` (the host) or `ats_slug` (the careers site's).""" store.add_company("Acme") row = next(c for c in client.get("/api/companies").json() if c["key"] == "acme") assert (row["board"], row["target"]) == ("greenhouse", "greenhouse:acme") # ------------------------------------------------------ the seniority range @pytest.mark.parametrize("path", ["/api/roles", "/api/roles/facets"]) @pytest.mark.parametrize("query", ["level_from=senior&level_to=junior", "level_from=exec&track=ic"]) def test_a_seniority_range_with_no_level_is_refused_not_ignored( client: TestClient, store: Store, path: str, query: str) -> None: _role(store) res = client.get(f"{path}?{query}") assert res.status_code == 422 and "no level" in res.text def test_a_seniority_range_with_levels_still_filters(client: TestClient, store: Store) -> None: _role(store) assert client.get("/api/roles?level_from=junior&level_to=senior").status_code == 200 assert client.get("/api/roles/facets?track=ic").status_code == 200 # --------------------------------------------------------------- Fetch text def test_fetch_text_answers_with_the_viewing_agents_vote( client: TestClient, store: Store, monkeypatch: pytest.MonkeyPatch) -> None: from app.jobs import posting agent = store.save_agent("Wolf", intent="backend") uid = _role(store) store.set_vote(agent.id, uid, 1) monkeypatch.setattr(posting, "fetch_posting", lambda s, u: s.set_article_text(u, "The whole posting.")) res = client.post(f"/api/roles/{uid}/text?agent={agent.id}") assert res.status_code == 200, res.text assert (res.json()["vote"], res.json()["article_text"]) == (1, "The whole posting.") # The default agent when none is named, as the other role routes read it. assert client.post(f"/api/roles/{uid}/text").json()["vote"] == 1 assert client.post(f"/api/roles/{uid}/text?agent=999").status_code == 404 # ------------------------------------------------------------------- stages def test_a_stage_shows_the_model_that_will_answer(tmp_path: Path) -> None: config = Config(database=tmp_path / "x.db") app = create_app(config) with TestClient(app) as client: by_name = {s["name"]: s for s in client.get("/api/stages").json()} assert by_name["extract"]["model"] == config.extract.model config.agent.model = "claude-opus-4-1" by_name = {s["name"]: s for s in client.get("/api/stages").json()} assert by_name["extract"]["model"] == by_name["summarise"]["model"] == "claude-opus-4-1" assert by_name["fetch_text"]["model"] == "" # ------------------------------------------------------------------- config def test_a_platsbanken_search_loads(tmp_path: Path) -> None: path = tmp_path / "config.yaml" path.write_text("searches:\n - {name: Sverige, provider: platsbanken, params: {q: python}}\n", encoding="utf-8") assert config_mod.load(path).searches[0].provider == "platsbanken" def test_a_search_provider_that_is_no_reader_names_the_readers(tmp_path: Path) -> None: path = tmp_path / "config.yaml" path.write_text("searches:\n - {name: X, provider: monster}\n", encoding="utf-8") with pytest.raises(ConfigError, match="jobindex, adzuna, platsbanken"): config_mod.load(path) def test_the_example_config_holds_every_default() -> None: """Each value in `config.example.yaml` is the default, so a copy changes nothing; a key added there with another value, or a key the code does not read, fails here.""" loaded = config_mod.load(ROOT / "config.example.yaml").model_dump(exclude={"path"}) assert loaded == Config().model_dump(exclude={"path"}) def test_the_example_config_names_every_key_of_the_sections_it_documents() -> None: import yaml raw = yaml.safe_load((ROOT / "config.example.yaml").read_text("utf-8")) for name, allowed_missing in (("agent", set()), ("extract", set()), ("fetch_text", set()), ("embed", set()), ("workers", set()), ("summarise", {"on_ingest"})): # accepted, ignored fields = set(type(getattr(Config(), name)).model_fields) # `credentials_database` is filled from `database`, never read from the file. fields -= {"credentials_database"} assert fields - set(raw[name]) == allowed_missing, name