| 1 | """Story search: each readable board is searched for the run's story terms. |
| 2 | |
| 3 | Boards with a keyword search are asked once per term before their |
| 4 | newest-first read; boards read whole are matched where they are. Every |
| 5 | matched row carries the term it matched, and a role found both ways is one |
| 6 | row. |
| 7 | """ |
| 8 | |
| 9 | from __future__ import annotations |
| 10 | |
| 11 | import copy |
| 12 | import json |
| 13 | import threading |
| 14 | import time |
| 15 | from pathlib import Path |
| 16 | from unittest.mock import patch |
| 17 | |
| 18 | import pytest |
| 19 | |
| 20 | from lib import health, http, jobs, jobs_digest, render |
| 21 | |
| 22 | WINDOW = ("2026-10-15", "2026-11-14") |
| 23 | FIXTURES = Path(__file__).parent / "fixtures" |
| 24 | AMAZON = json.loads((FIXTURES / "jobs_amazon_search.json").read_text(encoding="utf-8")) |
| 25 | PCSX = json.loads((FIXTURES / "jobs_eightfold_pcsx.json").read_text(encoding="utf-8")) |
| 26 | |
| 27 | |
| 28 | def _missing(url, *_args, **_kwargs): |
| 29 | raise http.HTTPError("HTTP 404: Not Found", status_code=404) |
| 30 | |
| 31 | |
| 32 | # --- Workday: the site's own search, through ``searchText`` --- |
| 33 | |
| 34 | WORKDAY_SITE = "https://www.acme.com" |
| 35 | WORKDAY_PAGE = '<a href="https://acme.wd5.myworkdayjobs.com/en-US/AcmeCareers">Jobs</a>' |
| 36 | |
| 37 | |
| 38 | def _workday_row(index, title=None): |
| 39 | return { |
| 40 | "title": title or f"Role {index}", |
| 41 | "externalPath": f"/job/Remote/Role-{index}_JR{index}", |
| 42 | "locationsText": "Remote", |
| 43 | "postedOn": "Posted Today", |
| 44 | "bulletFields": [f"JR{index}"], |
| 45 | } |
| 46 | |
| 47 | |
| 48 | class WorkdayBoard: |
| 49 | """A 40-role Workday board whose own search matches titles.""" |
| 50 | |
| 51 | def __init__(self): |
| 52 | self.rows = [_workday_row(index) for index in range(40)] |
| 53 | # One match inside the rows the newest-first read reaches, one past it. |
| 54 | self.rows[3] = _workday_row(3, "Humanoid Controls Engineer") |
| 55 | self.rows[35] = _workday_row(35, "Humanoid Hand Designer") |
| 56 | self.bodies = [] |
| 57 | self.lock = threading.Lock() |
| 58 | |
| 59 | def post(self, url, json_data, headers=None, **_kwargs): |
| 60 | with self.lock: |
| 61 | self.bodies.append(dict(json_data)) |
| 62 | term = json_data["searchText"].lower() |
| 63 | rows = [row for row in self.rows if term in row["title"].lower()] if term else self.rows |
| 64 | offset = json_data["offset"] |
| 65 | return {"total": len(rows) if offset == 0 else 0, |
| 66 | "jobPostings": rows[offset:offset + json_data["limit"]]} |
| 67 | |
| 68 | def get(self, url, headers=None, **_kwargs): |
| 69 | return {"jobPostingInfo": {"jobDescription": f"<p>Own {url}.</p>", "startDate": "2026-11-03"}} |
| 70 | |
| 71 | def search(self, terms, *, ceiling=20): |
| 72 | pools = [] |
| 73 | real_select = jobs_digest.select_roles |
| 74 | |
| 75 | def select(items, **kwargs): |
| 76 | pools.append(list(items)) |
| 77 | return real_select(items, **kwargs) |
| 78 | |
| 79 | with patch.object(jobs, "WORKDAY_ROW_CEILING", ceiling), \ |
| 80 | patch.object(jobs.http, "get_text", |
| 81 | side_effect=lambda url, **_k: None if url.endswith("/robots.txt") else WORKDAY_PAGE), \ |
| 82 | patch.object(jobs.http, "post", side_effect=self.post), \ |
| 83 | patch.object(jobs.http, "get", side_effect=self.get), \ |
| 84 | patch.object(jobs.jobs_digest, "select_roles", side_effect=select): |
| 85 | items, artifact = jobs.search_jobs( |
| 86 | "Acme", WINDOW, {"_jobs_story_terms": terms}, web_backend="none", site=WORKDAY_SITE, |
| 87 | ) |
| 88 | return items, artifact, pools |
| 89 | |
| 90 | |
| 91 | def test_workday_story_term_is_sent_as_search_text_before_the_listing_and_matches_are_tagged(): |
| 92 | board = WorkdayBoard() |
| 93 | items, artifact, pools = board.search(["humanoid"]) |
| 94 | |
| 95 | assert board.bodies[0]["searchText"] == "humanoid" |
| 96 | assert [body["searchText"] for body in board.bodies[1:]] == [""] * (len(board.bodies) - 1) |
| 97 | tagged = {item["title"]: item.get("story_term") for item in items if item.get("story_term")} |
| 98 | assert tagged == {"Humanoid Controls Engineer": "humanoid"} |
| 99 | # The match the newest-first read did not reach is offered to the digest, |
| 100 | # tagged, and is not one of the board's rows. |
| 101 | pool = {item["title"]: item.get("story_term") for item in pools[0]} |
| 102 | assert pool["Humanoid Hand Designer"] == "humanoid" |
| 103 | assert "Humanoid Hand Designer" not in {item["title"] for item in items} |
| 104 | assert len(items) == 20 and artifact["open_roles"] == 20 |
| 105 | assert artifact["story_search"] == { |
| 106 | "ran": True, "terms": ["humanoid"], "matches": 2, "story_partial": False, |
| 107 | } |
| 108 | |
| 109 | |
| 110 | def test_a_story_match_past_the_read_takes_a_digest_slot_with_its_fetched_text(): |
| 111 | board = WorkdayBoard() |
| 112 | board.rows = [_workday_row(index) for index in range(100)] |
| 113 | board.rows[90] = _workday_row(90, "Humanoid Hand Designer") |
| 114 | _items, artifact, _pools = board.search(["humanoid"], ceiling=60) |
| 115 | |
| 116 | roles = artifact["digest"]["roles"] |
| 117 | assert len(roles) == jobs_digest.DIGEST_MAX_ROLES |
| 118 | first = roles[0] |
| 119 | assert (first["title"], first["story_term"]) == ("Humanoid Hand Designer", "humanoid") |
| 120 | assert first["text"] == "Own https://acme.wd5.myworkdayjobs.com/wday/cxs/acme/AcmeCareers/job/Remote/Role-90_JR90." |
| 121 | |
| 122 | |
| 123 | # --- Amazon: ``base_query`` on search.json --- |
| 124 | |
| 125 | HUMANOID_JOB = { |
| 126 | "id_icims": "3100001", |
| 127 | "title": "Applied Scientist, Humanoid Robotics", |
| 128 | "job_path": "/en/jobs/3100001/applied-scientist-humanoid-robotics", |
| 129 | "posted_date": "November 12, 2026", |
| 130 | "description": "Teach humanoid robots to move packages.", |
| 131 | "normalized_location": "Seattle, Washington, USA", |
| 132 | } |
| 133 | # The search also answers a role whose text never names the term. |
| 134 | LOOSE_JOB = { |
| 135 | "id_icims": "3100002", |
| 136 | "title": "Area Manager", |
| 137 | "job_path": "/en/jobs/3100002/area-manager", |
| 138 | "posted_date": "November 12, 2026", |
| 139 | "description": "Lead a shift at a fulfillment center.", |
| 140 | "normalized_location": "Austin, Texas, USA", |
| 141 | } |
| 142 | |
| 143 | |
| 144 | def _amazon_pages(): |
| 145 | pages = copy.deepcopy(AMAZON["pages"]) |
| 146 | # The matched role is also on the board's newest page. |
| 147 | pages[0]["jobs"][1] = dict(HUMANOID_JOB) |
| 148 | return pages |
| 149 | |
| 150 | |
| 151 | def _amazon_get(pages, story_pages, asked, *, before=None): |
| 152 | def get(url, params=None, deadline_monotonic=None, **_kwargs): |
| 153 | params = dict(params or {}) |
| 154 | asked.append(params) |
| 155 | if not url.startswith("https://www.amazon.jobs/"): |
| 156 | raise http.HTTPError("HTTP 404: Not Found", status_code=404) |
| 157 | if before is not None: |
| 158 | before(params, deadline_monotonic) |
| 159 | if params.get("base_query"): |
| 160 | answer = story_pages[params["base_query"]] |
| 161 | if isinstance(answer, Exception): |
| 162 | raise answer |
| 163 | return copy.deepcopy(answer) |
| 164 | index = int(params.get("offset") or 0) // jobs.AMAZON_PAGE_SIZE |
| 165 | if index < len(pages): |
| 166 | return copy.deepcopy(pages[index]) |
| 167 | raise http.HTTPError("HTTP 404: Not Found", status_code=404) |
| 168 | |
| 169 | return get |
| 170 | |
| 171 | |
| 172 | def _amazon_search(terms, story_pages, *, before=None, budget=None): |
| 173 | asked = [] |
| 174 | get = _amazon_get(_amazon_pages(), story_pages, asked, before=before) |
| 175 | with patch.object(jobs, "AMAZON_PAGE_SIZE", 3), \ |
| 176 | patch.object(jobs.http, "get", side_effect=get), \ |
| 177 | patch.object(jobs.http, "get_text", return_value=None), \ |
| 178 | patch.object(jobs.http, "post", side_effect=_missing), \ |
| 179 | http.capture_failures() as failures: |
| 180 | items, artifact = jobs.search_jobs( |
| 181 | "Amazon", WINDOW, {"_jobs_story_terms": terms}, web_backend="none", |
| 182 | site="https://www.amazon.com/", budget=budget, |
| 183 | ) |
| 184 | return items, artifact, asked, failures |
| 185 | |
| 186 | |
| 187 | def _hits(*rows): |
| 188 | return {"error": None, "hits": len(rows), "jobs": [dict(row) for row in rows]} |
| 189 | |
| 190 | |
| 191 | def test_amazon_story_term_is_sent_as_base_query_and_its_match_is_one_tagged_row(): |
| 192 | items, artifact, asked, _failures = _amazon_search( |
| 193 | ["humanoid"], {"humanoid": _hits(HUMANOID_JOB, LOOSE_JOB)}, |
| 194 | ) |
| 195 | |
| 196 | assert asked[0]["base_query"] == "humanoid" |
| 197 | assert all("base_query" not in params for params in asked[1:]) |
| 198 | matched = [item for item in items if item["id"] == "AZ3100001"] |
| 199 | assert len(matched) == 1 and matched[0]["story_term"] == "humanoid" |
| 200 | # A row whose text does not name the term is not a match. |
| 201 | assert not any(item["id"] == "AZ3100002" for item in items) |
| 202 | assert len(items) == 9 and artifact["resultCount"] == 9 |
| 203 | assert artifact["open_roles"] == 10000 |
| 204 | assert artifact["story_search"]["matches"] == 1 |
| 205 | |
| 206 | |
| 207 | def test_story_calls_that_reach_the_story_deadline_skip_the_rest_and_the_read_keeps_its_share(): |
| 208 | now = [0.0] |
| 209 | budget = jobs.LaneBudget(45, clock=lambda: now[0]) |
| 210 | left_at_listing = [] |
| 211 | |
| 212 | def before(params, deadline_monotonic): |
| 213 | if params.get("base_query"): |
| 214 | # Each story call takes all the time it is allowed. |
| 215 | now[0] += round(deadline_monotonic - time.monotonic()) |
| 216 | elif not left_at_listing: |
| 217 | left_at_listing.append(budget.remaining()) |
| 218 | |
| 219 | terms = ["humanoid", "drone", "satellite", "pharmacy"] |
| 220 | items, artifact, asked, _failures = _amazon_search( |
| 221 | terms, {term: _hits() for term in terms}, before=before, budget=budget, |
| 222 | ) |
| 223 | |
| 224 | assert [params["base_query"] for params in asked if "base_query" in params] == ["humanoid", "drone"] |
| 225 | assert artifact["story_search"]["story_partial"] is True |
| 226 | assert artifact["story_search"]["terms"] == ["humanoid", "drone"] |
| 227 | # One third of 45 s went to story calls; the newest-first read starts |
| 228 | # with the other two thirds. |
| 229 | assert left_at_listing[0] >= 30 - 0.5 |
| 230 | assert len(items) == 9 |
| 231 | |
| 232 | |
| 233 | def test_a_429_on_the_second_story_call_stops_story_search_and_the_board_is_still_read(): |
| 234 | items, artifact, asked, failures = _amazon_search( |
| 235 | ["humanoid", "drone", "satellite"], |
| 236 | { |
| 237 | "humanoid": _hits(HUMANOID_JOB), |
| 238 | "drone": http.HTTPError("HTTP 429: Too Many Requests", status_code=429), |
| 239 | "satellite": _hits(), |
| 240 | }, |
| 241 | ) |
| 242 | |
| 243 | assert [params["base_query"] for params in asked if "base_query" in params] == ["humanoid", "drone"] |
| 244 | assert artifact["story_search"] == { |
| 245 | "ran": True, "terms": ["humanoid"], "matches": 1, "story_partial": True, |
| 246 | } |
| 247 | assert len(items) == 9 and artifact["tier"] == "ats" |
| 248 | assert not any(failure.status_code == 429 for failure in failures) |
| 249 | |
| 250 | |
| 251 | |
| 252 | @pytest.mark.parametrize("failure", [ |
| 253 | http.HTTPError("HTTP 500: Internal Server Error", status_code=500), |
| 254 | ValueError("not JSON"), |
| 255 | ], ids=["server-error", "bad-shape"]) |
| 256 | def test_a_failed_story_call_skips_its_term_marks_the_search_partial_and_the_next_term_runs(failure): |
| 257 | items, artifact, asked, _failures = _amazon_search( |
| 258 | ["drone", "humanoid"], {"drone": failure, "humanoid": _hits(HUMANOID_JOB)}, |
| 259 | ) |
| 260 | |
| 261 | assert [params["base_query"] for params in asked if "base_query" in params] == ["drone", "humanoid"] |
| 262 | assert artifact["story_search"] == { |
| 263 | "ran": True, "terms": ["humanoid"], "matches": 1, "story_partial": True, |
| 264 | } |
| 265 | assert len(items) == 9 |
| 266 | |
| 267 | |
| 268 | def test_a_story_call_that_times_out_stops_story_search(): |
| 269 | timeout = http.HTTPError("timed out", outcome_state=health.TIMEOUT) |
| 270 | _items, artifact, asked, _failures = _amazon_search( |
| 271 | ["drone", "humanoid"], {"drone": timeout, "humanoid": _hits(HUMANOID_JOB)}, |
| 272 | ) |
| 273 | |
| 274 | assert [params["base_query"] for params in asked if "base_query" in params] == ["drone"] |
| 275 | assert artifact["story_search"] == {"ran": False, "terms": [], "matches": 0, "story_partial": True} |
| 276 | |
| 277 | |
| 278 | def test_a_board_whose_every_story_call_failed_says_not_run_not_no_matches(): |
| 279 | unavailable = http.HTTPError("HTTP 503: Service Unavailable", status_code=503) |
| 280 | items, artifact, _asked, _failures = _amazon_search( |
| 281 | ["drone", "satellite"], {"drone": unavailable, "satellite": unavailable}, |
| 282 | ) |
| 283 | |
| 284 | assert artifact["story_search"] == {"ran": False, "terms": [], "matches": 0, "story_partial": True} |
| 285 | assert len(items) == 9 |
| 286 | assert render._story_search_status(artifact["story_search"]) == "; story search: not run (partial)" |
| 287 | |
| 288 | # --- Eightfold: one story call, however many terms --- |
| 289 | |
| 290 | _MICROSOFT_LANDING = ( |
| 291 | '<html><body><div id="careers-eightFoldCareerUrl" hidden>' |
| 292 | "https://apply.careers.microsoft.com/careers</div>" |
| 293 | "<p>Join our team. Open positions.</p></body></html>" |
| 294 | ) |
| 295 | _MICROSOFT_PAGE = ( |
| 296 | '<html><head><link href="https://static.vscdn.net/fonts/css/eightfold-font-base.css">' |
| 297 | '<script>window._EF_GROUP_ID = "microsoft.com";</script></head><body></body></html>' |
| 298 | ) |
| 299 | |
| 300 | |
| 301 | def test_eightfold_is_asked_one_story_call_for_three_terms(): |
| 302 | listed = [] |
| 303 | |
| 304 | def get(url, params=None, **_kwargs): |
| 305 | if "/api/pcsx/search" in url: |
| 306 | listed.append(dict(params or {})) |
| 307 | answer = copy.deepcopy(PCSX["page"]) |
| 308 | if int(params["start"]) > 0: |
| 309 | answer["data"]["positions"] = [] |
| 310 | return answer |
| 311 | if "/api/pcsx/position_details" in url: |
| 312 | return copy.deepcopy(PCSX["detail"]) |
| 313 | raise http.HTTPError("HTTP 404: Not Found", status_code=404) |
| 314 | |
| 315 | pages = { |
| 316 | "https://careers.microsoft.com/": _MICROSOFT_LANDING, |
| 317 | "https://apply.careers.microsoft.com/careers": _MICROSOFT_PAGE, |
| 318 | } |
| 319 | with patch.object(jobs.http, "get", side_effect=get), \ |
| 320 | patch.object(jobs.http, "get_text", side_effect=lambda url, **_k: pages.get(url)), \ |
| 321 | patch.object(jobs.http, "post", side_effect=_missing): |
| 322 | _items, artifact = jobs.search_jobs( |
| 323 | "Microsoft", WINDOW, {"_jobs_story_terms": ["copilot", "quantum", "datacenter"]}, |
| 324 | web_backend="none", site="https://www.microsoft.com/", |
| 325 | ) |
| 326 | |
| 327 | story_calls = [params for params in listed if params.get("query")] |
| 328 | assert [params["query"] for params in story_calls] == ["copilot"] |
| 329 | assert listed[0]["query"] == "copilot" |
| 330 | assert artifact["story_search"]["terms"] == ["copilot"] |
| 331 | assert artifact["story_search"]["story_partial"] is False |
| 332 | |
| 333 | |
| 334 | # --- Greenhouse: a board read whole is matched where it is --- |
| 335 | |
| 336 | |
| 337 | def _greenhouse_job(ident, title, content): |
| 338 | return { |
| 339 | "id": ident, "title": title, "content": content, |
| 340 | "absolute_url": f"https://boards.greenhouse.io/acme/jobs/{ident}", |
| 341 | "first_published": "2026-11-10T00:00:00Z", |
| 342 | "departments": [{"name": "Engineering"}], "offices": [{"name": "Remote"}], |
| 343 | } |
| 344 | |
| 345 | |
| 346 | def test_greenhouse_rows_are_matched_locally_on_whole_words_in_title_and_description(): |
| 347 | board = {"jobs": [ |
| 348 | _greenhouse_job(1, "AI Platform Engineer", "<p>Ship models.</p>"), |
| 349 | _greenhouse_job(2, "Maintenance Technician", "<p>Keep the plant running.</p>"), |
| 350 | _greenhouse_job(3, "Mechanical Engineer", "<p>Design arms for our robotics line.</p>"), |
| 351 | _greenhouse_job(4, "Recruiter", "<p>Hire people.</p>"), |
| 352 | ]} |
| 353 | asked = [] |
| 354 | |
| 355 | def get(url, **kwargs): |
| 356 | asked.append(url) |
| 357 | return copy.deepcopy(board) |
| 358 | |
| 359 | with patch.object(jobs.http, "get_text", |
| 360 | return_value='<a href="https://boards.greenhouse.io/acme">Jobs</a>'), \ |
| 361 | patch.object(jobs.http, "get", side_effect=get): |
| 362 | items, artifact = jobs.search_jobs( |
| 363 | "Acme", WINDOW, {"_jobs_story_terms": ["AI", "robotics"]}, |
| 364 | web_backend="none", site="https://www.acme.com/", |
| 365 | ) |
| 366 | |
| 367 | tags = {item["title"]: item.get("story_term") for item in items} |
| 368 | assert tags == { |
| 369 | "AI Platform Engineer": "AI", |
| 370 | "Maintenance Technician": None, |
| 371 | "Mechanical Engineer": "robotics", |
| 372 | "Recruiter": None, |
| 373 | } |
| 374 | # The board is read once; no search call is added for a board read whole. |
| 375 | assert asked == ["https://boards-api.greenhouse.io/v1/boards/acme/jobs"] |
| 376 | assert artifact["story_search"] == { |
| 377 | "ran": True, "terms": ["AI", "robotics"], "matches": 2, "story_partial": False, |
| 378 | } |
| 379 | assert artifact["open_roles"] == 4 |
| 380 | |
| 381 | |
| 382 | # --- A board with no story search says so --- |
| 383 | |
| 384 | |
| 385 | def test_a_board_this_lane_cannot_search_records_that_story_search_did_not_run(monkeypatch): |
| 386 | def reader(entry, *, deadline, **_kwargs): |
| 387 | rows = [jobs._ats_item( |
| 388 | provider="stub", slug="jobs.acmecorp.com", ident=f"R{n}", title=f"Robotics Engineer {n}", |
| 389 | url=f"https://jobs.acmecorp.com/roles/{n}", description="Build robots.", |
| 390 | date="2026-11-10", department=f"Team {n}", location="Austin, TX", whole_posting=True, |
| 391 | ) for n in range(3)] |
| 392 | return rows, {"board_total": 3} |
| 393 | |
| 394 | monkeypatch.setitem( |
| 395 | jobs.COMPANY_BOARDS, "acmecorp.com", |
| 396 | {"name": "Acme", "provider": "stub", "board": "jobs.acmecorp.com"}, |
| 397 | ) |
| 398 | monkeypatch.setitem(jobs._COMPANY_READERS, "stub", "_stub_reader") |
| 399 | monkeypatch.setattr(jobs, "_stub_reader", reader, raising=False) |
| 400 | with patch.object(jobs.http, "get", side_effect=_missing), \ |
| 401 | patch.object(jobs.http, "get_text", return_value=None), \ |
| 402 | patch.object(jobs.http, "post", side_effect=_missing): |
| 403 | items, artifact = jobs.search_jobs( |
| 404 | "Acme", WINDOW, {"_jobs_story_terms": ["robotics"]}, |
| 405 | web_backend="none", site="https://www.acmecorp.com/", |
| 406 | ) |
| 407 | |
| 408 | assert artifact["story_search"] == { |
| 409 | "ran": False, "terms": [], "matches": 0, "story_partial": False, |
| 410 | } |
| 411 | assert not any(item.get("story_term") for item in items) |
| 412 |