"""Oracle Recruiting Cloud: the listing's rows from a saved page (Nokia's, trimmed), paging and completeness against a fake `get`, the role's own resource for the description (Milestone's, trimmed), the slug, and discovery's patterns. No network.""" from __future__ import annotations import copy import json import sys 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.discover import boards_in # noqa: E402 from plugins import ats # noqa: E402 from plugins.readers import _runner, oracle # noqa: E402 from plugins.readers._shared import is_web_url # noqa: E402 FIXTURES = ROOT / "tests" / "fixtures" / "ats" HOST = "fa-evmr-saasfaprod1.fa.ocs.oraclecloud.com" SLUG = f"{HOST}/CX_1" API = f"https://{HOST}/hcmRestApi/resources/latest" def _listing() -> dict[str, Any]: return json.loads((FIXTURES / "oracle.json").read_bytes()) def _rows() -> list[ats.Row]: return oracle.parse((FIXTURES / "oracle.json").read_bytes(), SLUG) # ------------------------------------------------------------------- rows def test_rows_carry_the_listing_fields() -> None: rows = _rows() assert [r["source_id"] for r in rows] == ["39905", "37189", "40316", "40975", "31680"] first = rows[0] assert first["title"] == "Supply Chain Program Manager" assert first["url"] == f"https://{HOST}/hcmUI/CandidateExperience/en/sites/CX_1/job/39905" assert first["posted"] is not None and first["posted"].isoformat() == "2026-09-28T00:00:00+00:00" assert first["description"] == "" # the text comes with the role's own read assert first["teaser"].startswith("Nokia is searching for a Supply Chain Program") assert first["salary_text"] == "" and "salary_min" not in first assert all(is_web_url(r["url"]) for r in rows) def test_the_locations_are_the_primary_and_the_secondary_ones() -> None: rows = _rows() assert rows[0]["location"] == "Thailand; Malaysia" assert rows[1]["location"] == "Malaysia; Philippines; Indonesia; Thailand" assert rows[2]["location"] == "India" def test_every_place_is_kept_with_its_work_mode() -> None: rows = _rows() assert [p["text"] for p in rows[1]["places"]] == [ "Malaysia", "Philippines", "Indonesia", "Thailand"] assert [p["remote"] for p in rows[0]["places"]] == [False, False] # hybrid assert [p["remote"] for p in rows[4]["places"]] == [True] # remote assert [p["remote"] for p in rows[3]["places"]] == [None] # states none assert all("country" not in r for r in rows) # prep derives it from the places def test_remote_is_the_workplace_type_code_as_given() -> None: assert [r["remote"] for r in _rows()] == [ "ORA_HYBRID", "ORA_HYBRID", "ORA_ON_SITE", None, "ORA_REMOTE"] def test_a_department_is_taken_where_a_tenant_fills_one() -> None: """All four boards read left the department fields null.""" assert {r["department"] for r in _rows()} == {""} data = _listing() data["items"][0]["requisitionList"][0]["JobFamily"] = " Supply Chain " data["items"][0]["requisitionList"][1]["Department"] = "Finance" rows = oracle.parse(json.dumps(data).encode(), SLUG) assert [r["department"] for r in rows[:3]] == ["Supply Chain", "Finance", ""] def test_a_role_without_a_title_or_with_an_id_that_is_no_id_is_dropped_by_the_runner() -> None: data = _listing() roles = data["items"][0]["requisitionList"] roles[0]["Title"] = " " roles[1]["Id"] = "1/../../x" roles[2]["Id"] = "" rows = oracle.parse(json.dumps(data).encode(), SLUG) assert rows[1]["url"] == "" # the id builds no link assert [r["source_id"] for r in rows if _runner.valid(r)] == ["40975", "31680"] def test_a_listing_without_the_expand_has_no_roles() -> None: """Without `expand=requisitionList` the answer is the facets only.""" data = _listing() del data["items"][0]["requisitionList"] assert oracle.parse(json.dumps(data).encode(), SLUG) == [] # ----------------------------------------------------------------- paging @pytest.fixture def no_delay(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(ats, "PAGE_DELAY", 0) def _fake(monkeypatch: pytest.MonkeyPatch, total: int | None = None) -> list[str]: """`ats._get` answering the listing from the saved roles, `limit` and `offset` honoured as Oracle does, and a page past the end empty.""" asked: list[str] = [] every = _listing()["items"][0]["requisitionList"] def fake_get(client, url, host, slug, *, method="GET", payload=None, headers=None, www_twin=False): asked.append(url) limit = int(url.split("limit=")[1].split(",")[0]) offset = int(url.split("offset=")[1]) data = _listing() data["items"][0]["requisitionList"] = every[offset:offset + limit] data["items"][0]["TotalJobsCount"] = len(every) if total is None else total return json.dumps(data).encode() monkeypatch.setattr(ats, "_get", fake_get) return asked def test_the_listing_is_paged_by_limit_and_offset_to_the_stated_total( monkeypatch: pytest.MonkeyPatch, no_delay: None) -> None: asked = _fake(monkeypatch) monkeypatch.setattr(oracle, "PAGE_SIZE", 2) rows, complete = ats._fetch_rows(object(), f"oracle:{SLUG}") # type: ignore[arg-type] find = "onlyData=true&expand=requisitionList.secondaryLocations&finder=findReqs;siteNumber=CX_1" assert asked == [f"{API}/recruitingCEJobRequisitions?{find},limit=2,offset=0", f"{API}/recruitingCEJobRequisitions?{find},limit=2,offset=2", f"{API}/recruitingCEJobRequisitions?{find},limit=2,offset=4"] assert [r["source_id"] for r in rows] == ["39905", "37189", "40316", "40975", "31680"] assert complete def test_a_board_that_ends_short_of_its_total_is_incomplete( monkeypatch: pytest.MonkeyPatch, no_delay: None) -> None: """The total says 7 and the page past the fifth role is empty.""" _fake(monkeypatch, total=7) monkeypatch.setattr(oracle, "PAGE_SIZE", 2) rows, complete = ats._fetch_rows(object(), f"oracle:{SLUG}") # type: ignore[arg-type] assert (len(rows), complete) == (5, False) def test_a_small_board_is_one_page(monkeypatch: pytest.MonkeyPatch, no_delay: None) -> None: asked = _fake(monkeypatch) rows, complete = ats._fetch_rows(object(), f"oracle:{SLUG}") # type: ignore[arg-type] assert len(asked) == 1 and f"limit={oracle.PAGE_SIZE},offset=0" in asked[0] assert (len(rows), complete) == (5, True) def test_an_empty_board_is_complete(monkeypatch: pytest.MonkeyPatch, no_delay: None) -> None: data = _listing() data["items"][0]["requisitionList"] = [] data["items"][0]["TotalJobsCount"] = 0 monkeypatch.setattr(ats, "_get", lambda *a, **k: json.dumps(data).encode()) assert ats._fetch_rows(object(), f"oracle:{SLUG}") == ([], True) # type: ignore[arg-type] @pytest.mark.parametrize("answer", [ {}, {"items": []}, {"items": {}}, {"items": [None]}, [], {"title": "Unauthorized"}]) def test_an_answer_without_the_search_wrapper_fails_the_read( monkeypatch: pytest.MonkeyPatch, no_delay: None, answer: Any) -> None: """It used to read as an empty last page with no total: a complete read of a board with no roles.""" monkeypatch.setattr(ats, "_get", lambda *a, **k: json.dumps(answer).encode()) with pytest.raises(ValueError, match="no search wrapper in items"): ats._fetch_rows(object(), f"oracle:{SLUG}") # type: ignore[arg-type] def test_a_board_answering_without_the_wrapper_is_recorded_failing( monkeypatch: pytest.MonkeyPatch, no_delay: None) -> None: monkeypatch.setattr(ats, "_get", lambda *a, **k: b'{"title": "Unauthorized"}') source = ats.ATSSource({"boards": [{"url": f"oracle:{SLUG}", "label": "Nokia", "params": {}}], "run": "r"}) source.state = {} assert list(source.fetch()) == [] assert f"ats:ok:oracle:{SLUG}" not in source.state assert "no search wrapper" in json.loads(source.state[f"ats:failing:oracle:{SLUG}"])["reason"] # ----------------------------------------------------------------- detail def _detail_get(body: bytes, asked: list[str]) -> Any: def get(url: str, *, method: str = "GET", payload: Any = None, headers: Any = None) -> bytes: asked.append(url) return body return get def test_detail_reads_the_description_and_the_posting_time() -> None: asked: list[str] = [] row = {"source_id": "24594"} got = oracle.detail(_detail_get((FIXTURES / "oracle-detail.json").read_bytes(), asked), "fa-ewto-saasfaprod1.fa.ocs.oraclecloud.com/CX_1001", row) assert asked == [ "https://fa-ewto-saasfaprod1.fa.ocs.oraclecloud.com/hcmRestApi/resources/latest/" "recruitingCEJobRequisitionDetails?expand=all&onlyData=true" "&finder=ById;Id=%2224594%22,siteNumber=CX_1001"] assert got["description"].startswith("Be the key in unlocking business opportunities") assert "<" not in got["description"] and " " not in got["description"] assert "&" not in got["description"] and "\xa0" not in got["description"] assert got["posted"].isoformat() == "2026-09-28T15:09:24+00:00" assert set(got) <= set(ats.DETAIL_FIELDS) def test_detail_appends_the_responsibilities_and_qualifications_where_filled() -> None: data = json.loads((FIXTURES / "oracle-detail.json").read_bytes()) data["items"][0]["ExternalResponsibilitiesStr"] = "" data["items"][0]["ExternalQualificationsStr"] = "

