From 0ebaa852f6e585e5fc170d0930db7c461803db74 Mon Sep 17 00:00:00 2001 From: Wolf Date: Wed, 30 Sep 2026 15:44:32 +0200 Subject: [PATCH] Store a board's reach countries as ISO codes and refuse an empty seniority range Co-Authored-By: Claude Fable 5.1 --- app/web/api.py | 38 +++++++-- tests/test_api_reach.py | 171 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 201 insertions(+), 8 deletions(-) create mode 100644 tests/test_api_reach.py diff --git a/app/web/api.py b/app/web/api.py index c71d3ea..5bb86ae 100644 --- a/app/web/api.py +++ b/app/web/api.py @@ -98,7 +98,13 @@ def _feed_filters( raise HTTPException(422, f"{name} is one of {', '.join(RUNGS)}, not {rung!r}.") if track and track not in TRACKS: raise HTTPException(422, f"track is one of {', '.join(TRACKS)}, not {track!r}.") - levels = levels_between(level_from, level_to, track) if level_from or level_to or track else [] + levels: tuple[str, ...] = () + if level_from or level_to or track: + # The store reads an empty list as "no filter", so a range that holds no + # level must be refused here or it would list every role. + levels = levels_between(level_from, level_to, track) + if not levels: + raise HTTPException(422, "That seniority range holds no level.") return { "q": q or None, "company": company or None, "place": place or None, "function": function or None, "remote": remote or None, "days": days, @@ -359,14 +365,21 @@ def _known_role(store: Store, uid: str) -> Role: @router.post("/roles/{uid}/text") -def fetch_text(uid: str, store: StoreDep) -> Role: +def fetch_text(uid: str, store: StoreDep, agent: int | None = None) -> ScoredRole: """Fetch the posting page once and keep it as plain text, for a role whose description is a teaser (`jobs.posting.fetch_posting`); a Jobindex role - is read from the page its "Se jobbet" link leads to.""" + is read from the page its "Se jobbet" link leads to. The role comes back as + `agent` sees it, as `GET /api/roles/{uid}` does: the page merges the answer + into the open role, and one without the vote would blank the reader's.""" + agent_id = _agent_id(store, agent) try: - return jobs.posting.fetch_posting(store, uid) + jobs.posting.fetch_posting(store, uid) except jobs.posting.PostingError as exc: raise HTTPException(exc.status, str(exc)) from exc + role = store.role(uid, agent_id) + if role is None: + raise HTTPException(404, f"no such role: {uid}") + return role @router.post("/roles/{uid}/summarise", status_code=202) @@ -436,12 +449,17 @@ class CompanyOut(BaseModel): with no board shown that is not `from_search`, and `hand_reason` says why it is read by hand (`app.models.HAND_REASONS`). `all_countries` and `all_roles` are the company's two fetch overrides: its big boards read - with the agents' wide reach, and with no role-type narrowing.""" + with the agents' wide reach, and with no role-type narrowing. `target` is + the attached board in full, `host:slug`, where `board` is its host alone; + the page compares it with the board typed to know whether a replacement + closes anything. `ats_slug` cannot stand in for it, since the careers site + may run on another host than the board.""" key: str name: str notes: str = "" board: str + target: str = "" subscription_id: int | None = None on: bool | None = None affinity: int @@ -500,6 +518,7 @@ def _company_outs(store: Store, agent: int | None) -> list[CompanyOut]: sub = subs.get(sub_id) if sub_id is not None else None from_search = jobs.sources.known_from_search_only(c, ever_boarded) out.append(CompanyOut(key=c.key, name=c.name, notes=c.notes, board=host, + target=target, subscription_id=sub_id, on=on, affinity=c.affinity, open_roles=counts.get(c.key, 0), ats=c.ats, ats_slug=c.ats_slug, careers_url=c.careers_url, @@ -865,9 +884,12 @@ def set_reach(sub_id: int, body: ReachBody, store: StoreDep) -> dict[str, Any]: sub = store.subscription(sub_id) if sub is None or sub.source != "ats": raise HTTPException(404, f"no such board: {sub_id}") - codes = sorted({c.strip().upper() for c in body.countries if c.strip()}) - if unknown := [c for c in codes if not places.known(f"country:{c}") or c == "EU"]: - raise HTTPException(422, f"Not a country code: {', '.join(unknown)}.") + named = sorted({c.strip() for c in body.countries if c.strip()}) + tokens = {c: places.parse(f"country:{c}") for c in named} + if unknown := [c for c, t in tokens.items() if not places.known(str(t)) or t.value == "EU"]: + raise HTTPException(422, f"Not a country: {', '.join(unknown)}.") + # The ISO code is what the reach compares against, not the name or alias typed. + codes = sorted({t.value for t in tokens.values()}) if body.mode == "own" and not (codes or body.remote): raise HTTPException(422, "Name a country or remote, or take the agents' reach.") params = {k: v for k, v in sub.params.items() if k not in jobs.reach.OVERRIDE_KEYS} diff --git a/tests/test_api_reach.py b/tests/test_api_reach.py new file mode 100644 index 0000000..0361893 --- /dev/null +++ b/tests/test_api_reach.py @@ -0,0 +1,171 @@ +"""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["enrich"]["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()), ("enrich", 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