| 1 | """The jobs lane inside one time budget, and what it says when the time runs out. |
| 2 | |
| 3 | Evidence, four live runs on v3.34.1 on 2026-11-10: |
| 4 | |
| 5 | - "Disney" (``--ticker "DIS:Walt Disney"``, official site |
| 6 | thewaltdisneycompany.com): "Jobs timeout: jobs timed out after 180s". The |
| 7 | official site never reached the lane, so it guessed disney.com, disney.ai |
| 8 | and disney.io; the last two never answered, at 30 s a page. |
| 9 | - "Sundar Pichai" (``--ticker "GOOGL:Alphabet"``): "Jobs timeout: URL Error: |
| 10 | timed out" after 134 s, from sundarpichai.com and sundarpichai.ai. |
| 11 | - "Elon Musk" (``--ticker "TSLA:Tesla,SPCX:SpaceX"``): no jobs, because two |
| 12 | host companies named no one company. |
| 13 | - "Waymo": the roles the run ranked highest were not among the digest's 40. |
| 14 | """ |
| 15 | |
| 16 | import socket |
| 17 | import threading |
| 18 | import urllib.error |
| 19 | from unittest.mock import patch |
| 20 | |
| 21 | import last30days as cli |
| 22 | from lib import health, http, jobs, jobs_digest, pipeline, render, schema, yahoo_finance |
| 23 | |
| 24 | WINDOW = ("2026-10-12", "2026-11-11") |
| 25 | CAREERS = '<a href="https://acme.wd5.myworkdayjobs.com/en-US/AcmeCareers">Jobs</a>' |
| 26 | |
| 27 | |
| 28 | class Clock: |
| 29 | """A clock the test moves: a stubbed request costs time without waiting.""" |
| 30 | |
| 31 | def __init__(self, now: float = 1000.0) -> None: |
| 32 | self.start = self.now = now |
| 33 | self._lock = threading.Lock() |
| 34 | |
| 35 | def __call__(self) -> float: |
| 36 | return self.now |
| 37 | |
| 38 | def advance(self, seconds: float) -> None: |
| 39 | with self._lock: |
| 40 | self.now += seconds |
| 41 | |
| 42 | @property |
| 43 | def elapsed(self) -> float: |
| 44 | return self.now - self.start |
| 45 | |
| 46 | |
| 47 | def _not_found(url, *_args, **_kwargs): |
| 48 | raise http.HTTPError("HTTP 404: Not Found", status_code=404) |
| 49 | |
| 50 | |
| 51 | # --- One budget for the whole lane --- |
| 52 | |
| 53 | |
| 54 | def test_slow_board_returns_the_rows_read_with_a_floor_count_and_a_coverage_note(capsys): |
| 55 | clock = Clock() |
| 56 | listing_calls = [] |
| 57 | |
| 58 | def post(url, json_data, headers=None, **_kwargs): |
| 59 | clock.advance(4.0) # every listing page takes four seconds |
| 60 | offset = json_data["offset"] |
| 61 | listing_calls.append(offset) |
| 62 | rows = [ |
| 63 | { |
| 64 | "title": f"Role {index}", |
| 65 | "externalPath": f"/job/Remote/Role-{index}_JR{index}", |
| 66 | "locationsText": "Remote", |
| 67 | "bulletFields": [f"JR{index}"], |
| 68 | } |
| 69 | for index in range(offset, offset + 20) |
| 70 | ] |
| 71 | return {"total": 2000 if offset == 0 else 0, "jobPostings": rows} |
| 72 | |
| 73 | with patch("lib.jobs.http.get_text", return_value=CAREERS), \ |
| 74 | patch("lib.jobs.http.post", side_effect=post), \ |
| 75 | patch("lib.jobs.http.get", side_effect=AssertionError("no time is left for detail calls")): |
| 76 | items, artifact = jobs.search_jobs( |
| 77 | "Acme", WINDOW, {}, web_backend="none", site="https://www.acme.com", |
| 78 | budget=jobs.LaneBudget(45.0, clock=clock), |
| 79 | ) |
| 80 | |
| 81 | # About eleven pages fit in 45 s; eight run at once, so a few more start. |
| 82 | assert 20 < len(items) < 2000 |
| 83 | assert len(listing_calls) <= 12 + jobs.WORKDAY_MAX_WORKERS |
| 84 | assert clock.elapsed <= 45.0 + 4.0 * jobs.WORKDAY_MAX_WORKERS |
| 85 | assert artifact["tier"] == "ats" |
| 86 | assert artifact["open_roles"] == len(items) |
| 87 | assert artifact["open_roles_floor"] is True |
| 88 | assert artifact["new_in_window"] is None |
| 89 | assert "45s time budget ran out" in artifact["coverage_note"] |
| 90 | assert f"{len(items):,} rows read of the 2,000 the board lists" in artifact["coverage_note"] |
| 91 | assert artifact["digest"]["roles"] |
| 92 | assert "board read in part" in artifact["digest"]["note"] |
| 93 | assert "role text fetched for 0 of 40 selected roles" in artifact["digest"]["note"] |
| 94 | assert "_source_outcome" not in artifact |
| 95 | assert "[Jobs] Acme: workday board acme.wd5/AcmeCareers: board read in part" in capsys.readouterr().err |
| 96 | |
| 97 | |
| 98 | def test_budget_spent_with_nothing_found_names_the_step_on_stderr_and_in_the_outcome(capsys): |
| 99 | clock = Clock() |
| 100 | pages = [] |
| 101 | |
| 102 | def slow_page(url, **_kwargs): |
| 103 | pages.append(url) |
| 104 | clock.advance(20.0) |
| 105 | return None |
| 106 | |
| 107 | with patch("lib.jobs.http.get_text", side_effect=slow_page), \ |
| 108 | patch("lib.jobs.http.get", side_effect=AssertionError("no time is left to probe")): |
| 109 | items, artifact = jobs.search_jobs( |
| 110 | "Kanye West", WINDOW, {}, web_backend="none", |
| 111 | budget=jobs.LaneBudget(45.0, clock=clock), |
| 112 | ) |
| 113 | |
| 114 | assert items == [] |
| 115 | assert pages == [ |
| 116 | "https://kanyewest.com/careers", "https://kanyewest.com/jobs", "https://kanyewest.ai/careers", |
| 117 | ] |
| 118 | outcome = artifact["_source_outcome"] |
| 119 | assert outcome["state"] == health.TIMEOUT |
| 120 | assert "45s budget" in outcome["detail"] |
| 121 | assert "before the careers page https://kanyewest.ai/jobs" in outcome["detail"] |
| 122 | assert artifact["_source_out_of_time"] is True |
| 123 | assert f"[Jobs] {outcome['detail']}" in capsys.readouterr().err |
| 124 | |
| 125 | |
| 126 | def test_every_careers_request_carries_a_short_timeout_and_the_lanes_deadline(): |
| 127 | seen = [] |
| 128 | |
| 129 | def page(url, **kwargs): |
| 130 | seen.append((url, kwargs)) |
| 131 | return None |
| 132 | |
| 133 | with patch("lib.jobs.http.get_text", side_effect=page), \ |
| 134 | patch("lib.jobs.http.get", side_effect=_not_found): |
| 135 | jobs.search_jobs("Kanye West", WINDOW, {}, web_backend="none") |
| 136 | jobs.search_jobs("Acme", WINDOW, {}, web_backend="none", site="https://www.acme.com") |
| 137 | |
| 138 | pages = [(url, kwargs) for url, kwargs in seen if not url.endswith("/robots.txt")] |
| 139 | # Six guessed pages for Kanye West; the known site's two pages and its |
| 140 | # careers. and jobs. hosts for Acme. |
| 141 | assert len(pages) == 10 |
| 142 | for url, kwargs in pages: |
| 143 | limit = ( |
| 144 | jobs.PAGE_TIMEOUT_SECONDS if url.startswith("https://www.acme.com/") |
| 145 | else jobs.GUESS_TIMEOUT_SECONDS |
| 146 | ) |
| 147 | assert kwargs["timeout"] == limit <= 8 |
| 148 | assert kwargs["retries"] == 1 |
| 149 | assert kwargs["deadline_monotonic"] is not None |
| 150 | |
| 151 | |
| 152 | def test_every_board_api_call_carries_a_short_timeout_and_the_lanes_deadline(): |
| 153 | seen = [] |
| 154 | |
| 155 | def api(url, *_args, **kwargs): |
| 156 | seen.append(kwargs) |
| 157 | raise http.HTTPError("HTTP 404: Not Found", status_code=404) |
| 158 | |
| 159 | with patch("lib.jobs.http.get_text", return_value=None), \ |
| 160 | patch("lib.jobs.http.get", side_effect=api): |
| 161 | jobs.search_jobs("Acme", WINDOW, {}, web_backend="none") |
| 162 | |
| 163 | assert len(seen) == 3 # one slug, three providers |
| 164 | for kwargs in seen: |
| 165 | assert kwargs["timeout"] == jobs.API_TIMEOUT_SECONDS <= 10 |
| 166 | assert kwargs["retries"] == 2 |
| 167 | assert kwargs["deadline_monotonic"] is not None |
| 168 | |
| 169 | |
| 170 | # --- A dead host fails fast --- |
| 171 | |
| 172 | |
| 173 | def _timed_out(*_args, **_kwargs): |
| 174 | raise urllib.error.URLError(TimeoutError("timed out")) |
| 175 | |
| 176 | |
| 177 | def _dead_hosts(dead, asked): |
| 178 | def opener(req, timeout=None, **_kwargs): |
| 179 | asked.append((req.full_url, timeout)) |
| 180 | if req.full_url.split("/")[2] in dead: |
| 181 | _timed_out() |
| 182 | raise urllib.error.HTTPError(req.full_url, 404, "Not Found", {}, None) |
| 183 | return opener |
| 184 | |
| 185 | |
| 186 | def test_guessed_host_that_never_answers_is_asked_once_briefly_and_is_not_an_outage(capsys): |
| 187 | asked = [] |
| 188 | dead = {"sundarpichai.com", "sundarpichai.ai", "sundarpichai.io"} |
| 189 | budget = jobs.LaneBudget(45.0) |
| 190 | with patch.object(http, "_open_request", side_effect=_dead_hosts(dead, asked)), \ |
| 191 | patch.object(http.time, "sleep"), \ |
| 192 | http.capture_failures() as failures: |
| 193 | items, artifact = jobs.search_jobs( |
| 194 | "Sundar Pichai", WINDOW, {}, web_backend="none", budget=budget, |
| 195 | ) |
| 196 | |
| 197 | careers = [(url, timeout) for url, timeout in asked if "sundarpichai." in url] |
| 198 | assert [url for url, _timeout in careers] == [ |
| 199 | "https://sundarpichai.com/careers", |
| 200 | "https://sundarpichai.ai/careers", |
| 201 | "https://sundarpichai.io/careers", |
| 202 | ] |
| 203 | assert all(timeout <= jobs.GUESS_TIMEOUT_SECONDS for _url, timeout in careers) |
| 204 | assert items == [] |
| 205 | assert failures == [] |
| 206 | assert "_source_outcome" not in artifact |
| 207 | assert budget.slow == [ |
| 208 | f"{host} did not answer in {jobs.GUESS_TIMEOUT_SECONDS}s" |
| 209 | for host in ("sundarpichai.com", "sundarpichai.ai", "sundarpichai.io") |
| 210 | ] |
| 211 | # The caller that owns the budget says once that no board was found. |
| 212 | assert capsys.readouterr().err == "" |
| 213 | |
| 214 | |
| 215 | def test_official_site_that_never_answers_is_asked_once_and_is_recorded(): |
| 216 | asked = [] |
| 217 | with patch.object(http, "_open_request", side_effect=_dead_hosts({"www.acme.com"}, asked)), \ |
| 218 | patch.object(http.time, "sleep"), \ |
| 219 | http.capture_failures() as failures: |
| 220 | items, _artifact = jobs.search_jobs( |
| 221 | "Acme", WINDOW, {}, web_backend="none", site="https://www.acme.com", |
| 222 | ) |
| 223 | |
| 224 | assert [url for url, _timeout in asked if url.split("/")[2] == "www.acme.com"] == [ |
| 225 | "https://www.acme.com/careers", |
| 226 | ] |
| 227 | assert asked[0][1] <= jobs.PAGE_TIMEOUT_SECONDS |
| 228 | assert items == [] |
| 229 | assert failures and all(failure.outcome_state == health.TIMEOUT for failure in failures) |
| 230 | |
| 231 | |
| 232 | def test_name_that_does_not_resolve_on_a_guessed_host_is_not_retried(): |
| 233 | asked = [] |
| 234 | |
| 235 | def opener(req, timeout=None, **_kwargs): |
| 236 | asked.append(req.full_url) |
| 237 | raise urllib.error.URLError(socket.gaierror(8, "nodename nor servname provided")) |
| 238 | |
| 239 | with patch.object(http, "_open_request", side_effect=opener), patch.object(http.time, "sleep"): |
| 240 | html, no_answer = jobs._careers_text("https://kanyewest.io/careers", guessed=True) |
| 241 | assert html is None and no_answer is True |
| 242 | assert asked == ["https://kanyewest.io/careers"] |
| 243 | |
| 244 | |
| 245 | def test_slow_hosts_are_named_when_they_spend_the_budget(capsys): |
| 246 | clock = Clock() |
| 247 | |
| 248 | def opener(req, timeout=None, **_kwargs): |
| 249 | clock.advance(float(jobs.GUESS_TIMEOUT_SECONDS)) # the host uses its whole timeout |
| 250 | _timed_out() |
| 251 | |
| 252 | with patch.object(http, "_open_request", side_effect=opener), \ |
| 253 | patch.object(http.time, "sleep"), \ |
| 254 | http.capture_failures() as failures: |
| 255 | items, artifact = jobs.search_jobs( |
| 256 | "Kanye West", WINDOW, {}, web_backend="none", |
| 257 | budget=jobs.LaneBudget(10.0, clock=clock), |
| 258 | ) |
| 259 | |
| 260 | assert items == [] |
| 261 | assert failures == [] |
| 262 | detail = artifact["_source_outcome"]["detail"] |
| 263 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 264 | assert "kanyewest.com did not answer in 4s" in detail |
| 265 | assert "kanyewest.ai did not answer in 4s" in detail |
| 266 | assert "10s budget" in detail |
| 267 | assert detail in capsys.readouterr().err |
| 268 | |
| 269 | |
| 270 | # --- A careers system the lane does not read --- |
| 271 | |
| 272 | # google.com/careers on 2026-11-10: Google's own careers system. No supported |
| 273 | # board is named on it or on the job search it links to. |
| 274 | OWN_SYSTEM = """ |
| 275 | <h1>Join our team</h1> |
| 276 | <a href="/about/careers/applications/jobs/results">Search jobs</a> |
| 277 | <a href="https://www.linkedin.com/company/google/jobs/">LinkedIn</a> |
| 278 | """ |
| 279 | |
| 280 | |
| 281 | def test_careers_site_with_no_supported_board_returns_quietly(capsys): |
| 282 | # A company whose site is in neither the company-board registry nor its |
| 283 | # list of unreadable job sites. |
| 284 | fetched = [] |
| 285 | |
| 286 | def page(url, **_kwargs): |
| 287 | fetched.append(url) |
| 288 | return OWN_SYSTEM if "initech.com" in url else None |
| 289 | |
| 290 | with patch("lib.jobs.http.get_text", side_effect=page), \ |
| 291 | patch("lib.jobs.http.get", side_effect=_not_found), \ |
| 292 | http.capture_failures() as failures: |
| 293 | items, artifact = jobs.search_jobs( |
| 294 | "Initech", WINDOW, {}, web_backend="none", site="https://www.initech.com", |
| 295 | ) |
| 296 | |
| 297 | assert fetched[:2] == [ |
| 298 | "https://www.initech.com/careers", |
| 299 | "https://www.initech.com/about/careers/applications/jobs/results", |
| 300 | ] |
| 301 | # Then the site's careers. and jobs. hosts and its robots.txt files, for a |
| 302 | # board or a job sitemap; nothing off the site. |
| 303 | assert all(jobs._same_site(jobs._host(url), "initech.com") for url in fetched) |
| 304 | assert items == [] |
| 305 | assert artifact["tier"] == "web" |
| 306 | assert failures == [] |
| 307 | assert "_source_outcome" not in artifact |
| 308 | assert "_source_outcome_detail" not in artifact |
| 309 | assert "[Jobs] no supported job board found for Initech" in capsys.readouterr().err |
| 310 | |
| 311 | |
| 312 | # --- The official site the run already knows --- |
| 313 | |
| 314 | |
| 315 | def test_official_site_reaches_the_jobs_lane_when_wikidata_named_no_company(): |
| 316 | assert cli._company_for_jobs({}, None, "Disney", official_site="thewaltdisneycompany.com") == { |
| 317 | "topic_site": "thewaltdisneycompany.com", |
| 318 | } |
| 319 | resolved = {"company": "Nvidia", "company_site": "https://www.nvidia.com/"} |
| 320 | assert cli._company_for_jobs(resolved, None, "Nvidia", official_site="example.com") == resolved |
| 321 | # A Yahoo match after a failed Wikidata lookup names the company with no |
| 322 | # site; the official site the run knows is still the topic's. |
| 323 | yahoo = {"company": "Apple", "ticker": "AAPL"} |
| 324 | assert cli._company_for_jobs(yahoo, None, "Apple", official_site="apple.com") == { |
| 325 | **yahoo, "topic_site": "apple.com", |
| 326 | } |
| 327 | # A company that is not the topic (a person's company) never takes the |
| 328 | # person's site. |
| 329 | person = {"company": "Anduril"} |
| 330 | assert cli._company_for_jobs(person, None, "Palmer Luckey", official_site="palmerluckey.com") == person |
| 331 | |
| 332 | (_items, _artifact), _names, mock = _run_lane( |
| 333 | "Disney", {"topic_site": "thewaltdisneycompany.com"}, lambda *_a, **_k: ([], {"tier": "web"}), |
| 334 | ) |
| 335 | assert mock.call_args_list[0].kwargs["site"] == "thewaltdisneycompany.com" |
| 336 | |
| 337 | |
| 338 | # --- Two companies named by the host --- |
| 339 | |
| 340 | |
| 341 | def _rows(count=6, host="boards.greenhouse.io/spacex"): |
| 342 | return [ |
| 343 | {"id": f"GH{index}", "title": f"Engineer {index}", "url": f"https://{host}/jobs/{index}"} |
| 344 | for index in range(count) |
| 345 | ] |
| 346 | |
| 347 | |
| 348 | def _run_lane(topic, company, search, config=None): |
| 349 | subquery = schema.SubQuery(label="primary", search_query=topic, ranking_query=topic, sources=["jobs"]) |
| 350 | config = {"_company": company, **(config or {})} |
| 351 | with patch.object(jobs, "search_jobs", side_effect=search) as mock: |
| 352 | result = pipeline._retrieve_stream_impl( |
| 353 | topic=topic, subquery=subquery, source="jobs", config=config, |
| 354 | depth="default", date_range=WINDOW, runtime=None, mock=False, |
| 355 | web_backend="auto", raw_topic=topic, |
| 356 | ) |
| 357 | return result, [call.args[0] for call in mock.call_args_list], mock |
| 358 | |
| 359 | |
| 360 | def test_two_host_ticker_companies_are_both_handed_to_the_lane_in_order(): |
| 361 | two = yahoo_finance.parse_host_tickers("TSLA:Tesla,SPCX:SpaceX") |
| 362 | assert cli._company_for_jobs({}, two, "Elon Musk") == {"host_companies": ["Tesla", "SpaceX"]} |
| 363 | # The topic's own name is never one of them. |
| 364 | assert cli._company_for_jobs({}, two, "Tesla") == {"host_companies": ["SpaceX"]} |
| 365 | |
| 366 | |
| 367 | def test_each_host_company_is_tried_in_order_and_the_first_board_found_is_used(): |
| 368 | board = {"tier": "ats", "provider": "greenhouse", "company": "SpaceX", "open_roles": 6} |
| 369 | |
| 370 | def search(name, *_args, **_kwargs): |
| 371 | return (_rows(), board) if name == "SpaceX" else ([], {"tier": "web"}) |
| 372 | |
| 373 | (items, artifact), names, mock = _run_lane( |
| 374 | "Elon Musk", {"host_companies": ["Tesla", "SpaceX"]}, search, |
| 375 | ) |
| 376 | assert names == ["Elon Musk", "Tesla", "SpaceX"] |
| 377 | assert len(items) == 6 |
| 378 | assert artifact["board_of"] == "SpaceX" |
| 379 | # One budget for all three; finding the earlier companies' boards may |
| 380 | # use only a share of it, so the last still has its turn. |
| 381 | budgets = [call.kwargs["budget"] for call in mock.call_args_list] |
| 382 | assert isinstance(budgets[0], jobs.LaneBudget) |
| 383 | assert budgets[0] is budgets[1] is budgets[2] |
| 384 | shares = [call.kwargs["discovery_seconds"] for call in mock.call_args_list] |
| 385 | assert shares[0] <= jobs.JOBS_BUDGET_SECONDS / 3 and shares[1] <= jobs.JOBS_BUDGET_SECONDS / 2 |
| 386 | assert shares[2] is None |
| 387 | assert [call.kwargs["web_backend"] for call in mock.call_args_list] == ["auto", "none", "none"] |
| 388 | |
| 389 | |
| 390 | def test_first_host_company_with_a_board_ends_the_search(): |
| 391 | board = {"tier": "ats", "provider": "greenhouse", "company": "Tesla", "open_roles": 6} |
| 392 | (_items, artifact), names, _mock = _run_lane( |
| 393 | "Elon Musk", {"host_companies": ["Tesla", "SpaceX"]}, |
| 394 | lambda name, *_a, **_k: (_rows(), board) if name == "Tesla" else ([], {"tier": "web"}), |
| 395 | ) |
| 396 | assert names == ["Elon Musk", "Tesla"] |
| 397 | assert artifact["board_of"] == "Tesla" |
| 398 | |
| 399 | |
| 400 | def test_a_host_company_whose_job_site_cannot_be_read_keeps_its_footer_line(): |
| 401 | def search(name, *_args, **_kwargs): |
| 402 | if name == "Tesla": |
| 403 | return [], {"tier": "web", "job_site_unreadable": "Tesla"} |
| 404 | return [], {"tier": "web", "company": name} |
| 405 | |
| 406 | (items, artifact), names, _mock = _run_lane( |
| 407 | "Elon Musk", {"host_companies": ["Tesla", "SpaceX"]}, search, |
| 408 | ) |
| 409 | assert names == ["Elon Musk", "Tesla", "SpaceX"] |
| 410 | assert items == [] |
| 411 | assert artifact["company"] == "Elon Musk" |
| 412 | assert artifact["job_site_unreadable"] == "Tesla" |
| 413 | |
| 414 | |
| 415 | def test_host_companies_cut_off_by_the_budget_leave_the_reason_on_the_topics_result(): |
| 416 | outcome = {"state": health.TIMEOUT, "detail": "Tesla: jobs lane ran out of time", "attempted": True} |
| 417 | |
| 418 | def search(name, *_args, **_kwargs): |
| 419 | if name == "Elon Musk": |
| 420 | return [], {"tier": "web", "company": "Elon Musk"} |
| 421 | return [], {"tier": "web", "_source_outcome": outcome, "_source_out_of_time": True} |
| 422 | |
| 423 | (items, artifact), names, _mock = _run_lane( |
| 424 | "Elon Musk", {"host_companies": ["Tesla", "SpaceX"]}, search, |
| 425 | ) |
| 426 | assert names == ["Elon Musk", "Tesla", "SpaceX"] |
| 427 | assert items == [] |
| 428 | assert artifact["company"] == "Elon Musk" |
| 429 | assert artifact["_source_outcome"] == outcome |
| 430 | assert artifact["_source_out_of_time"] is True |
| 431 | |
| 432 | |
| 433 | def test_real_lane_tries_the_second_company_inside_the_same_budget(): |
| 434 | # The topic and the first company answer nowhere; the second has a board |
| 435 | # that names it. No request is real: every one goes through the opener. |
| 436 | spacex = ( |
| 437 | b'{"jobs":[{"id":1,"title":"Propulsion Engineer","company_name":"SpaceX",' |
| 438 | b'"absolute_url":"https://boards.greenhouse.io/spacex/jobs/1",' |
| 439 | b'"first_published":"2026-11-01T00:00:00Z","content":"Build engines."}]}' |
| 440 | ) |
| 441 | |
| 442 | class Response: |
| 443 | status = 200 |
| 444 | |
| 445 | def __enter__(self): |
| 446 | return self |
| 447 | |
| 448 | def __exit__(self, *_exc): |
| 449 | return False |
| 450 | |
| 451 | def read(self, size=-1): |
| 452 | return spacex |
| 453 | |
| 454 | def opener(req, timeout=None, **_kwargs): |
| 455 | if req.full_url.startswith("https://boards-api.greenhouse.io/v1/boards/spacex/"): |
| 456 | return Response() |
| 457 | raise urllib.error.HTTPError(req.full_url, 404, "Not Found", {}, None) |
| 458 | |
| 459 | subquery = schema.SubQuery( |
| 460 | label="primary", search_query="Elon Musk", ranking_query="Elon Musk", sources=["jobs"], |
| 461 | ) |
| 462 | lane = {} |
| 463 | with patch.object(http, "_open_request", side_effect=opener), patch.object(http.time, "sleep"): |
| 464 | items, artifact = pipeline._retrieve_stream_impl( |
| 465 | topic="Elon Musk", subquery=subquery, source="jobs", |
| 466 | config={"_company": {"host_companies": ["Tesla", "SpaceX"]}, "_jobs_lane": lane}, |
| 467 | depth="default", date_range=WINDOW, runtime=None, mock=False, |
| 468 | web_backend="none", raw_topic="Elon Musk", |
| 469 | ) |
| 470 | assert [item["title"] for item in items] == ["Propulsion Engineer"] |
| 471 | assert artifact["board_of"] == "SpaceX" |
| 472 | assert artifact["owned"] is True # the board states the company's name |
| 473 | assert artifact["digest"]["roles"][0]["title"] == "Propulsion Engineer" |
| 474 | assert lane["budget"].settled is True |
| 475 | |
| 476 | |
| 477 | def test_footer_and_digest_name_the_company_whose_board_it_is(): |
| 478 | digest = {"distinct_roles": 1, "roles": [{ |
| 479 | "title": "Propulsion Engineer", "department": "", "location": "", "posted": "", |
| 480 | "url": "https://boards.greenhouse.io/spacex/jobs/1", "urls": [], "text": "Build engines.", |
| 481 | }]} |
| 482 | board = { |
| 483 | "tier": "ats", "provider": "greenhouse", "company": "SpaceX", "board_of": "SpaceX", |
| 484 | "open_roles": 1234, "new_in_window": 56, "owned": True, "digest": digest, |
| 485 | } |
| 486 | report = _report("Elon Musk", board) |
| 487 | assert render._jobs_board_footer_line(report) == ( |
| 488 | "💼 Jobs at SpaceX: 1,234 open roles │ 56 new in the L30" |
| 489 | ) |
| 490 | nvidia = {**board, "board_of": "Nvidia", "open_roles": 2000, "open_roles_floor": True, "new_in_window": None} |
| 491 | assert render._jobs_board_footer_line(_report("Jensen Huang", nvidia)) == ( |
| 492 | "💼 Jobs at Nvidia: 2,000+ open roles" |
| 493 | ) |
| 494 | assert "- Board: SpaceX | greenhouse | 1,234 open roles" in "\n".join(render._render_jobs_digest(report)) |
| 495 | # The topic's own board keeps the line it always had. |
| 496 | del board["board_of"] |
| 497 | assert render._jobs_board_footer_line(report) == "💼 Jobs: 1,234 open roles │ 56 new in the L30" |
| 498 | |
| 499 | |
| 500 | def _report(topic, board, items=None): |
| 501 | return schema.Report( |
| 502 | topic=topic, |
| 503 | range_from=WINDOW[0], |
| 504 | range_to=WINDOW[1], |
| 505 | generated_at="2026-11-10T00:00:00Z", |
| 506 | provider_runtime=schema.ProviderRuntime("mock", "mock", "mock"), |
| 507 | query_plan=schema.QueryPlan( |
| 508 | intent="product", freshness_mode="balanced_recent", cluster_mode="none", |
| 509 | raw_topic=topic, subqueries=[], source_weights={}, |
| 510 | ), |
| 511 | clusters=[], ranked_candidates=[], |
| 512 | items_by_source={"jobs": items} if items else {}, |
| 513 | errors_by_source={}, |
| 514 | artifacts={"jobs": board}, |
| 515 | ) |
| 516 | |
| 517 | |
| 518 | # --- One budget for every pass of a run --- |
| 519 | |
| 520 | |
| 521 | def test_second_pass_of_the_same_run_does_not_search_again_once_the_lane_has_its_answer(): |
| 522 | lane = {} |
| 523 | calls = [] |
| 524 | |
| 525 | def search(name, *_args, **_kwargs): |
| 526 | calls.append(name) |
| 527 | return [], {"tier": "web"} |
| 528 | |
| 529 | for _pass in range(2): |
| 530 | (items, artifact), _names, _mock = _run_lane( |
| 531 | "Kanye West", {}, search, config={"_jobs_lane": lane}, |
| 532 | ) |
| 533 | assert calls == ["Kanye West"] |
| 534 | assert (items, artifact) == ([], {}) |
| 535 | |
| 536 | |
| 537 | def test_second_pass_after_a_spent_budget_asks_nothing(): |
| 538 | clock = Clock() |
| 539 | lane = {"budget": jobs.LaneBudget(45.0, clock=clock)} |
| 540 | clock.advance(46.0) |
| 541 | (items, artifact), names, _mock = _run_lane( |
| 542 | "Kanye West", {}, lambda *_a, **_k: ([], {"tier": "web"}), config={"_jobs_lane": lane}, |
| 543 | ) |
| 544 | assert names == [] |
| 545 | assert (items, artifact) == ([], {}) |
| 546 | |
| 547 | |
| 548 | def test_comparison_entities_share_the_budget_equally(): |
| 549 | lane = {} |
| 550 | _run_lane( |
| 551 | "Acme", {}, lambda *_a, **_k: ([], {"tier": "web"}), |
| 552 | config={"_jobs_lane": lane, "_comparison_entity_count": 3}, |
| 553 | ) |
| 554 | assert lane["budget"].seconds == jobs.JOBS_BUDGET_SECONDS / 3 |
| 555 | |
| 556 | |
| 557 | def test_the_lanes_budget_is_45_seconds_and_far_under_the_generic_source_cap(): |
| 558 | assert jobs.JOBS_BUDGET_SECONDS == 45.0 |
| 559 | assert jobs.JOBS_BUDGET_SECONDS <= pipeline.STREAM_FUTURE_TIMEOUT_SECONDS / 4 |
| 560 | |
| 561 | |
| 562 | # --- Ownership --- |
| 563 | |
| 564 | |
| 565 | def test_board_under_a_guessed_slug_that_names_another_company_is_passed_over(): |
| 566 | # boards-api.greenhouse.io/v1/boards/disney on 2026-11-10: a two-role |
| 567 | # template board of "Sgt. Pepper's Lonely Hearts Club Band". |
| 568 | namesake = {"jobs": [{ |
| 569 | "id": 1, "title": "MASTER TEMPLATE", "company_name": "Sgt. Pepper's Lonely Hearts Club Band", |
| 570 | "absolute_url": "https://job-boards.greenhouse.io/disney/jobs/1", |
| 571 | }]} |
| 572 | |
| 573 | def api(url, *_args, **_kwargs): |
| 574 | if url == "https://boards-api.greenhouse.io/v1/boards/disney/jobs": |
| 575 | return namesake |
| 576 | raise http.HTTPError("HTTP 404: Not Found", status_code=404) |
| 577 | |
| 578 | with patch("lib.jobs.http.get_text", return_value=None), \ |
| 579 | patch("lib.jobs.http.get", side_effect=api): |
| 580 | items, artifact = jobs.search_jobs("Disney", WINDOW, {}, web_backend="none") |
| 581 | assert items == [] |
| 582 | assert artifact["tier"] == "web" |
| 583 | assert "not-the-company:greenhouse:disney" in artifact["attempted"] |
| 584 | |
| 585 | |
| 586 | def test_board_under_a_guessed_slug_with_a_longer_form_of_the_name_counts_but_gives_no_digest(): |
| 587 | listed = {"jobs": [{ |
| 588 | "id": 1, "title": "Engineer", "company_name": "Meta Platforms", |
| 589 | "absolute_url": "https://job-boards.greenhouse.io/meta/jobs/1", "content": "Build things.", |
| 590 | }]} |
| 591 | calls = [] |
| 592 | |
| 593 | def api(url, *_args, **_kwargs): |
| 594 | calls.append(url) |
| 595 | if url == "https://boards-api.greenhouse.io/v1/boards/meta/jobs": |
| 596 | return listed |
| 597 | raise http.HTTPError("HTTP 404: Not Found", status_code=404) |
| 598 | |
| 599 | with patch("lib.jobs.http.get_text", return_value=None), \ |
| 600 | patch("lib.jobs.http.get", side_effect=api): |
| 601 | items, artifact = jobs.search_jobs("Meta", WINDOW, {}, web_backend="none") |
| 602 | assert len(items) == 1 |
| 603 | assert artifact["open_roles"] == 1 |
| 604 | assert artifact["found_via"] == "slug-guess" |
| 605 | assert artifact["owned"] is False |
| 606 | assert "digest" not in artifact |
| 607 | # The probe's rows are the board: it is not read a second time. |
| 608 | assert calls == ["https://boards-api.greenhouse.io/v1/boards/meta/jobs"] |
| 609 | |
| 610 | |
| 611 | # --- The digest carries the roles the run ranked highest --- |
| 612 | |
| 613 | |
| 614 | def _board_row(index, *, department, location, title=None): |
| 615 | return { |
| 616 | "id": f"GH{index}", |
| 617 | "title": title or f"Role {index}", |
| 618 | "url": f"https://boards.greenhouse.io/waymo/jobs/{index}", |
| 619 | "description": f"Own the number {index} line.", |
| 620 | "description_blocks": f"Own the number {index} line.", |
| 621 | "date": "2026-11-09", |
| 622 | "posted_date_true": True, |
| 623 | "provider": "greenhouse", |
| 624 | "department": department, |
| 625 | "location": location, |
| 626 | } |
| 627 | |
| 628 | |
| 629 | def _waymo_board(): |
| 630 | """Forty-five one-of-a-kind roles the rarity pick takes, then fifteen in |
| 631 | one department and one city that it leaves out.""" |
| 632 | rare = [ |
| 633 | _board_row(index, department=f"Dept {index}", location=f"City {index}") for index in range(45) |
| 634 | ] |
| 635 | common = [ |
| 636 | _board_row(index, department="Engineering", location="Mountain View", title=f"Engineer {index}") |
| 637 | for index in range(45, 60) |
| 638 | ] |
| 639 | return rare + common |
| 640 | |
| 641 | |
| 642 | def test_roles_the_run_ranked_take_up_to_ten_of_the_forty_digest_places(): |
| 643 | rows = _waymo_board() |
| 644 | selected = jobs_digest.select_roles(rows) |
| 645 | digest = jobs_digest.build_digest(rows, selected) |
| 646 | picked = [entry["url"] for entry in digest["roles"]] |
| 647 | assert len(picked) == 40 |
| 648 | common = [row["url"] for row in rows[45:]] |
| 649 | assert not set(common) & set(picked) |
| 650 | |
| 651 | ranked = [*common[:12], picked[3], "https://boards.greenhouse.io/other/jobs/1"] |
| 652 | out = jobs_digest.add_engine_roles(digest, rows, ranked) |
| 653 | |
| 654 | urls = [entry["url"] for entry in out["roles"]] |
| 655 | assert len(urls) == jobs_digest.DIGEST_MAX_ROLES == 40 |
| 656 | assert jobs_digest.ENGINE_ROLE_SLOTS == 10 |
| 657 | assert urls[:10] == common[:10] |
| 658 | assert urls[10:] == picked[:30] |
| 659 | assert all(entry.get("engine") for entry in out["roles"][:10]) |
| 660 | assert out["roles"][0]["text"] == "Own the number 45 line." |
| 661 | assert out["roles"][0]["posted"] == "2026-11-09" |
| 662 | # The ten places are spent: a role ranked after them is not reserved. |
| 663 | assert out["roles"][13]["url"] == picked[3] and not out["roles"][13].get("engine") |
| 664 | assert out["engine_roles"] == 10 |
| 665 | assert out["distinct_roles"] == digest["distinct_roles"] |
| 666 | # The digest it was given is not changed. |
| 667 | assert [entry["url"] for entry in digest["roles"]] == picked |
| 668 | assert not any(entry.get("engine") for entry in digest["roles"]) |
| 669 | |
| 670 | |
| 671 | def test_digest_with_no_ranked_roles_is_the_rarity_pick(): |
| 672 | rows = _waymo_board() |
| 673 | digest = jobs_digest.build_digest(rows, jobs_digest.select_roles(rows)) |
| 674 | out = jobs_digest.add_engine_roles(digest, rows, []) |
| 675 | assert out["roles"] == digest["roles"] |
| 676 | assert out["engine_roles"] == 0 |
| 677 | |
| 678 | |
| 679 | def _job_candidate(row, score): |
| 680 | item = schema.SourceItem( |
| 681 | item_id=row["id"], source="jobs", title=row["title"], body="", url=row["url"], |
| 682 | ) |
| 683 | return schema.Candidate( |
| 684 | candidate_id=f"c{row['id']}", item_id=item.item_id, source="jobs", title=item.title, |
| 685 | url=item.url, snippet="", subquery_labels=["primary"], native_ranks={}, |
| 686 | local_relevance=0.5, freshness=50, engagement=None, source_quality=0.5, |
| 687 | rrf_score=0.1, sources=["jobs"], source_items=[item], final_score=score, |
| 688 | ) |
| 689 | |
| 690 | |
| 691 | def test_ranked_postings_and_hiring_signal_roles_are_taken_in_turn(): |
| 692 | rows = _waymo_board() |
| 693 | ranked = [_job_candidate(rows[index], 90 - index) for index in (50, 51, 52)] |
| 694 | summary = { |
| 695 | "mode": "standard", "include": True, "rejected_job_keys": [], |
| 696 | "strategic_candidates": [{"title": "Engineer 55", "url": rows[55]["url"]}], |
| 697 | "signals": [{"theme": "go-to-market", "evidence": [ |
| 698 | {"title": "Engineer 56", "url": rows[56]["url"]}, |
| 699 | {"title": "Engineer 50", "url": rows[50]["url"]}, |
| 700 | ]}], |
| 701 | } |
| 702 | assert pipeline._engine_ranked_job_urls(ranked, summary) == [ |
| 703 | rows[index]["url"] for index in (50, 55, 51, 56, 52) |
| 704 | ] |
| 705 | # A Hiring Signals block the run does not print names no roles. |
| 706 | assert pipeline._engine_ranked_job_urls(ranked, {**summary, "include": False}) == [ |
| 707 | rows[index]["url"] for index in (50, 51, 52) |
| 708 | ] |
| 709 | # A posting the ranking rejected is not one it ranked. |
| 710 | from lib import fusion |
| 711 | rejected = {**summary, "rejected_job_keys": [fusion.candidate_key(ranked[0].source_items[0])]} |
| 712 | assert rows[50]["url"] not in pipeline._engine_ranked_job_urls(ranked, rejected)[:1] |
| 713 | |
| 714 | |
| 715 | def test_pipeline_adds_the_ranked_roles_to_the_boards_digest_and_drops_the_rows(): |
| 716 | rows = _waymo_board() |
| 717 | digest = jobs_digest.build_digest(rows, jobs_digest.select_roles(rows)) |
| 718 | board = {"tier": "ats", "provider": "greenhouse", "company": "Waymo", "open_roles": 60, |
| 719 | "owned": True, "digest": digest} |
| 720 | bundle = schema.RetrievalBundle(artifacts={"jobs": board}) |
| 721 | bundle.jobs_board_rows = rows |
| 722 | ranked = [_job_candidate(rows[index], 90 - index) for index in (58, 59)] |
| 723 | |
| 724 | pipeline._add_ranked_roles_to_jobs_digest(bundle, ranked, None) |
| 725 | |
| 726 | roles = bundle.artifacts["jobs"]["digest"]["roles"] |
| 727 | assert [entry["title"] for entry in roles[:2]] == ["Engineer 58", "Engineer 59"] |
| 728 | assert len(roles) == 40 |
| 729 | assert bundle.jobs_board_rows == [] |
| 730 | |
| 731 | text = "\n".join(render._render_jobs_digest(_report("Waymo", bundle.artifacts["jobs"]))) |
| 732 | assert "- Roles listed: 40 of 60 distinct roles, the first 2 are the roles this run's own ranking" in text |
| 733 | assert text.index("Engineer 58") < text.index("Role 0") |
| 734 | |
| 735 | |
| 736 | def test_a_ranked_role_the_board_keeps_out_of_the_digest_stays_out(): |
| 737 | rows = _waymo_board() |
| 738 | rows[58]["digest_excluded"] = True |
| 739 | eligible = [row for row in rows if not row.get("digest_excluded")] |
| 740 | digest = jobs_digest.build_digest(eligible, jobs_digest.select_roles(eligible)) |
| 741 | board = {"tier": "ats", "provider": "apple", "company": "Waymo", "open_roles": 60, |
| 742 | "owned": True, "digest": digest} |
| 743 | bundle = schema.RetrievalBundle(artifacts={"jobs": board}) |
| 744 | bundle.jobs_board_rows = rows |
| 745 | ranked = [_job_candidate(rows[index], 90 - index) for index in (58, 59)] |
| 746 | |
| 747 | pipeline._add_ranked_roles_to_jobs_digest(bundle, ranked, None) |
| 748 | |
| 749 | titles = [entry["title"] for entry in bundle.artifacts["jobs"]["digest"]["roles"]] |
| 750 | assert titles[0] == "Engineer 59" and "Engineer 58" not in titles |
| 751 | |
| 752 | |
| 753 | def test_board_with_no_digest_gets_no_ranked_roles(): |
| 754 | rows = _waymo_board() |
| 755 | board = {"tier": "ats", "provider": "greenhouse", "company": "Waymo", "open_roles": 60, "owned": False} |
| 756 | bundle = schema.RetrievalBundle(artifacts={"jobs": board}) |
| 757 | bundle.jobs_board_rows = rows |
| 758 | pipeline._add_ranked_roles_to_jobs_digest(bundle, [_job_candidate(rows[58], 90)], None) |
| 759 | assert "digest" not in bundle.artifacts["jobs"] |
| 760 | assert bundle.jobs_board_rows == [] |
| 761 | |
| 762 | |
| 763 | def test_ranked_roles_a_board_gave_no_text_for_are_counted_in_the_note(): |
| 764 | # Workday gives a role's text one call at a time, made for the rarity |
| 765 | # picks before anything is ranked. |
| 766 | rows = _waymo_board() |
| 767 | for row in rows[45:]: |
| 768 | row["description"] = row["description_blocks"] = "" |
| 769 | row["whole_posting"] = True |
| 770 | digest = jobs_digest.build_digest(rows, jobs_digest.select_roles(rows)) |
| 771 | out = jobs_digest.add_engine_roles({**digest, "note": "earlier note"}, rows, [rows[50]["url"], rows[51]["url"]]) |
| 772 | assert [entry["title"] for entry in out["roles"][:2]] == ["Engineer 50", "Engineer 51"] |
| 773 | assert out["note"].startswith("earlier note; 2 of the ranked roles listed first have no role text") |
| 774 | |
| 775 | |
| 776 | # --- The web fallback: only real postings, never ads or landing pages --- |
| 777 | |
| 778 | AD = ( |
| 779 | "https://duckduckgo.com/y.js?ad_domain=career%2Dedge.net&ad_provider=bingv7aa" |
| 780 | "&ad_type=txad&click_metadata=fDVA_zkAVS87wM1gPeREjxYWU" |
| 781 | ) |
| 782 | # What the web search gave for "Disney careers jobs hiring" on 2026-11-10. |
| 783 | DISNEY_WEB = [ |
| 784 | {"title": "Search our Job Opportunities at DISNEY - Disney Careers", |
| 785 | "url": "https://www.disneycareers.com/en/search-jobs", "snippet": "Search jobs at Disney."}, |
| 786 | {"title": "Disney® Careers - Hiring All Positions", "url": AD, |
| 787 | "snippet": "Hiring Immediately. Full & Part-Time Disney Jobs."}, |
| 788 | {"title": "Disney Jobs (Positions Open) - Disney Careers (Applications)", |
| 789 | "url": AD.replace("career%2Dedge.net", "jobmatcher.io"), "snippet": "Hiring Now."}, |
| 790 | {"title": "Careers at Disney | Disney Careers", "url": "https://jobs.disneycareers.com/", "snippet": ""}, |
| 791 | ] |
| 792 | # And for "Sundar Pichai careers jobs hiring", on v3.34.1 and after. |
| 793 | PICHAI_WEB = [ |
| 794 | {"title": "Sundar Pichai - Wikipedia", "url": "https://en.wikipedia.org/wiki/Sundar_Pichai", |
| 795 | "snippet": "Pichai began his career as a materials engineer."}, |
| 796 | {"title": "How to get a job at Google, according to the CEO | Fortune", |
| 797 | "url": "https://fortune.com/2024/10/12/how-to-get-a-job-at-google-ceo-sundar-pichai-entry-level-hiring/", |
| 798 | "snippet": "Hiring advice."}, |
| 799 | {"title": "11,000+Sundar Pichai In Inr Jobs in United States - LinkedIn", |
| 800 | "url": "https://www.linkedin.com/jobs/sundar-pichai-in-inr-jobs", "snippet": "Jobs."}, |
| 801 | {"title": "Careers", "url": "https://duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2Fcareers", "snippet": ""}, |
| 802 | ] |
| 803 | |
| 804 | |
| 805 | def _web(results): |
| 806 | return patch("lib.jobs.grounding.web_search", return_value=(results, {"label": "keyless"})) |
| 807 | |
| 808 | |
| 809 | def test_web_fallback_with_ads_landing_pages_and_wikipedia_ends_with_nothing(capsys): |
| 810 | for company, results in (("Disney", DISNEY_WEB), ("Sundar Pichai", PICHAI_WEB)): |
| 811 | with _web(results), \ |
| 812 | patch("lib.jobs.http.get_text", return_value=None), \ |
| 813 | patch("lib.jobs.http.get", side_effect=_not_found), \ |
| 814 | http.capture_failures() as failures: |
| 815 | items, artifact = jobs.search_jobs(company, WINDOW, {}, web_backend="keyless") |
| 816 | assert items == [] |
| 817 | assert artifact["tier"] == "web" and artifact["resultCount"] == 0 |
| 818 | assert "_source_outcome" not in artifact |
| 819 | assert failures == [] |
| 820 | err = capsys.readouterr().err |
| 821 | assert err.count("[Jobs]") == 1 |
| 822 | assert f"[Jobs] no supported job board found for {company}" in err |
| 823 | |
| 824 | |
| 825 | def test_web_fallback_keeps_a_posting_on_a_recognised_board_that_names_the_company(): |
| 826 | results = [ |
| 827 | *DISNEY_WEB, |
| 828 | {"title": "Senior Engineer - Acme", "url": "https://boards.greenhouse.io/acme/jobs/4012345", |
| 829 | "snippet": "Join Acme."}, |
| 830 | {"title": "Designer", "url": "https://jobs.lever.co/acme/0b1c2d3e-aaaa-bbbb-cccc-0123456789ab", |
| 831 | "snippet": ""}, |
| 832 | {"title": "Analyst at Acme", "url": "https://acme.wd5.myworkdayjobs.com/en-US/AcmeCareers/job/Remote/Analyst_JR1", |
| 833 | "snippet": ""}, |
| 834 | # A board's front page is a landing page, and another company's |
| 835 | # posting is not this company's. |
| 836 | {"title": "Jobs at Acme", "url": "https://boards.greenhouse.io/acme", "snippet": ""}, |
| 837 | {"title": "Engineer who loves Acme products", "url": "https://jobs.ashbyhq.com/other/0b1c2d3e-aaaa-bbbb-cccc-0123456789ab", |
| 838 | "snippet": "Acme"}, |
| 839 | ] |
| 840 | with _web(results): |
| 841 | items, _artifact = jobs.search_jobs_web("Acme", WINDOW, {}, backend="keyless") |
| 842 | assert [item["url"] for item in items] == [ |
| 843 | "https://boards.greenhouse.io/acme/jobs/4012345", |
| 844 | "https://jobs.lever.co/acme/0b1c2d3e-aaaa-bbbb-cccc-0123456789ab", |
| 845 | "https://acme.wd5.myworkdayjobs.com/en-US/AcmeCareers/job/Remote/Analyst_JR1", |
| 846 | ] |
| 847 | |
| 848 | |
| 849 | def test_careers_page_search_skips_ad_and_redirect_links(): |
| 850 | with _web(DISNEY_WEB[1:3] + [PICHAI_WEB[3]] + DISNEY_WEB[:1]): |
| 851 | assert jobs._search_for_careers_url("Disney", WINDOW, {}, backend="keyless") == ( |
| 852 | "https://www.disneycareers.com/en/search-jobs" |
| 853 | ) |
| 854 | with _web(DISNEY_WEB[1:3]): |
| 855 | assert jobs._search_for_careers_url("Disney", WINDOW, {}, backend="keyless") is None |
| 856 | |
| 857 | |
| 858 | def test_run_with_no_valid_jobs_prints_no_jobs_footer_line_or_source(): |
| 859 | report = _report("Disney", None) |
| 860 | report.artifacts = {} |
| 861 | footer = "\n".join(render._render_emoji_footer(report, None)) |
| 862 | assert "💼" not in footer and "Jobs" not in footer |
| 863 | |
| 864 | |
| 865 | def test_topic_and_host_companies_with_no_board_get_one_stderr_line(capsys): |
| 866 | with patch("lib.jobs.http.get_text", return_value=None), \ |
| 867 | patch("lib.jobs.http.get", side_effect=_not_found), \ |
| 868 | _web(PICHAI_WEB): |
| 869 | subquery = schema.SubQuery( |
| 870 | label="primary", search_query="Sundar Pichai", ranking_query="Sundar Pichai", sources=["jobs"], |
| 871 | ) |
| 872 | items, artifact = pipeline._retrieve_stream_impl( |
| 873 | topic="Sundar Pichai", subquery=subquery, source="jobs", |
| 874 | config={"_company": {"host_companies": ["Alphabet"]}}, |
| 875 | depth="default", date_range=WINDOW, runtime=None, mock=False, |
| 876 | web_backend="keyless", raw_topic="Sundar Pichai", |
| 877 | ) |
| 878 | assert items == [] |
| 879 | assert "_source_outcome" not in artifact |
| 880 | err = capsys.readouterr().err |
| 881 | assert err.count("[Jobs]") == 1 |
| 882 | assert "[Jobs] no supported job board found for Sundar Pichai (also tried: Alphabet)" in err |
| 883 | |
| 884 | |
| 885 | # --- Review findings on the first version of this change --- |
| 886 | |
| 887 | |
| 888 | def test_web_fallback_for_a_company_with_no_board_stays_inside_its_discovery_share(): |
| 889 | # A person topic with host companies: the topic's own search may use a |
| 890 | # share of the budget, and the web fallback is part of that search. With |
| 891 | # the whole budget it could leave the later companies no time. |
| 892 | clock = Clock() |
| 893 | budget = jobs.LaneBudget(45.0, clock=clock) |
| 894 | seen = {} |
| 895 | |
| 896 | def web(company, *_args, **_kwargs): |
| 897 | seen["remaining"] = budget.remaining() |
| 898 | return [], {} |
| 899 | |
| 900 | with patch("lib.jobs.http.get_text", return_value=None), \ |
| 901 | patch("lib.jobs.http.get", side_effect=_not_found), \ |
| 902 | patch.object(jobs, "search_jobs_web", side_effect=web): |
| 903 | jobs.search_jobs( |
| 904 | "Elon Musk", WINDOW, {}, web_backend="keyless", budget=budget, discovery_seconds=15.0, |
| 905 | ) |
| 906 | assert seen["remaining"] <= 15.0 |
| 907 | # The share ends with the call; the next company starts from the budget. |
| 908 | assert budget.remaining() == 45.0 |
| 909 | |
| 910 | |
| 911 | def test_found_board_is_read_with_the_whole_budget_not_the_discovery_share(): |
| 912 | clock = Clock() |
| 913 | budget = jobs.LaneBudget(45.0, clock=clock) |
| 914 | seen = {} |
| 915 | |
| 916 | def board(token, *, deadline): |
| 917 | seen["remaining"] = budget.remaining() |
| 918 | return [], {} |
| 919 | |
| 920 | with patch("lib.jobs.http.get_text", return_value=CAREERS), \ |
| 921 | patch.object(jobs, "search_workday_board", side_effect=board): |
| 922 | jobs.search_jobs( |
| 923 | "Acme", WINDOW, {}, web_backend="none", site="https://www.acme.com", |
| 924 | budget=budget, discovery_seconds=15.0, |
| 925 | ) |
| 926 | assert seen["remaining"] == 45.0 |
| 927 | |
| 928 | |
| 929 | def test_top_ranked_role_at_the_end_of_the_rarity_picks_is_not_trimmed_away(): |
| 930 | rows = _waymo_board() |
| 931 | digest = jobs_digest.build_digest(rows, jobs_digest.select_roles(rows)) |
| 932 | picked = [entry["url"] for entry in digest["roles"]] |
| 933 | # The run's best role is the rarity pick in the last place; one |
| 934 | # lower-ranked role is added in front. |
| 935 | out = jobs_digest.add_engine_roles(digest, rows, [picked[39], rows[50]["url"]]) |
| 936 | urls = [entry["url"] for entry in out["roles"]] |
| 937 | assert len(urls) == 40 |
| 938 | assert picked[39] in urls and rows[50]["url"] in urls |
| 939 | assert picked[38] not in urls # the rarest unranked role gave up its place |
| 940 | assert next(entry for entry in out["roles"] if entry["url"] == picked[39])["engine"] is True |
| 941 | assert out["engine_roles"] == 2 |
| 942 | |
| 943 | |
| 944 | def test_ranked_roles_beyond_the_reserved_places_are_not_reserved(): |
| 945 | rows = _waymo_board() |
| 946 | digest = jobs_digest.build_digest(rows, jobs_digest.select_roles(rows)) |
| 947 | picked = [entry["url"] for entry in digest["roles"]] |
| 948 | # Every pick is ranked, then a role off the list: the ten reserved places |
| 949 | # are the ten best ranked, all already listed, so nothing is added. |
| 950 | out = jobs_digest.add_engine_roles(digest, rows, [*picked, rows[50]["url"]]) |
| 951 | assert [entry["url"] for entry in out["roles"]] == picked |
| 952 | assert out["engine_roles"] == jobs_digest.ENGINE_ROLE_SLOTS |
| 953 | |
| 954 | |
| 955 | def test_hard_deadline_of_a_request_is_its_own_time_limit_not_the_lanes_remaining_time(): |
| 956 | import time as real_time |
| 957 | seen = [] |
| 958 | |
| 959 | def page(url, **kwargs): |
| 960 | seen.append((kwargs["timeout"], kwargs["deadline_monotonic"] - real_time.monotonic())) |
| 961 | return None |
| 962 | |
| 963 | def api(url, *_args, **kwargs): |
| 964 | seen.append((kwargs["timeout"] * kwargs["retries"] + 5, kwargs["deadline_monotonic"] - real_time.monotonic())) |
| 965 | raise http.HTTPError("HTTP 404: Not Found", status_code=404) |
| 966 | |
| 967 | with patch("lib.jobs.http.get_text", side_effect=page), patch("lib.jobs.http.get", side_effect=api): |
| 968 | jobs.search_jobs("Kanye West", WINDOW, {}, web_backend="none") |
| 969 | assert len(seen) == 6 + 6 |
| 970 | for limit, hard in seen: |
| 971 | # A host that stalls in DNS or trickles bytes is cut off here. |
| 972 | assert hard <= limit |
| 973 | |
| 974 | |
| 975 | def test_hard_deadline_never_passes_the_lanes_remaining_time(): |
| 976 | import time as real_time |
| 977 | clock = Clock() |
| 978 | budget = jobs.LaneBudget(45.0, clock=clock) |
| 979 | clock.advance(43.0) |
| 980 | token = jobs._BUDGET.set(budget) |
| 981 | try: |
| 982 | bounds = jobs._bounds(jobs.PAGE_TIMEOUT_SECONDS) |
| 983 | finally: |
| 984 | jobs._BUDGET.reset(token) |
| 985 | assert bounds["deadline_monotonic"] - real_time.monotonic() <= 2.0 |
| 986 | |
| 987 | |
| 988 | def test_listing_page_of_a_paged_board_has_its_own_hard_deadline(): |
| 989 | import time as real_time |
| 990 | seen = [] |
| 991 | |
| 992 | def post(url, json_data, headers=None, **kwargs): |
| 993 | seen.append(kwargs["deadline_monotonic"] - real_time.monotonic()) |
| 994 | return {"total": 1, "jobPostings": []} |
| 995 | |
| 996 | with patch("lib.jobs.http.post", side_effect=post): |
| 997 | jobs.search_workday_board("acme.wd5/AcmeCareers") |
| 998 | assert seen and seen[0] <= jobs.API_TIMEOUT_SECONDS * 2 + 5 |
| 999 | |
| 1000 | |
| 1001 | def _stalled_greenhouse_working_ashby(url, *_args, **_kwargs): |
| 1002 | if "greenhouse" in url: |
| 1003 | raise http.DeadlineExceeded() # this request reached its own limit |
| 1004 | if url == "https://api.ashbyhq.com/posting-api/job-board/acme": |
| 1005 | return {"jobs": [{"id": "1", "title": "Engineer", "jobUrl": "https://jobs.ashbyhq.com/acme/1"}]} |
| 1006 | raise http.HTTPError("HTTP 404: Not Found", status_code=404) |
| 1007 | |
| 1008 | |
| 1009 | def test_probe_that_reaches_its_own_time_limit_does_not_end_the_probing(): |
| 1010 | # Greenhouse stalls for its ~22 s; half the lane's budget is left and the |
| 1011 | # company's board is on Ashby. |
| 1012 | budget = jobs.LaneBudget(45.0) |
| 1013 | with patch("lib.jobs.http.get_text", return_value=None), \ |
| 1014 | patch("lib.jobs.http.get", side_effect=_stalled_greenhouse_working_ashby): |
| 1015 | items, artifact = jobs.search_jobs("Acme", WINDOW, {}, web_backend="none", budget=budget) |
| 1016 | assert [item["title"] for item in items] == ["Engineer"] |
| 1017 | assert artifact["tier"] == "ats" and artifact["provider"] == "ashby" |
| 1018 | assert budget.stopped_at == "" |
| 1019 | assert "_source_out_of_time" not in artifact |
| 1020 | |
| 1021 | |
| 1022 | def test_probe_that_reached_its_own_limit_with_no_board_elsewhere_is_named_and_can_be_retried(capsys): |
| 1023 | asked = [] |
| 1024 | |
| 1025 | def api(url, *_args, **_kwargs): |
| 1026 | asked.append(url.split("/")[2]) |
| 1027 | if "greenhouse" in url: |
| 1028 | raise http.DeadlineExceeded() |
| 1029 | raise http.HTTPError("HTTP 404: Not Found", status_code=404) |
| 1030 | |
| 1031 | budget = jobs.LaneBudget(45.0) |
| 1032 | with patch("lib.jobs.http.get_text", return_value=None), patch("lib.jobs.http.get", side_effect=api): |
| 1033 | items, artifact = jobs.search_jobs("Acme", WINDOW, {}, web_backend="none", budget=budget) |
| 1034 | assert asked == ["boards-api.greenhouse.io", "api.ashbyhq.com", "api.lever.co"] |
| 1035 | assert items == [] |
| 1036 | outcome = artifact["_source_outcome"] |
| 1037 | assert outcome["state"] == health.TIMEOUT |
| 1038 | assert "the greenhouse API did not answer for the slug acme" in outcome["detail"] |
| 1039 | assert "budget" not in outcome["detail"] |
| 1040 | # The lane had time left: the thin-results retry may ask again. |
| 1041 | assert "_source_out_of_time" not in artifact |
| 1042 | assert budget.stopped_at == "" |
| 1043 | assert outcome["detail"] in capsys.readouterr().err |
| 1044 | |
| 1045 | |
| 1046 | def test_probe_cut_off_by_the_lanes_own_deadline_still_ends_the_probing(): |
| 1047 | clock = Clock() |
| 1048 | budget = jobs.LaneBudget(45.0, clock=clock) |
| 1049 | asked = [] |
| 1050 | |
| 1051 | def api(url, *_args, **_kwargs): |
| 1052 | asked.append(url) |
| 1053 | clock.advance(50.0) # the lane's budget ran out during this request |
| 1054 | raise http.DeadlineExceeded() |
| 1055 | |
| 1056 | with patch("lib.jobs.http.get_text", return_value=None), patch("lib.jobs.http.get", side_effect=api): |
| 1057 | items, artifact = jobs.search_jobs("Acme", WINDOW, {}, web_backend="none", budget=budget) |
| 1058 | assert len(asked) == 1 |
| 1059 | assert items == [] |
| 1060 | assert "45s budget" in artifact["_source_outcome"]["detail"] |
| 1061 | assert artifact["_source_out_of_time"] is True |
| 1062 | |
| 1063 | |
| 1064 | def test_discovery_share_running_out_is_not_the_lane_running_out(): |
| 1065 | # The topic used its share; the lane still has time for the next company |
| 1066 | # and for a retry, so the source is not marked out of time. |
| 1067 | clock = Clock() |
| 1068 | budget = jobs.LaneBudget(45.0, clock=clock) |
| 1069 | |
| 1070 | def page(url, **_kwargs): |
| 1071 | clock.advance(6.0) |
| 1072 | return None |
| 1073 | |
| 1074 | with patch("lib.jobs.http.get_text", side_effect=page), \ |
| 1075 | patch("lib.jobs.http.get", side_effect=AssertionError("the share is spent")): |
| 1076 | items, artifact = jobs.search_jobs( |
| 1077 | "Kanye West", WINDOW, {}, web_backend="none", budget=budget, discovery_seconds=10.0, |
| 1078 | ) |
| 1079 | assert items == [] |
| 1080 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 1081 | assert "_source_out_of_time" not in artifact |
| 1082 | assert not budget.spent() |
| 1083 |