From 85bfe62fec8b538f43ff0f13b8987677d6ed9d20 Mon Sep 17 00:00:00 2001 From: Wolf Date: Tue, 29 Sep 2026 20:11:18 +0200 Subject: [PATCH] Read Eightfold career sites through the PCSX search Co-Authored-By: Claude Sonnet 5.5 --- plugins/atshosts/eightfold.py | 169 ++++++++++++++++++++ tests/fixtures/ats/eightfold-detail.json | 41 +++++ tests/fixtures/ats/eightfold.json | 145 +++++++++++++++++ tests/test_ats_eightfold.py | 195 +++++++++++++++++++++++ 4 files changed, 550 insertions(+) create mode 100644 plugins/atshosts/eightfold.py create mode 100644 tests/fixtures/ats/eightfold-detail.json create mode 100644 tests/fixtures/ats/eightfold.json create mode 100644 tests/test_ats_eightfold.py diff --git a/plugins/atshosts/eightfold.py b/plugins/atshosts/eightfold.py new file mode 100644 index 0000000..de23555 --- /dev/null +++ b/plugins/atshosts/eightfold.py @@ -0,0 +1,169 @@ +"""Eightfold: `eightfold:/`, for example +`eightfold:infineon.eightfold.ai/infineon.com` or, for a career site on the +company's own host, `eightfold:jobs.ericsson.com/ericsson.com`. The public +PCSX search, paged by offset at ten roles a page with the total stated, and a +role's text on its own request. + +Written from Ericsson's site on 2026-09-29 (637 roles), with Infineon's and +Microsoft's read the same day in the findings. Unverified on a tenant other +than those three: that the search takes the same parameters and answers with +the same fields. + +The `domain` is the tenant's own name for the company, usually the company's +domain, and it is not the host: the site's page carries it as `domain=` in its +links. `/api/apply/v2/jobs` answers 403 "Not authorized for PCSX" on the sites +tried, so it is not used. + +The search ignores `num` and answers ten roles a page, so a board costs one +request per ten roles, and `ats.MAX_PAGES` (100) stops a read at 1,000 roles: a +larger board (Infineon's 1,292, Microsoft's 2,319) is read incomplete every pull, +and an incomplete read never closes the roles it did not list. The rows are +sorted newest first (`sort_by=timestamp`) so that what the cap keeps is the +newest thousand and the pages do not shuffle between two requests, unlike the +default order, which puts hot roles first. The search does take a `location` +free text (Ericsson's "Sweden" found 157 of 637), which could bring a read +under the cap, but a target names no filter and none is built here. + +Discovery names Eightfold from an `eightfold.ai` link, and the host and the +domain from one that carries `domain=`. +""" + +from __future__ import annotations + +import html +import json +import re +from collections.abc import Callable +from typing import Any + +from desk.sources import strip_html + +from ._shared import Get, Page, Row, is_web_url, only, parse_dt + +NAME = "eightfold" +LABEL = "Eightfold" +PATTERNS = ( + # Both parts, from a link to a tenant's site that says its domain. + r"https?://([a-z0-9-]+\.eightfold\.ai)/[^\s\"'<>]*?[?&]domain=([a-z0-9.-]+\.[a-z]{2,})", + # No slug: a link to a tenant's site that does not. + r"[a-z0-9-]+\.eightfold\.ai", +) + +#: A whole host name: two labels or more, the last one letters, so neither an +#: address, a bare word nor a port names a site. `ats._get` refuses every host +#: but the tenant's, redirects included. +_NAME = re.compile(r"[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*\.[a-z]{2,}") + +#: Names a private network uses, never a company's career site. +_LOCAL = (".localhost", ".local", ".internal", ".lan", ".home.arpa") + +#: `workLocationOption` -> `store._remote`'s words. Only "onsite" and "hybrid" +#: were seen; the other spellings are the obvious ones. +_REMOTE = {"onsite": "onsite", "on_site": "onsite", "hybrid": "hybrid", "remote": "remote"} + + +def parts(slug: str) -> tuple[str, str]: + """`(host, domain)` of a slug, lowercased.""" + host, _, domain = slug.lower().partition("/") + return host, domain + + +def _name_ok(name: str) -> bool: + return bool(_NAME.fullmatch(name)) and not name.endswith(_LOCAL) + + +def slug_ok(slug: str) -> bool: + host, sep, domain = slug.lower().partition("/") + return bool(sep) and _name_ok(host) and _name_ok(domain) + + +def allowed(slug: str) -> Callable[[str], bool]: + return only(parts(slug)[0]) + + +def careers_url(slug: str) -> str: + return f"https://{parts(slug)[0]}/careers" + + +def robots_page(slug: str) -> str: + return careers_url(slug) + + +def page(get: Get, slug: str, cursor: Any) -> Page: + """One page of `/api/pcsx/search` -> `{"status": 200, "data": {"positions": + [...], "count": n}}`; the next starts at the offset after this page's + positions, and an empty page ends the read.""" + host, domain = parts(slug) + start = int(cursor or 0) + answer = json.loads(get(f"https://{host}/api/pcsx/search?domain={domain}" + f"&sort_by=timestamp&start={start}")) + data = answer.get("data") if isinstance(answer, dict) else None + positions = data.get("positions") if isinstance(data, dict) else None + if not isinstance(positions, list): + raise ValueError("not an Eightfold search answer: no data.positions" + + (f" (status {answer.get('status')})" if isinstance(answer, dict) else "")) + count = data.get("count") + results = [{"id": str(p.get("id") or "")} for p in positions] + return (positions, results, count if isinstance(count, int) else None, + start + len(positions) if positions else None) + + +def _place(locations: Any) -> str: + """The role's places, "; " apart. Eightfold writes each as "city,region, + country" with no space and repeats the name when a city is its own region + ("Mexico City,Mexico City,Mexico"), so the repeats go.""" + out: list[str] = [] + for loc in locations if isinstance(locations, list) else []: + names: list[str] = [] + for name in str(loc).split(","): + name = name.strip() + if name and name not in names: + names.append(name) + if names and ", ".join(names) not in out: + out.append(", ".join(names)) + return "; ".join(out) + + +def rows(positions: list[dict[str, Any]], slug: str) -> list[Row]: + """A position has `id` (a number, kept as a string), `displayJobId`, + `name`, `locations`, `postedTs` (epoch seconds), `department`, + `workLocationOption` and `positionUrl`, the path of the role's page on the + tenant's host. The list has no text, and no pay is stated anywhere.""" + host = parts(slug)[0] + out = [] + for p in positions: + title = (p.get("name") or "").strip() + source_id = str(p.get("id") or "") + path = str(p.get("positionUrl") or "").strip() + url = f"https://{host}{path}" if path.startswith("/") and path[1:2] != "/" else "" + if not title or not source_id or not is_web_url(url): + continue + out.append({ + "source_id": source_id, + "title": title, + "location": _place(p.get("locations") or p.get("standardizedLocations")), + "url": url, + "posted": parse_dt(p.get("postedTs")), + "department": str(p.get("department") or "").strip(), + "description": "", + "remote": _REMOTE.get(str(p.get("workLocationOption") or "").strip().lower()), + "salary_text": "", + }) + return out + + +def detail(get: Get, slug: str, row: Row) -> dict[str, Any]: + """`/api/pcsx/position_details` of the role -> `data.jobDescription`, the + HTML text of the ad. The same answer repeats the listing's fields, and + `publicUrl`, none of which is needed.""" + host, domain = parts(slug) + role = str(row["source_id"]) + if not role.isdigit(): + raise ValueError(f"not an Eightfold position id: {role!r}") + answer = json.loads(get(f"https://{host}/api/pcsx/position_details" + f"?position_id={role}&domain={domain}&hl=en")) + data = answer.get("data") if isinstance(answer, dict) else None + if not isinstance(data, dict) or "jobDescription" not in data: + raise ValueError("not an Eightfold position: no data.jobDescription") + text = html.unescape(strip_html(data["jobDescription"] or "")) + return {"description": " ".join(text.split())} diff --git a/tests/fixtures/ats/eightfold-detail.json b/tests/fixtures/ats/eightfold-detail.json new file mode 100644 index 0000000..c9d3f44 --- /dev/null +++ b/tests/fixtures/ats/eightfold-detail.json @@ -0,0 +1,41 @@ +{ + "status": 200, + "error": { + "message": "", + "body": "" + }, + "data": { + "id": 563121777283313, + "displayJobId": "791521", + "name": "Sr. Demand and S&OP Manager", + "locations": [ + "Plano,Texas,United States", + "Boise,Idaho,United States" + ], + "standardizedLocations": [ + "Plano, TX, US", + "Boise, ID, US" + ], + "postedTs": 1790365020, + "stars": 0, + "department": "83 Supply & Logistics", + "creationTs": 1789917546, + "jobDescription": "

Join our Team

\r

About this opportunity:

 

  • Job Locations: Plano, TX or Boise, ID
  • Ericsson Enterprise Wireless Solutions Inc. does not sponsor U.S work authorizations for this job positionincluding U.S. immigration filings for initial and/or change of employer paperwork for H-1’s, H-1B1’s, E-3’s, O-1’s, and TN’s. Ericsson also does not hire F-1’s working on CPT or EAD for this position. 

 

Ericsson Enterprise Wireless Solutions is a team of authentic, hard-working, and innovative peopledriven by a shared vision to Connect Beyond the limits of wired networks. We help customers —big and small, across industries and around the world — utilize LTE and 5G cellular technology toconnect people, places, and things, anywhere. We’re at the forefront of the Wireless WAN and 5G —the next big waves in networking — and we remain as hungry and humble as the day we started. Ifyou’re hungry to be part of something big, come join us. 

 

How Will You Contribute to the Company? 

The Sr. Demand Architect is responsible for creating an accurate and achievable collaborativeconsensus plan in close partnership with Sales, Product Management, and Finance. This keyposition must be able to facilitate and drive results in a fast-paced and demanding growthenvironment, leveraging his/her strong interpersonal and leadership skills. Additionally, theDemand Planner plays a critical role in the monthly S&OP process and will be the key resource forall demand-related issues. This role will be challenged to continue the development of bestpractices and standardized processes.

What you will do

\r

Forecasting

  • Manage demand planning and forecasting for purchasing to ensure an uninterrupted supply ofproducts for global customers
  • Partner with Sales and Marketing to understand historical sales, market trends, seasonality,product mix, sales events, marketing promotions, and other factors which influence theforecast
  • Manage key stakeholders by communicating realistic and accurate demand plans based onstatistical modeling
  • Drive consensus between cross-functional groups and leaders.
  • Effectively identify demand patterns, changes in trend, and drivers of product demand
  • Develop and drive continuous improvements to forecasting models, demand forecastingtechniques, and methods by performing root-cause analysis
  • Successfully identify risks and opportunities in the demand plan, escalates and communicatesappropriately
  • Work with Supply Planning and Sales stakeholders to shape demand and optimize businessperformance
  • Provide quantitative analysis that drives forecast and volatility improvements across thebusiness
  • Facilitate regular reviews of forecast accuracy results across the business
  • Effectively adapt communication of data, insights, statistical modeling, and market trends tovarious audiences
  • Utilize best practices in technology and processes to enable an effective demand planningfunction 

S&OP

\r
  • Manage the global S&OP demand process for all products in collaboration with Sales, Finance &Supply Chain
  • Collaborate across the organization to ensure that the appropriate data is available andaccurate to be reviewed at the S&OP process meetings
  • Prepare all data and metrics for demand-related S&OP meetings and reviews. Identify gapsand scenarios that will be presented. Guide final decision-making on open items includingtrade-offs and risk mitigation proposals
  • Provide ad hoc analysis to support decision-making by Supply Chain, Operations, Finance,Sales, Marketing, and Executive leadership 

NPI

  • SKU level demand planning to incorporate weekly and monthly reporting of key performanceindicators for the product transitions by collaborating with Product Management, Engineering,and Supply Planning leadership
  • Collaborate with cross-functional teams, and monitor progress of product milestones for on-time completion. Drive continuous improvement in processes
  • Develop internal tools to make SKU transition demand planning models sustainable andscalable
  • Manage the analysis of hardware lifecycle information to create a HW ramp up/ramp down planto optimize inventory & fulfill customer requirements
  • Support the analysis for Excess & Obsolete inventory, root causes, and process improvements 

 

Business Process 

  • Will play a key role in identifying, implementing, and integrating systems, solutions, andprocesses to improve business and operational processes, reduce costs, improve businessKPIs, and achieve organizational targets
  • Proficient at creating and analyzing business information and defining key businessresults/metrics with a proficiency in data tools such as Excel, SFDC, and Tableau
  • Document and share best practice methods, processes, and ideas across the business's supplychain operations to drive continuous improvements in all aspects of business operations

The skills you bring

\r
  • Bachelor’s Degree in Industrial Engineering, Supply Chain or related experience
  • 5+ years professional experience in statistical forecasting and consensus demand planning
  • 5+ years’ experience leading S&OP process
  • 2+ years of experience in data analytics and implementing AI soluition across supply chain functions
  • In-depth knowledge of the components of Demand Management and how forecasting, supply planning, demand analysis, and sales and operations work cohesively and successfully
  • Excellent communication (verbal and written) and interpersonal skills with an ability toeffectively communicate with both business and technical teams
  • Proficient at leveraging statistical forecasting methodologies to derive accurate and consistentdemand forecasts, understanding when to deviate based on market inputs
  • Entrepreneurial spirit and drive to create and build tools, processes and standardize acrossbusiness functions
  • Demand planning prowess, significant experience challenging the status quo, uncoveringhidden trends, and highlighting risk areas 

Why join Ericsson?

At Ericsson, you´ll have an outstanding opportunity. The chance to use your skills and imagination to push the boundaries of what´s possible. To build solutions never seen before to some of the world’s toughest problems. You´ll be challenged, but you won’t be alone. You´ll be joining a team of diverse innovators, all driven to go beyond the status quo to craft what comes next.

 

What happens once you apply?
Click Here to find all you need to know about what our typical hiring process looks like.

 

Ericsson uses a merit-based hiring approach that values people with different experiences, perspectives and skillsets. We truly believe this approach drives innovation, which is essential for our future growth. We encourage people from all backgrounds to apply and realize their full potential as part of our Ericsson team.  Ericsson is proud to be an Equal Opportunity employer, learn more.

 

If you need assistance or to request an accommodation due to a disability, please contact Ericsson at hr.direct.americas@ericsson.com. 

 

DISCLAIMER: The above statements are intended to describe the general nature and level of work being performed by employees in this position. They are not an exhaustive list of all responsibilities, duties and skills required for this position, and you may be required to perform additional job tasks as assigned.

 

Primary country and city: United States (US) || Boise (ID) (Country/ City)

 

Job details: Supply Chain Planner

 

Compensation and Benefits at Ericsson
At Ericsson, we know that our people are the key to our success. We offer a competitive package to help with your individual needs and goals.

 

Your Pay
The salary range for this position is dependent on various factors including, but not limited to, location, and the candidate’s combination of job-related knowledge, qualifications, skills, education, training, and experience.

 

Short-Term Variable Compensation Plan : Your pay also includes the opportunity for an annual bonus. Actual bonus payouts are based on performance of the business against the unit’s objectives, individual performance, and the individual bonus target. Certain eligibility and pro-ration rules apply.  

 

Your Health 
Ericsson Enterprise Wireless Solutions offers excellent, competitive employee benefits, such as: subsidized, nationwide PPO medical benefit options including a low-deductible Point of Service Plan and a qualifying High Deductible Health Plan (HDHP), with a generous company-provided HSA contribution. For California employees, we offer a subsidized HMO option through Kaiser. Ericsson Enterprise Wireless Solutions also offers subsidized dental and vision coverage. 

 

Your Financial Security 
We invest in both your short and long-term financial wellbeing. Our 401(k) plan has a 4% company match and immediate vesting. Employees will also receive company-paid employee basic life and AD&D insurance and company-paid disability benefits. 

 

Your Time 
Your work-life balance is important to us. New employees are provided a minimum of 15 days of accrued vacation, up to 3 personal days per year, 11 annual holidays, 8 hours of volunteer time, and 80 hours of sick time annually. Please note paid time off is pro-rated based on the employee’s start date. Furthermore, Ericsson provides up to 16 weeks of paid maternity leave and 6 weeks of parental or adoption leave at 100% of pay.

 

Additional Benefits 
Ericsson Enterprise Wireless Solutions offers other company-paid benefits such as a comprehensive Employee Assistance Program, mobile therapy, and volunteer paid time off. 

", + "location": "Plano,Texas,United States", + "isHot": 1, + "workLocationOption": "onsite", + "locationFlexibility": null, + "atsJobId": "791521", + "positionUrl": "/careers/job/563121777283313", + "publicUrl": "https://jobs.ericsson.com/careers/job/563121777283313", + "jdHighlight": [], + "positionUserActions": { + "isSaved": false, + "applyAction": { + "status": "link_off", + "applyUrl": "https://career2.successfactors.eu/career?company=Ericsson&career_ns=job_application&src=Eightfold&career_job_req_id=791521" + } + } + }, + "metadata": null +} \ No newline at end of file diff --git a/tests/fixtures/ats/eightfold.json b/tests/fixtures/ats/eightfold.json new file mode 100644 index 0000000..9c17361 --- /dev/null +++ b/tests/fixtures/ats/eightfold.json @@ -0,0 +1,145 @@ +{ + "status": 200, + "error": { + "message": "", + "body": "" + }, + "data": { + "positions": [ + { + "id": 563121777024688, + "displayJobId": "788936", + "name": "Systems Architect - RAN Semantic Data", + "locations": [ + "Stockholm,Stockholm,Sweden" + ], + "standardizedLocations": [ + "Stockholm, Stockholm County, SE" + ], + "postedTs": 1790703782, + "solrScore": null, + "stars": 0, + "department": "76 Product Development", + "creationTs": 1785822052, + "isHot": 0, + "workLocationOption": "onsite", + "locationFlexibility": null, + "atsJobId": "788936", + "positionUrl": "/careers/job/563121777024688", + "efcustomTextJobfuntionAdvancefilterpcs": [ + "Product Development" + ] + }, + { + "id": 563121777269700, + "displayJobId": "791400", + "name": "Director of Operations Excellence", + "locations": [ + "Mexico City,Mexico City,Mexico" + ], + "standardizedLocations": [ + "México D.F., CDMX, MX" + ], + "postedTs": 1790703449, + "solrScore": null, + "stars": 0, + "department": "82 Service Delivery", + "creationTs": 1789700838, + "isHot": 0, + "workLocationOption": "onsite", + "locationFlexibility": null, + "atsJobId": "791400", + "positionUrl": "/careers/job/563121777269700", + "efcustomTextJobfuntionAdvancefilterpcs": [ + "Service Delivery" + ] + }, + { + "id": 563121776511927, + "displayJobId": "786802", + "name": "SMA Production Quality Engineer", + "locations": [ + "Lewisville,Texas,United States" + ], + "standardizedLocations": [ + "Lewisville, TX, US" + ], + "postedTs": 1790701576, + "solrScore": null, + "stars": 0, + "department": "83 Supply & Logistics", + "creationTs": 1781768740, + "isHot": 0, + "workLocationOption": "onsite", + "locationFlexibility": null, + "atsJobId": "786802", + "positionUrl": "/careers/job/563121776511927", + "efcustomTextJobfuntionAdvancefilterpcs": [ + "Supply & Logistics" + ] + }, + { + "id": 563121776553428, + "displayJobId": "786911", + "name": "Product Quality Leader", + "locations": [ + "Lewisville,Texas,United States" + ], + "standardizedLocations": [ + "Lewisville, TX, US" + ], + "postedTs": 1790701145, + "solrScore": null, + "stars": 0, + "department": "83 Supply & Logistics", + "creationTs": 1782032961, + "isHot": 0, + "workLocationOption": "onsite", + "locationFlexibility": "flexible_within_country", + "atsJobId": "786911", + "positionUrl": "/careers/job/563121776553428", + "efcustomTextJobfuntionAdvancefilterpcs": [ + "Supply & Logistics" + ] + }, + { + "id": 563121776667313, + "displayJobId": "787350", + "name": "PMO Intern", + "locations": [ + "Tecnoparque,Mexico City,Mexico", + "Santa Fe,Mexico City,Mexico", + "Mexico City,Mexico City,Mexico", + "Tlalnepantla,Estado de México,Mexico" + ], + "standardizedLocations": [ + "México D.F., CDMX, MX", + "México D.F., CDMX, MX", + "México D.F., CDMX, MX", + "Tlalnepantla de Baz, Méx., MX" + ], + "postedTs": 1790699151, + "solrScore": null, + "stars": 0, + "department": "82 Service Delivery", + "creationTs": 1782910047, + "isHot": 0, + "workLocationOption": "onsite", + "locationFlexibility": null, + "atsJobId": "787350", + "positionUrl": "/careers/job/563121776667313", + "efcustomTextJobfuntionAdvancefilterpcs": [ + "Service Delivery" + ] + } + ], + "count": 637, + "sortBy": "timestamp", + "appliedFilters": {}, + "resultsMetaData": { + "usedFuzzSearch": false, + "mocTitle": null + } + }, + "metadata": null +} \ No newline at end of file diff --git a/tests/test_ats_eightfold.py b/tests/test_ats_eightfold.py new file mode 100644 index 0000000..398639a --- /dev/null +++ b/tests/test_ats_eightfold.py @@ -0,0 +1,195 @@ +"""The Eightfold host module against a saved page of Ericsson's search (five +of its roles) and one saved role answer. No network.""" + +from __future__ import annotations + +import json +import sys +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import httpx +import pytest + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from app.jobs import discover # noqa: E402 +from plugins import ats, atshosts # noqa: E402 +from plugins.atshosts import eightfold # noqa: E402 + +FIXTURES = ROOT / "tests" / "fixtures" / "ats" +SLUG = "jobs.ericsson.com/ericsson.com" + + +def _saved() -> dict[str, Any]: + return json.loads((FIXTURES / "eightfold.json").read_text()) + + +def _position(n: int) -> dict[str, Any]: + return {"id": 5000 + n, "displayJobId": str(n), "name": f"Role {n}", + "locations": ["Lund,Skane,Sweden"], "postedTs": 1790000000 - n, + "department": "76 Product Development", "workLocationOption": "hybrid", + "positionUrl": f"/careers/job/{5000 + n}"} + + +def _search(total: int, seen: list[str] | None = None) -> httpx.MockTransport: + """A search that ignores `num` and answers ten roles from `start`.""" + def handler(request: httpx.Request) -> httpx.Response: + if seen is not None: + seen.append(str(request.url)) + start = int(request.url.params["start"]) + positions = [_position(n) for n in range(start, min(start + 10, total))] + return httpx.Response(200, json={"status": 200, "data": { + "positions": positions, "count": total}}) + return httpx.MockTransport(handler) + + +def test_a_page_becomes_rows() -> None: + rows = eightfold.rows(_saved()["data"]["positions"], SLUG) + assert len(rows) == 5 + first, mexico, many = rows[0], rows[1], rows[4] + assert first["source_id"] == "563121777024688" + assert first["title"] == "Systems Architect - RAN Semantic Data" + assert first["url"] == "https://jobs.ericsson.com/careers/job/563121777024688" + assert first["location"] == "Stockholm, Sweden" # the city is its own region + assert first["department"] == "76 Product Development" + assert first["posted"] == datetime.fromtimestamp(1790703782, tz=UTC) + assert first["remote"] == "onsite" and (first["description"], first["salary_text"]) == ("", "") + assert mexico["location"] == "Mexico City, Mexico" + assert many["location"] == ("Tecnoparque, Mexico City, Mexico; Santa Fe, Mexico City, Mexico; " + "Mexico City, Mexico; Tlalnepantla, Estado de México, Mexico") + + +@pytest.mark.parametrize(("option", "remote"), [ + ("onsite", "onsite"), ("hybrid", "hybrid"), ("remote", "remote"), (None, None), ("odd", None)]) +def test_the_work_location_option_maps_to_the_remote_words( + option: str | None, remote: str | None) -> None: + assert eightfold.rows([_position(1) | {"workLocationOption": option}], SLUG)[0]["remote"] == remote + + +def test_a_position_without_a_name_an_id_or_a_path_is_left_out() -> None: + bad = [_position(1) | {"name": " "}, _position(2) | {"id": None}, + _position(3) | {"positionUrl": ""}, _position(4) | {"positionUrl": "//evil.example/x"}] + assert eightfold.rows(bad, SLUG) == [] + + +def test_the_standardized_location_stands_in_when_there_is_no_raw_one() -> None: + row = eightfold.rows([_position(1) | {"locations": [], "standardizedLocations": ["Lund, SE"]}], + SLUG)[0] + assert row["location"] == "Lund, SE" + + +def test_a_page_asks_for_the_newest_first_from_its_offset() -> None: + asked: list[str] = [] + + def get(url: str, **_: Any) -> bytes: + asked.append(url) + return json.dumps(_saved()).encode() + + decoded, results, total, cursor = eightfold.page(get, SLUG, None) + assert asked == ["https://jobs.ericsson.com/api/pcsx/search?domain=ericsson.com" + "&sort_by=timestamp&start=0"] + assert (len(decoded), len(results), total, cursor) == (5, 5, 637, 5) + assert eightfold.page(get, SLUG, 630)[3] == 635 + assert asked[-1].endswith("&start=630") + + +def test_a_board_is_read_ten_at_a_time_to_its_total(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(ats, "PAGE_DELAY", 0) + seen: list[str] = [] + with httpx.Client(transport=_search(25, seen)) as client: + rows, complete = ats._fetch_rows(client, f"eightfold:{SLUG}") + assert (len(rows), complete) == (25, True) + assert [u.rsplit("=", 1)[1] for u in seen] == ["0", "10", "20"] + + +def test_a_board_over_the_page_cap_is_incomplete(monkeypatch: pytest.MonkeyPatch) -> None: + """The cap is 100 pages of ten: a board of 1,292 (Infineon's) or 2,319 + (Microsoft's) is read as its first thousand and never as the whole.""" + monkeypatch.setattr(ats, "PAGE_DELAY", 0) + seen: list[str] = [] + with httpx.Client(transport=_search(1292, seen)) as client: + rows, complete = ats._fetch_rows(client, "eightfold:infineon.eightfold.ai/infineon.com") + assert (len(rows), complete) == (1000, False) and len(seen) == ats.MAX_PAGES == 100 + + +def test_an_empty_board_is_complete_at_zero(monkeypatch: pytest.MonkeyPatch) -> None: + with httpx.Client(transport=_search(0)) as client: + assert ats._fetch_rows(client, f"eightfold:{SLUG}") == ([], True) + + +@pytest.mark.parametrize("body", [ + b"Not found", b"[]", b'{"status": 403, "message": "Not authorized for PCSX"}', + b'{"data": {"positions": null}}']) +def test_an_answer_that_is_not_a_search_raises(body: bytes) -> None: + with pytest.raises(ValueError): + eightfold.page(lambda url, **_: body, SLUG, None) + + +def test_detail_reads_the_text_of_the_ad() -> None: + asked: list[str] = [] + + def get(url: str, **_: Any) -> bytes: + asked.append(url) + return (FIXTURES / "eightfold-detail.json").read_bytes() + + found = eightfold.detail(get, SLUG, {"source_id": "563121777283313"}) + assert asked == ["https://jobs.ericsson.com/api/pcsx/position_details" + "?position_id=563121777283313&domain=ericsson.com&hl=en"] + assert set(found) <= set(ats.DETAIL_FIELDS) + text = found["description"] + assert text.startswith("Join our Team") + assert "<" not in text and "&" not in text and "\r" not in text and " " not in text + + +@pytest.mark.parametrize("body", [b"", b"[]", b'{"data": {}}']) +def test_detail_refuses_an_answer_that_is_not_a_position(body: bytes) -> None: + with pytest.raises(ValueError): + eightfold.detail(lambda url, **_: body, SLUG, {"source_id": "1"}) + + +@pytest.mark.parametrize("role", ["", "12a", "1&domain=evil.example", "../x", "1 2"]) +def test_detail_refuses_an_id_that_is_not_a_number(role: str) -> None: + def get(url: str, **_: Any) -> bytes: + raise AssertionError("no request may be made") + + with pytest.raises(ValueError): + eightfold.detail(get, SLUG, {"source_id": role}) + + +def test_the_slug_the_urls_and_the_allow_list() -> None: + for slug in (SLUG, "infineon.eightfold.ai/infineon.com", "Apply.Careers.Microsoft.com/microsoft.com"): + assert eightfold.slug_ok(slug) and ats.is_known_target(f"eightfold:{slug}") + assert eightfold.careers_url("Jobs.Ericsson.com/ericsson.com") == "https://jobs.ericsson.com/careers" + assert eightfold.robots_page(SLUG) == "https://jobs.ericsson.com/careers" + allow = eightfold.allowed("Jobs.Ericsson.com/ericsson.com") + assert allow("jobs.ericsson.com") and allow("JOBS.ERICSSON.COM") + assert not allow("ericsson.com") and not allow("evil.example") + assert not allow("jobs.ericsson.com.evil.example") and not allow("localhost") + assert atshosts.HOSTS["eightfold"] is eightfold and ats.HOSTS["eightfold"] == "Eightfold" + + +@pytest.mark.parametrize("slug", [ + "", "jobs.ericsson.com", "jobs.ericsson.com/", "/ericsson.com", "jobs.ericsson.com/ericsson", + "jobs.ericsson.com/ericsson.com/", "jobs.ericsson.com/ericsson.com/x", "a/b/c.com", + "a@b.com/ericsson.com", "a.com#x/ericsson.com", "a.com?x/ericsson.com", "../ericsson.com", + "a.com%2fx/b.com", "a.com:443/b.com", "a.com/b.com:80", " a.com/b.com", "a.com/b.com ", + "a.com/b.com\n", "a.com/b.com\r\n", "127.0.0.1/ericsson.com", "a.com/127.0.0.1", + "localhost/ericsson.com", "a.com/localhost", "a.com/b.com&start=9", "a.com/b.com?x=1", + "[::1]/a.com", "a.com/b.com#", "app.localhost/a.com", "printer.local/a.com", + "meta.internal/a.com", "a.com/x.internal", "a_b.com/c.com", "évil.com/a.com"]) +def test_a_hostile_slug_is_refused(slug: str) -> None: + assert not eightfold.slug_ok(slug) + assert not ats.is_known_target(f"eightfold:{slug}") + + +def test_discovery_reads_the_host_and_domain_from_a_link_that_has_both() -> None: + page = ('Jobs' + 'no domain') + found = [(h, s) for h, s, _ in discover.boards_in(page)] + assert ("eightfold", "infineon.eightfold.ai/infineon.com") in found + assert ("eightfold", "") in found + assert "eightfold" not in {h for h, _ in discover._UNREADABLE if h not in atshosts.HOSTS}