返回 last30days-skill
test_jobs_company_boards.py
根目录 / tests / test_jobs_company_boards.py
1 """Company-run job boards: the registry, the readers and the honest failure.
2
3 A large company often runs its own job site, so no link on its careers page
4 names a hosted board. The lane reads such a board only when the run knows the
5 company's official site and that site is in the registry, and says plainly
6 when a known job site cannot be read.
7 """
8
9 from __future__ import annotations
10
11 import copy
12 import json
13 import time
14 from pathlib import Path
15 from unittest.mock import patch
16
17 import pytest
18
19 from lib import http, jobs, jobs_digest, render
20
21 from tests.test_render_patents import _report
22
23 WINDOW = ("2026-10-15", "2026-11-14")
24 SITE = "https://www.acmecorp.com/"
25
26
27 def _role(index, *, date="2026-11-10", posted=True, **extra):
28 item = jobs._ats_item(
29 provider="stub", slug="jobs.acmecorp.com", ident=f"R{index}",
30 title=f"Engineer {index}, Team {index}", url=f"https://jobs.acmecorp.com/roles/{index}",
31 description=f"Build system {index} for team {index}.", date=date,
32 department=f"Team {index}", location="Austin, TX", posted_date_true=posted,
33 whole_posting=True,
34 )
35 item.update(extra)
36 return item
37
38
39 @pytest.fixture
40 def stub(monkeypatch):
41 """A company board registered for acmecorp.com, read by a stub reader."""
42 calls = {"reader": [], "details": []}
43 state = {"rows": [_role(n) for n in range(6)], "info": {"board_total": 6}}
44
45 def reader(entry, *, deadline, **_kwargs):
46 calls["reader"].append({"entry": entry, "deadline": deadline})
47 return list(state["rows"]), dict(state["info"])
48
49 def details(items, *, deadline):
50 calls["details"].append({"ids": [item["id"] for item in items], "deadline": deadline})
51 for item in items:
52 item["description_blocks"] = f"Full text of {item['title']}."
53 return 0, 0
54
55 monkeypatch.setitem(
56 jobs.COMPANY_BOARDS, "acmecorp.com",
57 {"name": "Acme", "provider": "stub", "board": "jobs.acmecorp.com"},
58 )
59 monkeypatch.setitem(jobs._COMPANY_READERS, "stub", "_stub_reader")
60 monkeypatch.setitem(jobs._DETAIL_FETCHERS, "stub", "_stub_details")
61 monkeypatch.setattr(jobs, "_stub_reader", reader, raising=False)
62 monkeypatch.setattr(jobs, "_stub_details", details, raising=False)
63 return calls, state
64
65
66 class _NoRequests:
67 """Records every request the lane sends and answers it with a 404."""
68
69 def __init__(self):
70 self.urls = []
71
72 def __call__(self, url, *_args, **_kwargs):
73 self.urls.append(url)
74 raise http.HTTPError("HTTP 404: Not Found", status_code=404)
75
76 def text(self, url, *_args, **_kwargs):
77 # ``get_text`` answers a failure with None rather than raising.
78 self.urls.append(url)
79 return None
80
81
82 def _search(company="Acme", site=SITE, **kwargs):
83 requests = _NoRequests()
84 with patch.object(jobs.http, "get_text", side_effect=requests.text), \
85 patch.object(jobs.http, "get", side_effect=requests), \
86 patch.object(jobs.http, "post", side_effect=requests), \
87 http.capture_failures() as failures:
88 kwargs.setdefault("web_backend", "none")
89 items, artifact = jobs.search_jobs(company, WINDOW, {}, site=site, **kwargs)
90 return items, artifact, requests.urls, failures
91
92
93 # --- the registry is consulted only with a known official site ---
94
95
96 def test_a_run_with_no_known_site_never_reaches_a_registered_reader(stub):
97 calls, _state = stub
98 _items, artifact, urls, _failures = _search(site="")
99 assert calls["reader"] == []
100 assert artifact["tier"] == "web"
101 # Today's discovery ran: guessed domains, then hosted-system slugs.
102 assert any("acme.com/careers" in url for url in urls)
103
104
105 def test_a_known_site_outside_the_registry_follows_todays_discovery(stub):
106 calls, _state = stub
107 _items, artifact, urls, _failures = _search(company="Initech", site="https://www.initech.com/")
108 assert calls["reader"] == []
109 assert urls[0] == "https://www.initech.com/careers"
110 assert "job_site_unreadable" not in artifact
111
112
113 def test_a_registered_reader_s_rows_become_an_ats_artifact_with_a_digest(stub):
114 calls, _state = stub
115 items, artifact, urls, _failures = _search()
116 assert len(items) == 6
117 assert artifact["tier"] == "ats"
118 assert artifact["provider"] == "stub"
119 assert artifact["owned"] and artifact["found_via"] == "site"
120 assert artifact["digest"]["roles"]
121 assert calls["reader"][0]["entry"]["board"] == "jobs.acmecorp.com"
122 # Nothing else was asked: no careers page, no slug probe.
123 assert urls == []
124
125
126 def test_detail_text_is_fetched_for_the_selected_roles_only(stub):
127 calls, state = stub
128 state["rows"] = [_role(n) for n in range(60)]
129 state["info"] = {"board_total": 60}
130 _items, artifact, _urls, _failures = _search()
131 [fetched] = calls["details"]
132 selected = {role["url"] for role in artifact["digest"]["roles"]}
133 assert {f"https://jobs.acmecorp.com/roles/{ident[3:]}" for ident in fetched["ids"]} == selected
134 assert len(fetched["ids"]) < 60
135
136
137 def test_a_list_read_leaves_time_for_the_role_text(stub):
138 calls, _state = stub
139 started = time.monotonic()
140 _search()
141 [read] = calls["reader"]
142 [fetched] = calls["details"]
143 budget = jobs.JOBS_BUDGET_SECONDS
144 # The listing must end with about a third of the budget still left for the text.
145 assert read["deadline"] - started <= budget * (1 - jobs.DETAIL_SHARE) + 1
146 assert fetched["deadline"] - started >= budget - 1
147
148
149 def test_a_comparison_gives_the_reader_its_entity_s_share(stub):
150 calls, _state = stub
151 started = time.monotonic()
152 _search(entity_count=3)
153 [read] = calls["reader"]
154 assert read["deadline"] - started <= jobs.JOBS_BUDGET_SECONDS / 3 + 1
155
156
157 def test_roles_marked_excluded_are_counted_but_never_selected(stub):
158 _calls, state = stub
159 state["rows"] = [_role(n, digest_excluded=n < 4) for n in range(8)]
160 state["info"] = {"board_total": 8}
161 _items, artifact, _urls, _failures = _search()
162 titles = {role["title"] for role in artifact["digest"]["roles"]}
163 assert titles and not any(f"Engineer {n}," in title for n in range(4) for title in titles)
164 assert artifact["open_roles"] == 8
165
166
167 # --- counts from a board read newest first ---
168
169
170 def test_a_newest_first_read_that_left_the_window_counts_new_roles_exactly(stub):
171 _calls, state = stub
172 state["rows"] = [_role(n, date="2026-11-01") for n in range(5)] + [
173 _role(n, date="2026-09-01") for n in range(5, 15)
174 ]
175 state["info"] = {
176 "board_total": 6459, "board_newest_first": True, "board_window_covered": True,
177 "board_cut_short": True,
178 }
179 _items, artifact, _urls, _failures = _search()
180 assert artifact["open_roles"] == 6459
181 assert artifact["open_roles_floor"] is False
182 assert artifact["new_in_window"] == 5
183
184
185 def test_a_newest_first_read_cut_short_inside_the_window_prints_no_new_count(stub):
186 _calls, state = stub
187 state["rows"] = [_role(n, date="2026-11-12") for n in range(400)]
188 state["info"] = {
189 "board_total": 6459, "board_newest_first": True, "board_window_covered": False,
190 "board_cut_short": True,
191 }
192 _items, artifact, _urls, _failures = _search()
193 assert artifact["open_roles"] == 6459
194 assert artifact["new_in_window"] is None
195 line = render._jobs_board_footer_line(_report(jobs=artifact))
196 assert line == "💼 Jobs: 6,459 open roles"
197
198
199 def test_a_capped_board_total_prints_as_a_floor(stub):
200 _calls, state = stub
201 state["info"] = {
202 "board_total": 10000, "board_total_floor": True, "board_newest_first": True,
203 "board_window_covered": False, "board_cut_short": True,
204 }
205 _items, artifact, _urls, _failures = _search()
206 assert render._jobs_board_footer_line(_report(jobs=artifact)) == "💼 Jobs: 10,000+ open roles"
207
208
209 # --- a job site that cannot be read ---
210
211
212 def test_a_reader_that_fails_falls_to_the_sitemap_then_the_cant_be_read_outcome(stub, capsys):
213 _calls, state = stub
214 state["rows"] = []
215 items, artifact, urls, _failures = _search()
216 assert items == []
217 assert artifact["job_site_unreadable"] == "Acme"
218 assert "answered with an error" in artifact["job_site_unreadable_reason"]
219 # No slug probe: only the site's robots.txt files, asked for a job sitemap.
220 assert urls and all(url.endswith("/robots.txt") for url in urls)
221 assert "https://jobs.acmecorp.com/robots.txt" in urls
222 err = capsys.readouterr().err
223 assert "[Jobs] Acme's job site can't be read automatically" in err
224 assert "no supported job board found" not in err
225
226
227 @pytest.mark.parametrize(
228 ("company", "site", "name"),
229 [
230 ("Tesla", "https://www.tesla.com/", "Tesla"),
231 ("Meta Platforms", "https://about.meta.com/", "Meta"),
232 ],
233 )
234 def test_a_job_site_declared_unreadable_sends_no_request(company, site, name, capsys):
235 items, artifact, urls, failures = _search(company=company, site=site)
236 assert items == [] and urls == [] and failures == []
237 assert artifact["tier"] == "web"
238 assert artifact["job_site_unreadable"] == name
239 err = capsys.readouterr().err
240 assert f"{name}'s job site can't be read automatically" in err
241 assert "no supported job board found" not in err
242
243
244 def test_the_footer_says_a_known_job_site_cannot_be_read():
245 report = _report()
246 report.artifacts["jobs_site_unreadable"] = "Tesla"
247 rendered = render.render_compact(report)
248 assert "💼 Jobs: Tesla's job site can't be read automatically" in rendered
249
250
251 def test_the_footer_line_is_absent_when_the_site_is_not_in_the_registry():
252 _items, artifact, _urls, _failures = _search(company="Initech", site="https://www.initech.com/")
253 assert "job_site_unreadable" not in artifact
254 assert "can't be read automatically" not in render.render_compact(_report())
255
256
257 def test_a_hiring_signals_run_on_an_unreadable_site_still_returns_the_web_tier():
258 found = [{"id": "W1", "title": "Robotics Engineer", "url": "https://boards.greenhouse.io/tesla/jobs/1"}]
259 with patch.object(jobs, "search_jobs_web", return_value=(found, {"tier": "web"})):
260 items, artifact, urls, _failures = _search(
261 company="Tesla", site="https://www.tesla.com/", web_backend="auto", explicit=True,
262 )
263 assert items == found
264 assert artifact["job_site_unreadable"] == "Tesla"
265 assert urls == []
266
267
268 def test_a_board_url_on_a_company_job_site_is_still_ignored_without_a_request(capsys):
269 assert jobs.parse_board_url("https://jobs.apple.com/en-us/search") == (None, None)
270 requests = _NoRequests()
271 with patch.object(jobs.http, "get_text", side_effect=requests.text), \
272 patch.object(jobs.http, "get", side_effect=requests), \
273 patch.object(jobs.http, "post", side_effect=requests):
274 items, artifact = jobs.search_board_url(
275 "https://jobs.apple.com/en-us/search", ["Apple"], WINDOW, {},
276 )
277 assert (items, artifact) == ([], {})
278 assert requests.urls == []
279 err = capsys.readouterr().err
280 assert err.count("--jobs-board ignored: jobs.apple.com") == 1
281
282
283 # --- Amazon -------------------------------------------------------------------
284
285 FIXTURES = Path(__file__).parent / "fixtures"
286 AMAZON = json.loads((FIXTURES / "jobs_amazon_search.json").read_text(encoding="utf-8"))
287
288
289 def _amazon(pages, *, fail_at=None):
290 asked = []
291
292 def get(url, params=None, **_kwargs):
293 offset = int((params or {}).get("offset") or 0)
294 asked.append((url, offset))
295 index = offset // jobs.AMAZON_PAGE_SIZE
296 if index == fail_at:
297 raise http.HTTPError("HTTP 503: Service Unavailable", status_code=503)
298 if url.startswith("https://www.amazon.jobs/") and index < len(pages):
299 return copy.deepcopy(pages[index])
300 raise http.HTTPError("HTTP 404: Not Found", status_code=404)
301
302 return asked, get
303
304
305 def _amazon_search(pages, **kwargs):
306 asked, get = _amazon(pages, **kwargs)
307 texts = _NoRequests()
308 # The recorded pages are trimmed to three rows each: the page size the
309 # reader asks for matches them, so a full page reads as full.
310 with patch.object(jobs, "AMAZON_PAGE_SIZE", 3), \
311 patch.object(jobs.http, "get", side_effect=get), \
312 patch.object(jobs.http, "get_text", side_effect=texts.text), \
313 patch.object(jobs.http, "post", side_effect=texts):
314 items, artifact = jobs.search_jobs(
315 "Amazon", WINDOW, {}, web_backend="none", site="https://www.amazon.com/",
316 )
317 return items, artifact, asked, texts.urls
318
319
320 def test_amazon_pages_parse_to_rows_with_their_full_text():
321 items = [item for page in AMAZON["pages"] for item in jobs.parse_amazon_response(page)[0]]
322 assert len(items) == 9
323 first = items[0]
324 assert first["title"] == "Sr. Electrical Engineer, Prime Air Perception"
325 assert first["url"] == "https://www.amazon.jobs/en/jobs/10605151/sr-electrical-engineer-prime-air-perception"
326 assert first["department"] == "retail"
327 assert first["location"] == "Seattle, Washington, USA"
328 assert (first["date"], first["posted_date_true"]) == ("2026-11-14", True)
329 assert first["provider"] == "amazon" and first["id"] == "AZ10605151"
330 assert "Bachelor's degree" in first["description_blocks"]
331 assert "\n" in first["description_blocks"]
332
333
334 def test_amazon_reads_past_a_mixed_page_and_stops_after_one_with_no_new_role():
335 items, artifact, asked, other = _amazon_search(AMAZON["pages"])
336 assert len(items) == 9
337 assert {0, 3, 6} <= {offset for _url, offset in asked}
338 assert artifact["tier"] == "ats" and artifact["provider"] == "amazon"
339 # Three new on the first page and two on the mixed second page.
340 assert artifact["new_in_window"] == 5
341 assert artifact["open_roles"] == 10000 and artifact["open_roles_floor"] is True
342 assert other == []
343
344
345 def test_amazon_s_capped_total_prints_as_a_floor_and_the_run_prints_a_digest():
346 _items, artifact, _asked, _other = _amazon_search(AMAZON["pages"])
347 rendered = render.render_compact(_report(jobs=artifact))
348 assert "\n## Jobs Digest\n" in rendered
349 assert "💼 Jobs: 10,000+ open roles │ 5 new in the L30" in rendered
350 assert "Prime Air Perception" in rendered
351
352
353 def test_amazon_error_answered_as_http_200_is_the_cant_be_read_outcome():
354 error = {"error": "Result limit cannot be greater than 100", "hits": 0, "jobs": None}
355 items, artifact, asked, other = _amazon_search([error])
356 assert items == []
357 assert artifact["job_site_unreadable"] == "Amazon"
358 assert len(asked) == 1
359 # No careers page and no hosted-system slug was tried: only robots.txt
360 # files, asked for a job sitemap before the run says it cannot read the site.
361 assert all(url.endswith("/robots.txt") for url in other)
362 assert all(url.startswith("https://www.amazon.jobs/") for url, _offset in asked)
363
364
365 def test_amazon_page_that_fails_midway_keeps_the_rows_read():
366 items, artifact, _asked, _other = _amazon_search(AMAZON["pages"], fail_at=1)
367 assert len(items) == 3
368 assert artifact["board_cut_short"] is True
369 assert artifact["new_in_window"] is None
370 assert artifact["open_roles"] == 10000
371
372
373 # --- Apple --------------------------------------------------------------------
374
375 APPLE = json.loads((FIXTURES / "jobs_apple_search.json").read_text(encoding="utf-8"))
376 APPLE_DETAIL = json.loads((FIXTURES / "jobs_apple_detail.json").read_text(encoding="utf-8"))
377
378
379 def _apple_search(pages, *, detail=lambda url: copy.deepcopy(APPLE_DETAIL), window=("2026-10-15", "2026-11-14")):
380 posts, details = [], []
381
382 def post(url, body, **_kwargs):
383 posts.append(body["page"])
384 assert url == "https://jobs.apple.com/api/v1/search" and "format" in body
385 answer = pages.get(body["page"])
386 if isinstance(answer, Exception):
387 raise answer
388 if answer is None:
389 raise http.HTTPError("HTTP 404: Not Found", status_code=404)
390 return copy.deepcopy(answer)
391
392 others = _NoRequests()
393
394 def get(url, *args, **kwargs):
395 if not url.startswith("https://jobs.apple.com/api/v1/jobDetails/"):
396 return others(url, *args, **kwargs)
397 details.append(url)
398 answer = detail(url)
399 if answer is None:
400 raise http.HTTPError("HTTP 404: Not Found", status_code=404)
401 return answer
402
403 with patch.object(jobs.http, "post", side_effect=post), \
404 patch.object(jobs.http, "get_text", side_effect=others.text), \
405 patch.object(jobs.http, "get", side_effect=get):
406 items, artifact = jobs.search_jobs(
407 "Apple", window, {}, web_backend="none", site="https://www.apple.com/",
408 )
409 return items, artifact, posts, details, others.urls
410
411
412 def test_an_apple_page_parses_to_twenty_rows():
413 items, total = jobs.parse_apple_response(APPLE["corporate_page"])
414 assert total == 6459 and len(items) == 20
415 first = items[0]
416 assert first["title"].startswith("Senior Legal Counsel")
417 assert first["title"].endswith("Home and Wearables Product Counsel")
418 assert first["department"] == "Corporate Functions"
419 assert first["location"] == "Cupertino"
420 assert (first["date"], first["posted_date_true"]) == ("2026-11-14", True)
421 assert first["url"] == (
422 "https://jobs.apple.com/en-us/details/200689996/senior-legal-counsel-home-and-wearables-product-counsel"
423 )
424 assert first["detail_url"] == "https://jobs.apple.com/api/v1/jobDetails/200689996?locale=en-us"
425 assert not first["digest_excluded"]
426
427
428 def test_an_apple_role_listed_once_per_location_is_one_row_with_every_location():
429 rows = APPLE["corporate_page"]["res"]["searchResults"]
430 repeated = next(row["positionId"] for row in rows if [r["positionId"] for r in rows].count(row["positionId"]) > 1)
431 places = {loc["name"] for row in rows if row["positionId"] == repeated for loc in row["locations"]}
432 items, _artifact, _posts, _details, _others = _apple_search({1: APPLE["corporate_page"]})
433 merged = [item for item in items if f"/details/{repeated}/" in item["url"]]
434 assert len(merged) == 1 and set(merged[0]["offices"]) == places
435 # The digest shows every place, not only the first row's.
436 assert len(places) > 1
437 assert set(jobs_digest.distinct_roles(merged)[0]["locations"]) == places
438 assert len(items) == len({row["positionId"] for row in rows})
439
440
441 def test_apple_retail_pipeline_roles_are_counted_but_never_chosen():
442 items, total = jobs.parse_apple_response(APPLE["retail_page"])
443 assert len(items) == 20 and total == 6459
444 assert all(item["digest_excluded"] for item in items)
445 # A standing pipeline role carries the request's day, which is not when it was posted.
446 assert not any(item["posted_date_true"] for item in items)
447 _items, artifact, _posts, details, _others = _apple_search({1: APPLE["retail_page"]})
448 assert artifact["open_roles"] == 6459
449 assert artifact["digest"]["roles"] == [] and details == []
450
451
452 def test_an_apple_retail_role_story_search_finds_is_still_kept_out_of_the_digest():
453 retail = {item["url"] for item in jobs.parse_apple_response(APPLE["retail_page"])[0]}
454
455 def post(url, body, **_kwargs):
456 # The story search for the term answers with retail store roles only.
457 page = APPLE["retail_page"] if body["query"] else APPLE["corporate_page"]
458 return copy.deepcopy(page) if body["page"] == 1 else {"res": {"searchResults": [], "totalRecords": 6459}}
459
460 others = _NoRequests()
461 with patch.object(jobs.http, "post", side_effect=post), \
462 patch.object(jobs.http, "get_text", side_effect=others.text), \
463 patch.object(jobs.http, "get", side_effect=lambda url, *a, **k: copy.deepcopy(APPLE_DETAIL)):
464 _items, artifact = jobs.search_jobs(
465 "Apple", ("2026-10-15", "2026-11-14"), {"_jobs_story_terms": ["specialist"]},
466 web_backend="none", site="https://www.apple.com/",
467 )
468 roles = artifact["digest"]["roles"]
469 assert roles and not any(role["url"] in retail for role in roles)
470 assert not any(role.get("story_term") for role in roles)
471 assert artifact["story_search"]["ran"] is True and artifact["story_search"]["matches"] == 0
472
473
474 def test_apple_retail_by_team_name_is_excluded_and_a_pipe_row_has_no_true_date():
475 page = copy.deepcopy(APPLE["corporate_page"])
476 rows = page["res"]["searchResults"]
477 rows[0]["team"] = {"teamName": "Apple Retail", "teamCode": "RTLMY"}
478 rows[1].update({"type": "PIPE", "managedPipelineRole": False})
479 items, _total = jobs.parse_apple_response(page)
480 assert items[0]["digest_excluded"] is True
481 assert items[1]["posted_date_true"] is False and items[1]["digest_excluded"] is False
482
483
484 def test_apple_digest_holds_only_corporate_roles_with_their_full_text():
485 pages = {1: APPLE["retail_page"], 2: APPLE["corporate_page"], 3: APPLE["mixed_page"]}
486
487 def detail(url):
488 # Each role gets a sentence of its own, so it survives boilerplate removal.
489 position = url.split("/jobDetails/", 1)[1].split("?", 1)[0]
490 answer = copy.deepcopy(APPLE_DETAIL)
491 answer["res"]["description"] = f"Own the work of position {position}. " + answer["res"]["description"]
492 return answer
493
494 items, artifact, posts, details, others = _apple_search(pages, detail=detail)
495 assert {1, 2, 3} <= set(posts)
496 assert len(items) == 50
497 # The board's total counts rows, so its note counts the 60 rows read, not the 50 roles.
498 assert artifact["coverage_note"].startswith("board read in part: 60 rows read of the 6,459")
499 roles = artifact["digest"]["roles"]
500 by_url = {item["url"]: item for item in items}
501 assert roles and not any(by_url[role["url"]]["digest_excluded"] for role in roles)
502 assert sorted(details) == sorted(by_url[role["url"]]["detail_url"] for role in roles)
503 assert all("Own the work of position" in role["text"] for role in roles)
504 assert "role text fetched" not in (artifact["digest"].get("note") or "")
505 assert artifact["open_roles"] == 6459 and artifact["new_in_window"] is None
506 rendered = render.render_compact(_report(jobs=artifact))
507 assert "\n## Jobs Digest\n" in rendered
508 assert "💼 Jobs: 6,459 open roles" in rendered
509 assert others == []
510
511
512 def test_the_apple_detail_parser_keeps_description_and_qualifications_apart():
513 detail = jobs.parse_apple_detail(APPLE_DETAIL)
514 assert detail["description"].startswith("You will be responsible for advising")
515 assert detail["responsibilities"].startswith("Deep understanding of general privacy laws")
516 assert detail["minimumQualifications"].startswith("Knowledge of comprehensive privacy laws")
517 assert detail["preferredQualifications"].startswith("Experience providing strategic")
518 assert jobs.parse_apple_detail({"res": {"description": ""}}) is None
519 assert jobs.parse_apple_detail("<html>no data</html>") is None
520
521
522 def test_apple_answering_no_rows_against_a_total_is_the_cant_be_read_outcome():
523 empty = {"res": {"searchResults": [], "totalRecords": 6459}}
524 items, artifact, posts, _details, others = _apple_search({1: empty})
525 assert items == [] and posts == [1]
526 assert artifact["job_site_unreadable"] == "Apple"
527 assert all(url.endswith("/robots.txt") for url in others)
528
529
530 def test_an_apple_detail_that_fails_keeps_its_summary_and_is_counted():
531 first_failed = []
532
533 def detail(url):
534 if not first_failed:
535 first_failed.append(url)
536 return None
537 return copy.deepcopy(APPLE_DETAIL)
538
539 _items, artifact, _posts, _details, _others = _apple_search(
540 {1: APPLE["corporate_page"]}, detail=detail,
541 )
542 selected = len(artifact["digest"]["roles"])
543 assert f"role text fetched for {selected - 1} of {selected} selected roles" in artifact["digest"]["note"]
544
545
546 def test_a_company_board_that_does_not_answer_is_a_retryable_timeout_not_unreadable():
547 timeout = http.HTTPError("timed out", outcome_state=http.health.TIMEOUT)
548 items, artifact, _posts, details, others = _apple_search({1: timeout})
549 assert items == [] and details == [] and others == []
550 assert "job_site_unreadable" not in artifact
551 assert artifact["_source_outcome"]["state"] == http.health.TIMEOUT
552 assert "the apple board jobs.apple.com did not answer" in artifact["_source_outcome"]["detail"]
553 assert "can't be read automatically" not in render.render_compact(_report(jobs=artifact))
554
555
556 def test_a_slow_apple_page_ends_that_call_and_keeps_the_rows_read():
557 timeout = http.HTTPError("timed out", outcome_state=http.health.TIMEOUT)
558 items, artifact, _posts, _details, _others = _apple_search(
559 {1: APPLE["corporate_page"], 2: timeout},
560 )
561 # The page's 20 rows are 15 roles.
562 assert len(items) == 15
563 assert artifact["board_cut_short"] is True
564 assert artifact["open_roles"] == 6459
565
566
567 # --- Eightfold (Microsoft, Qualcomm, Netflix) ----------------------------------
568
569 PCSX = json.loads((FIXTURES / "jobs_eightfold_pcsx.json").read_text(encoding="utf-8"))
570 V2 = json.loads((FIXTURES / "jobs_eightfold_v2.json").read_text(encoding="utf-8"))
571 # What detection reads off each careers site (no registry row any more).
572 MICROSOFT = {"name": "Microsoft", "provider": "eightfold", "board": "apply.careers.microsoft.com",
573 "domain": "microsoft.com", "api": "pcsx"}
574 NETFLIX = {"name": "Netflix", "provider": "eightfold", "board": "explore.jobs.netflix.net",
575 "domain": "netflix.com", "api": "v2"}
576 # Recorded shapes of the pages detection follows: Microsoft's careers host
577 # points at its Eightfold board by name; Netflix's jobs page links a jobs
578 # host on its other domain; both Eightfold pages state their group id.
579 _MICROSOFT_LANDING = (
580 '<html><body><div id="careers-eightFoldCareerUrl" hidden>'
581 "https://apply.careers.microsoft.com/careers</div>"
582 "<p>Join our team. Open positions.</p></body></html>"
583 )
584 _NETFLIX_LANDING = (
585 '<html><body><a href="https://explore.jobs.netflix.net/careers">See open roles</a>'
586 "<p>Join our team.</p></body></html>"
587 )
588
589
590 def _eightfold_page_html(group):
591 return (
592 '<html><head><link href="https://static.vscdn.net/fonts/css/eightfold-font-base.css">'
593 f'<script>window._EF_GROUP_ID = "{group}";</script></head><body></body></html>'
594 )
595
596
597 _EIGHTFOLD_PAGES = {
598 "https://careers.microsoft.com/": _MICROSOFT_LANDING,
599 "https://apply.careers.microsoft.com/careers": _eightfold_page_html("microsoft.com"),
600 "https://www.netflix.com/jobs": _NETFLIX_LANDING,
601 "https://explore.jobs.netflix.net/careers": _eightfold_page_html("netflix.com"),
602 }
603
604
605 def _eightfold_page(fixture, start, *, pcsx, total=None):
606 """The fixture's listing page with ids moved by ``start`` so every page differs."""
607 answer = copy.deepcopy(fixture["page"])
608 body = answer["data"] if pcsx else answer
609 for position in body["positions"]:
610 position["id"] = int(position["id"]) + start
611 if pcsx:
612 position["positionUrl"] = f"/careers/job/{position['id']}"
613 else:
614 position["canonicalPositionUrl"] = f"https://explore.jobs.netflix.net/careers/job/{position['id']}"
615 if total is not None:
616 body["count"] = total
617 if start >= body["count"]:
618 body["positions"] = []
619 return answer
620
621
622 def _eightfold_search(company, site, fixture, *, pcsx, total=None, status=None):
623 listed, details = [], []
624
625 def get(url, params=None, **_kwargs):
626 if "/api/pcsx/search" in url or url.endswith("/api/apply/v2/jobs"):
627 listed.append((url, dict(params or {})))
628 if status is not None:
629 raise http.HTTPError(f"HTTP {status}", status_code=status)
630 return _eightfold_page(fixture, int(params["start"]), pcsx=pcsx, total=total)
631 if "/api/pcsx/position_details" in url or "/api/apply/v2/jobs/" in url:
632 details.append(url)
633 # Each role gets a sentence of its own, so it survives boilerplate removal.
634 answer = copy.deepcopy(fixture["detail"])
635 body = answer["data"] if pcsx else answer
636 key = "jobDescription" if pcsx else "job_description"
637 body[key] = f"<p>Own the work behind {url.split('jobs/')[-1]}.</p>" + body[key]
638 return answer
639 raise http.HTTPError("HTTP 404: Not Found", status_code=404)
640
641 texts = _NoRequests()
642
643 def page_text(url, *args, **kwargs):
644 if url in _EIGHTFOLD_PAGES:
645 return _EIGHTFOLD_PAGES[url]
646 return texts.text(url, *args, **kwargs)
647
648 with patch.object(jobs.http, "get", side_effect=get), \
649 patch.object(jobs.http, "get_text", side_effect=page_text), \
650 patch.object(jobs.http, "post", side_effect=texts):
651 items, artifact = jobs.search_jobs(company, WINDOW, {}, web_backend="none", site=site)
652 return items, artifact, listed, details, [
653 url for url in texts.urls if not url.endswith("/robots.txt")
654 ]
655
656
657 def test_a_pcsx_page_parses_to_rows_with_a_public_url():
658 items, total = jobs.parse_eightfold_response(PCSX["page"], MICROSOFT)
659 assert total == 2392 and len(items) == 10
660 first = items[0]
661 assert first["title"] == "Technical Program Manager II - FD&E"
662 assert first["department"] == "Technical Program Management"
663 assert first["location"] == "United States, Washington, Redmond"
664 assert first["url"] == "https://apply.careers.microsoft.com/careers/job/1970393557041639"
665 assert first["id"] == "EF1970393557041639" and first["provider"] == "eightfold"
666 assert first["detail_url"].startswith(
667 "https://apply.careers.microsoft.com/api/pcsx/position_details?position_id=1970393557041639&domain=microsoft.com"
668 )
669
670
671 def test_a_v2_page_parses_the_same_fields_from_its_own_names():
672 items, total = jobs.parse_eightfold_response(V2["page"], NETFLIX)
673 assert total == 418 and len(items) == 10
674 first = items[0]
675 assert first["title"] == "AI Engineer 6 - AI Foundation & Tooling, Ads Platform"
676 assert first["department"] == "Data & Insights"
677 assert first["location"] == "Los Gatos,California,United States of America"
678 assert first["url"] == "https://explore.jobs.netflix.net/careers/job/790298014263"
679 assert first["detail_url"] == "https://explore.jobs.netflix.net/api/apply/v2/jobs/790298014263?domain=netflix.com"
680
681
682 def test_no_eightfold_row_claims_a_true_posted_date():
683 rows = (jobs.parse_eightfold_response(PCSX["page"], MICROSOFT)[0]
684 + jobs.parse_eightfold_response(V2["page"], NETFLIX)[0])
685 assert rows and not any(row["posted_date_true"] or row["date"] for row in rows)
686
687
688 def test_a_403_on_both_api_generations_is_the_cant_be_read_outcome():
689 items, artifact, listed, details, _other = _eightfold_search(
690 "Microsoft", "https://www.microsoft.com/", PCSX, pcsx=True, status=403,
691 )
692 assert items == [] and artifact["job_site_unreadable"] == "Microsoft"
693 # A detected board does not say its generation: pcsx is asked, then v2.
694 assert [url.rsplit("/api/", 1)[1] for url, _params in listed] == ["pcsx/search", "apply/v2/jobs"]
695 assert details == []
696
697
698 def test_a_large_eightfold_board_is_read_to_its_ceiling_and_prints_the_reported_total():
699 items, artifact, listed, details, other = _eightfold_search(
700 "Microsoft", "https://www.microsoft.com/", PCSX, pcsx=True,
701 )
702 assert len(items) == jobs.EIGHTFOLD_ROW_CEILING == 400
703 # Only the careers pages detection read before the board was found.
704 assert len(listed) == 40
705 assert other == ["https://www.microsoft.com/careers", "https://www.microsoft.com/jobs"]
706 assert all(params["domain"] == "microsoft.com" and params["sort_by"] == "timestamp"
707 for _url, params in listed)
708 assert artifact["open_roles"] == 2392 and artifact["new_in_window"] is None
709 rendered = render.render_compact(_report(jobs=artifact))
710 assert "💼 Jobs: 2,392 open roles" in rendered
711 assert "new in the L30" not in rendered.split("💼 Jobs:", 1)[1].split("\n", 1)[0]
712
713
714 def test_eightfold_role_text_is_requested_only_for_digest_selected_roles():
715 items, artifact, _listed, details, _other = _eightfold_search(
716 "Microsoft", "https://www.microsoft.com/", PCSX, pcsx=True,
717 )
718 roles = artifact["digest"]["roles"]
719 assert roles and len(details) == len(roles) < len(items)
720 by_url = {item["url"]: item for item in items}
721 assert {by_url[role["url"]]["detail_url"] for role in roles} == set(details)
722 assert all("Own the work behind" in role["text"] for role in roles)
723
724
725 @pytest.mark.parametrize(
726 "company, site, fixture, pcsx",
727 [("Microsoft", "https://www.microsoft.com/", PCSX, True),
728 ("Netflix", "https://www.netflix.com/", V2, False)],
729 )
730 def test_microsoft_and_netflix_runs_print_a_digest(company, site, fixture, pcsx):
731 _items, artifact, _listed, _details, _other = _eightfold_search(company, site, fixture, pcsx=pcsx)
732 rendered = render.render_compact(_report(jobs=artifact))
733 assert "\n## Jobs Digest\n" in rendered
734 assert "role text fetched" not in (artifact["digest"].get("note") or "")
735
736
737 def test_a_place_several_merged_roles_share_is_not_a_rare_location():
738 def role(n, places):
739 return {
740 "title": "Engineer", "department": "Hardware", "url": f"https://example.com/{n}",
741 "description": f"text {n}", "location": places[0], "locations": places,
742 }
743
744 # Cupertino is one role's first place and an extra place of three others.
745 shared = [role(0, ["Cupertino"])] + [role(n, ["Austin", "Cupertino"]) for n in (1, 2, 3)]
746 rare = role(4, ["Austin", "Reno"])
747
748 chosen = jobs_digest.select_roles([*shared, rare], limit=1)
749
750 assert [picked["item"]["url"] for picked in chosen] == ["https://example.com/4"]
751
751 lines PYTHON