Five years & more

" got = oracle.detail(_detail_get(json.dumps(data).encode(), []), SLUG, {"source_id": "24594"}) assert got["description"].endswith("\n## Responsibilities\n\u2022 Run the desk\n## Qualifications\nFive years & more") def test_detail_of_a_role_no_longer_open_has_nothing_to_read() -> None: data = copy.deepcopy(json.loads((FIXTURES / "oracle-detail.json").read_bytes())) data["items"] = [] assert oracle.detail(_detail_get(json.dumps(data).encode(), []), SLUG, {"source_id": "1"}) == {} def test_a_role_id_cannot_add_to_the_detail_url() -> None: asked: list[str] = [] oracle.detail(_detail_get(b'{"items": []}', asked), SLUG, {"source_id": '1"&x=/../'}) assert asked[0].endswith("finder=ById;Id=%221%22%26x%3D%2F..%2F%22,siteNumber=CX_1") # ----------------------------------------------------------- slug and URLs @pytest.mark.parametrize("slug", [ "fa-ewto-saasfaprod1.fa.ocs.oraclecloud.com/CX_1001", "iaings.fa.ocs.oraclecloud.com/SinchCareer", "ejqi.fa.ocs.oraclecloud.eu/CX_1001", "a.oraclecloud.com/CX", ]) def test_a_pod_and_a_site_number_are_a_slug(slug: str) -> None: assert oracle.slug_ok(slug) and ats.is_known_target(f"oracle:{slug}") @pytest.mark.parametrize("slug", [ "", "CX_1", "/CX_1", f"{HOST}", f"{HOST}/", f"{HOST}/CX_1/", f"{HOST}/CX_1/jobs", f"{HOST}/a b", f" {HOST}/CX_1", f"{HOST} /CX_1", f"{HOST}/CX_1\n", f"{HOST}/CX_1 ", f"{HOST}\n/CX_1", f"{HOST}/CX_1\r\n", f"{HOST}@evil.com/CX_1", f"evil.com@{HOST}/CX_1", f"{HOST}#x/CX_1", f"{HOST}?x=1/CX_1", f"{HOST}/CX_1?x=1", f"{HOST}/CX_1#x", f"{HOST}/CX%2f1", f"{HOST}/..", f"{HOST}/.", f"..{HOST}/CX_1", "../CX_1", f"{HOST}:8443/CX_1", f"{HOST}:443/CX_1", "localhost/CX_1", "127.0.0.1/CX_1", "[::1]/CX_1", "2130706433/CX_1", "oraclecloud.com/CX_1", ".oraclecloud.com/CX_1", "evil.com/CX_1", "fa.oraclecloud.com.evil.com/CX_1", "fa.oraclecloud.com.internal/CX_1", "fa.oraclecloud.org/CX_1", "fa.oraclecloud.com/a/b", "fa.oraclecloud.com\\CX_1", ]) def test_a_hostile_slug_is_refused(slug: str) -> None: assert not oracle.slug_ok(slug) assert not ats.is_known_target(f"oracle:{slug}") def test_only_the_pod_named_by_the_slug_is_allowed() -> None: allow = oracle.allowed(SLUG) assert allow(HOST) and allow(HOST.upper()) assert not allow("fa-ewto-saasfaprod1.fa.ocs.oraclecloud.com.evil.com") assert not allow("jobs.nokia.com") and not allow("oraclecloud.com") assert not allow("fa-evmr-saasfaprod2.fa.ocs.oraclecloud.com") assert ats._allowed_host("oracle", SLUG)(HOST) def test_the_careers_page_is_the_candidate_site() -> None: url = f"https://{HOST}/hcmUI/CandidateExperience/en/sites/CX_1/jobs" assert oracle.careers_url(SLUG) == ats.careers_url(f"oracle:{SLUG}") == url assert oracle.allowed(SLUG)(httpx.URL(url).host) def test_a_slug_written_with_capitals_names_the_same_pod() -> None: slug = f"{HOST.upper()}/CX_1" assert oracle.slug_ok(slug) and oracle.allowed(slug)(HOST) assert oracle.careers_url(slug).startswith(f"https://{HOST}/") # -------------------------------------------------------------- discovery def test_discovery_finds_the_pod_and_the_site_in_a_candidate_site_link() -> None: page = f'Role' assert [(h, s) for h, s, _ in boards_in(page)] == [("oracle", SLUG)] def test_discovery_keeps_the_case_of_a_site_name() -> None: page = "https://iaings.fa.ocs.oraclecloud.com/hcmUI/CandidateExperience/en/sites/SinchCareer/jobs" assert [(h, s) for h, s, _ in boards_in(page)] == [("oracle", "iaings.fa.ocs.oraclecloud.com/SinchCareer")] def test_discovery_reads_the_site_off_the_rest_call() -> None: page = ("fetch('https://ejqi.fa.ocs.oraclecloud.eu/hcmRestApi/resources/latest/" "recruitingCEJobRequisitions?onlyData=true&finder=findReqs;siteNumber=CX_1001,limit=25')") assert [(h, s) for h, s, _ in boards_in(page)] == [("oracle", "ejqi.fa.ocs.oraclecloud.eu/CX_1001")] def test_discovery_names_a_pod_it_has_no_site_for() -> None: page = f"https://{HOST}/hcmUI/faces/AtkHomePageWelcome" assert [(h, s) for h, s, _ in boards_in(page)] == [("oracle", "")] # A company's own domain, which only redirects to the pod, names nothing. assert boards_in("https://jobs.nokia.com/en/sites/CX_1") == [] def test_every_slug_discovery_finds_is_a_slug() -> None: pages = [f"https://{HOST}/hcmUI/CandidateExperience/en/sites/CX_1/jobs", "https://a.fa.us2.oraclecloud.com/hcmUI/CandidateExperience/fr/sites/CX_1001/job/1", "https://a.oraclecloud.eu/hcmUI/CandidateExperience/en/sites/X?lang=en"] for page in pages: found = boards_in(page) assert found and all(oracle.slug_ok(slug) for _h, slug, _ in found), page