:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement recruitee import source (#68587)
Tom Owers220cff280a8b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex c834dc9d68e0..fbf2fce15807 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -285,6 +285,7 @@ the row lists both.| recurly | HTTP | requests + `rest_source.RESTClient` | ✅ || ramp | HTTP | requests | ✅ || recharge | HTTP | requests | ✅ |+| recruitee | HTTP | requests | ✅ || reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || redshift | DB protocol | psycopg (Postgres-compatible) | ➖ || resend | HTTP | requests | ✅ |@@ -613,7 +614,6 @@ doesn't conflict with concurrent PRs.- rb2b- rd_station_marketing- recreation-- recruitee- redis- referralherodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 74650dca97a4..9796413ec581 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -2695,7 +2695,8 @@ class RecreationSourceConfig(config.Config):@config.configclass RecruiteeSourceConfig(config.Config):- pass+ company_id: str+ api_token: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/canonical_descriptions.pynew file mode 100644index 000000000000..2be3d3e3c49a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/canonical_descriptions.py@@ -0,0 +1,57 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Recruitee API docs (https://docs.recruitee.com/reference).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "candidates": {+ "description": "A person who has applied to or been sourced for a job in your Recruitee account.",+ "docs_url": "https://docs.recruitee.com/reference/candidates-index",+ "columns": {+ "id": "The unique ID of the candidate.",+ "name": "The candidate's full name.",+ "emails": "The candidate's email addresses.",+ "phones": "The candidate's phone numbers.",+ "source": "Where the candidate came from (e.g. a job board or referral).",+ "created_at": "When the candidate record was created.",+ "updated_at": "When the candidate record was last updated.",+ },+ },+ "offers": {+ "description": "A job opening (offer) posted in Recruitee that candidates apply to.",+ "docs_url": "https://docs.recruitee.com/reference/offers-index",+ "columns": {+ "id": "The unique ID of the offer.",+ "title": "The job title of the offer.",+ "status": "The current status of the offer (e.g. published, closed, draft).",+ "department_id": "The ID of the department the offer belongs to.",+ "location": "The location of the job.",+ "created_at": "When the offer was created.",+ "updated_at": "When the offer was last updated.",+ },+ },+ "departments": {+ "description": "A department that job offers and candidates are organised under.",+ "docs_url": "https://docs.recruitee.com/reference/departments-index",+ "columns": {+ "id": "The unique ID of the department.",+ "name": "The name of the department.",+ "status": "The status of the department.",+ "offers_count": "The number of offers in the department.",+ },+ },+ "placements": {+ "description": "A candidate placed onto a specific offer, capturing their position in that offer's pipeline.",+ "docs_url": "https://docs.recruitee.com/reference/placements-index",+ "columns": {+ "id": "The unique ID of the placement.",+ "candidate_id": "The ID of the placed candidate.",+ "offer_id": "The ID of the offer the candidate is placed on.",+ "stage_id": "The ID of the current pipeline stage.",+ "status": "The status of the placement (e.g. hired, rejected).",+ "created_at": "When the placement was created.",+ "updated_at": "When the placement was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/recruitee.py b/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/recruitee.pynew file mode 100644index 000000000000..a75b208cab26--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/recruitee.py@@ -0,0 +1,168 @@+import re+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.recruitee.settings import RECRUITEE_ENDPOINTS++RECRUITEE_HOST = "https://api.recruitee.com"+# The list endpoints accept a `limit`; the largest page minimises round trips.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# Cheap probe used to confirm credentials. Departments is the smallest company-level list, and the+# token is company-wide, so one probe validates access to every list endpoint.+DEFAULT_PROBE_PATH = "/departments"+# The company_id is interpolated into the request path, so restrict it to path-safe characters to+# keep the request pinned to api.recruitee.com/c/<company_id>.+COMPANY_ID_REGEX = re.compile(r"^[a-zA-Z0-9_-]+$")+++class RecruiteeRetryableError(Exception):+ pass+++class RecruiteeResumeConfig:+ # Offset of the next page to fetch. Offset pagination is deterministic, so a crashed+ # full-refresh sync resumes from the page after the last one yielded; merge dedupes on `id`.+ offset: int = 0+++def base_url(company_id: str) -> str:+ if not COMPANY_ID_REGEX.match(company_id):+ raise ValueError("Recruitee company ID contains invalid characters")+ return f"{RECRUITEE_HOST}/c/{company_id}"+++def _headers(api_token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_token}", "Accept": "application/json"}+++@retry(+ retry=retry_if_exception_type((RecruiteeRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ company_id: str,+ path: str,+ data_key: str,+ offset: int,+ limit: int,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ response = session.get(+ f"{base_url(company_id)}{path}",+ params={"limit": limit, "offset": offset},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise RecruiteeRetryableError(f"Recruitee API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"Recruitee API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ # Recruitee list endpoints wrap the records under a key named after the resource, e.g.+ # {"candidates": [...]}. Anything else means the payload shape changed unexpectedly.+ if not isinstance(data, dict):+ raise RecruiteeRetryableError(f"Recruitee returned an unexpected payload for {path}: {type(data).__name__}")+ items = data.get(data_key)+ if not isinstance(items, list):+ raise RecruiteeRetryableError(f"Recruitee response for {path} missing list under '{data_key}'")+ return items+++def get_rows(+ company_id: str,+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RecruiteeResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = RECRUITEE_ENDPOINTS[endpoint]+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume.offset if resume else 0+ if resume and resume.offset > 0:+ logger.debug(f"Recruitee: resuming {endpoint} from offset {offset}")++ while True:+ items = _fetch_page(session, company_id, config.path, config.data_key, offset, PAGE_SIZE, logger)+ if items:+ yield items++ # A short page (or an empty one) means we've reached the end of the collection.+ if len(items) < PAGE_SIZE:+ break++ offset += PAGE_SIZE+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(RecruiteeResumeConfig(offset=offset))+++def recruitee_source(+ company_id: str,+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RecruiteeResumeConfig],+) -> SourceResponse:+ config = RECRUITEE_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ company_id=company_id,+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def check_access(company_id: str, api_token: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the credentials.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,))+ try:+ response = session.get(f"{base_url(company_id)}{path}", params={"limit": 1, "offset": 0}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Recruitee: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Recruitee returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(company_id: str, api_token: str) -> tuple[bool, str | None]:+ status, message = check_access(company_id, api_token)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Recruitee company ID or API token"+ return False, message or "Could not validate Recruitee credentials"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/settings.pynew file mode 100644index 000000000000..091423315a6f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/settings.py@@ -0,0 +1,27 @@+from dataclasses import dataclass, field+++@dataclass+class RecruiteeEndpointConfig:+ name: str+ # Path relative to https://api.recruitee.com/c/<company_id> (leading slash included).+ path: str+ # Top-level key in the JSON response that holds the list of records (matches the resource name).+ data_key: str+ # Recruitee object IDs are unique within a company, so `id` is a safe primary key.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++# Recruitee company-level list endpoints. All are full refresh only: Recruitee exposes no+# documented server-side `updated_after`/`created_after` cursor on these listings (the official+# Airbyte connector is likewise full-refresh only), so there is no incremental cursor to advance.+RECRUITEE_ENDPOINTS: dict[str, RecruiteeEndpointConfig] = {+ "candidates": RecruiteeEndpointConfig(name="candidates", path="/candidates", data_key="candidates"),+ "offers": RecruiteeEndpointConfig(name="offers", path="/offers", data_key="offers"),+ "departments": RecruiteeEndpointConfig(name="departments", path="/departments", data_key="departments"),+ "placements": RecruiteeEndpointConfig(name="placements", path="/placements", data_key="placements"),+}++ENDPOINTS = tuple(RECRUITEE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/source.pyindex 65ffccd98e8a..c49e80f6e35b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/source.py@@ -1,30 +1,147 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import RecruiteeSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.recruitee.recruitee import (+ RecruiteeResumeConfig,+ recruitee_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.recruitee.settings import (+ ENDPOINTS,+ RECRUITEE_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class RecruiteeSource(SimpleSource[RecruiteeSourceConfig]):+class RecruiteeSource(ResumableSource[RecruiteeSourceConfig, RecruiteeResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.RECRUITEE+ @property+ def connection_host_fields(self) -> list[str]:+ # The API token is sent to api.recruitee.com/c/<company_id>, so retargeting the company ID+ # must re-require the token — otherwise a preserved token could be pointed at another company.+ return ["company_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.RECRUITEE,category=DataWarehouseSourceCategory.HR___RECRUITING,label="Recruitee",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Recruitee company ID and API token to pull your recruiting data into the PostHog Data warehouse.++Find your company ID and create a personal API token under **Settings → Apps and plugins → Personal API tokens** in [Recruitee](https://app.recruitee.com/). The token grants read access to your candidates, offers, departments, and placements. All tables sync via full refresh.+""",iconPath="/static/services/recruitee.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/recruitee",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="company_id",+ label="Company ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.recruitee.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.recruitee.com": "Your Recruitee API token is invalid or has been revoked. Generate a new token under Settings → Apps and plugins → Personal API tokens, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.recruitee.com": "Your Recruitee API token does not have access to this data. Check the token's role and permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: RecruiteeSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — Recruitee's list endpoints expose no documented,+ # reliably ordered server-side timestamp filter, so there is no incremental cursor to advance.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: RecruiteeSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The token is company-wide, so a single probe validates access to every schema.+ return validate_credentials(config.company_id, config.api_token)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RecruiteeResumeConfig]:+ return ResumableSourceManager[RecruiteeResumeConfig](inputs, RecruiteeResumeConfig)++ def source_for_pipeline(+ self,+ config: RecruiteeSourceConfig,+ resumable_source_manager: ResumableSourceManager[RecruiteeResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in RECRUITEE_ENDPOINTS:+ raise ValueError(f"Unknown Recruitee schema '{inputs.schema_name}'")++ return recruitee_source(+ company_id=config.company_id,+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/tests/test_recruitee.py b/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/tests/test_recruitee.pynew file mode 100644index 000000000000..76766b743927--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/tests/test_recruitee.py@@ -0,0 +1,234 @@+from typing import Any++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.recruitee import recruitee+from products.warehouse_sources.backend.temporal.data_imports.sources.recruitee.recruitee import (+ PAGE_SIZE,+ RecruiteeResumeConfig,+ RecruiteeRetryableError,+ base_url,+ check_access,+ get_rows,+ recruitee_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.recruitee.settings import (+ ENDPOINTS,+ RECRUITEE_ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = recruitee._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: RecruiteeResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[RecruiteeResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> RecruiteeResumeConfig | None:+ return self._state++ def save_state(self, data: RecruiteeResumeConfig) -> None:+ self.saved.append(data)+++def _full_page(start_id: int) -> list[dict]:+ return [{"id": start_id + i} for i in range(PAGE_SIZE)]+++class TestBaseUrl:+ def test_interpolates_company_id_into_path(self) -> None:+ assert base_url("mycompany") == "https://api.recruitee.com/c/mycompany"++ @parameterized.expand([("slash", "a/b"), ("dot", "evil.com"), ("space", "a b"), ("at", "user@host")])+ def test_rejects_unsafe_company_id(self, _name: str, company_id: str) -> None:+ with pytest.raises(ValueError):+ base_url(company_id)+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[int, list[dict]], endpoint: str = "candidates"+ ) -> list[dict]:+ def fake_fetch(+ session: Any, company_id: str, path: str, data_key: str, offset: int, limit: int, logger: Any+ ) -> list[dict]:+ return pages[offset]++ monkeypatch.setattr(recruitee, "_fetch_page", fake_fetch)+ monkeypatch.setattr(recruitee, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ company_id="acme",+ api_token="rc-token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_short_page_yields_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {0: [{"id": 1}, {"id": 2}]})+ assert rows == [{"id": 1}, {"id": 2}]+ # The page is short (< PAGE_SIZE), so we stop without persisting resume state.+ assert manager.saved == []++ def test_follows_offset_pagination_until_short_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {0: _full_page(0), PAGE_SIZE: [{"id": 999}]}+ rows = self._collect(manager, monkeypatch, pages)+ assert len(rows) == PAGE_SIZE + 1+ # State is saved after the first full page (offset advances to PAGE_SIZE), then we stop.+ assert [s.offset for s in manager.saved] == [PAGE_SIZE]++ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(RecruiteeResumeConfig(offset=PAGE_SIZE))+ # Offset 0 must never be fetched on resume.+ pages = {PAGE_SIZE: [{"id": 5}]}+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": 5}]++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {0: []})+ assert rows == []+ assert manager.saved == []+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else {"candidates": []}+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(RecruiteeRetryableError):+ _fetch_page_unwrapped(session, "acme", "/candidates", "candidates", 0, PAGE_SIZE, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "acme", "/candidates", "candidates", 0, PAGE_SIZE, MagicMock())++ def test_success_extracts_list_under_data_key(self) -> None:+ body = {"candidates": [{"id": 1}]}+ session = self._session_returning(200, body)+ result = _fetch_page_unwrapped(session, "acme", "/candidates", "candidates", 0, PAGE_SIZE, MagicMock())+ assert result == [{"id": 1}]++ def test_non_dict_body_is_retryable(self) -> None:+ session = self._session_returning(200, [{"id": 1}])+ with pytest.raises(RecruiteeRetryableError):+ _fetch_page_unwrapped(session, "acme", "/candidates", "candidates", 0, PAGE_SIZE, MagicMock())++ def test_missing_data_key_is_retryable(self) -> None:+ session = self._session_returning(200, {"offers": []})+ with pytest.raises(RecruiteeRetryableError):+ _fetch_page_unwrapped(session, "acme", "/candidates", "candidates", 0, PAGE_SIZE, MagicMock())++ def test_request_uses_limit_and_offset_params(self) -> None:+ session = self._session_returning(200, {"offers": []})+ _fetch_page_unwrapped(session, "acme", "/offers", "offers", 200, PAGE_SIZE, MagicMock())+ args, kwargs = session.get.call_args+ assert kwargs["params"] == {"limit": PAGE_SIZE, "offset": 200}+ assert args[0] == "https://api.recruitee.com/c/acme/offers"+++class TestCheckAccess:+ def _patch_session(self, monkeypatch: Any, response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ monkeypatch.setattr(recruitee, "make_tracked_session", lambda **kwargs: session)+ return session++ @pytest.mark.parametrize(+ "status, ok, expected_status, expected_message",+ [+ (200, True, 200, None),+ (401, False, 401, None),+ (403, False, 403, None),+ (500, False, 500, "Recruitee returned HTTP 500"),+ ],+ )+ def test_status_mapping(+ self, status: int, ok: bool, expected_status: int, expected_message: str | None, monkeypatch: Any+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ self._patch_session(monkeypatch, response)+ assert check_access("acme", "rc-token") == (expected_status, expected_message)++ def test_connection_error_maps_to_zero(self, monkeypatch: Any) -> None:+ self._patch_session(monkeypatch, requests.ConnectionError("boom"))+ status, message = check_access("acme", "rc-token")+ assert status == 0+ assert message is not None and "boom" in message++ @pytest.mark.parametrize(+ "status, expected_valid, expected_message",+ [+ (200, True, None),+ (401, False, "Invalid Recruitee company ID or API token"),+ (403, False, "Invalid Recruitee company ID or API token"),+ (500, False, "Recruitee returned HTTP 500"),+ ],+ )+ def test_validate_credentials(+ self, status: int, expected_valid: bool, expected_message: str | None, monkeypatch: Any+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ self._patch_session(monkeypatch, response)+ assert validate_credentials("acme", "rc-token") == (expected_valid, expected_message)+++class TestRecruiteeSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = recruitee_source(+ company_id="acme",+ api_token="rc-token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # No stable creation timestamp is guaranteed across every object, so we don't partition.+ assert response.partition_mode is None++ def test_every_endpoint_uses_id_primary_key(self) -> None:+ assert all(config.primary_keys == ["id"] for config in RECRUITEE_ENDPOINTS.values())+ assert set(RECRUITEE_ENDPOINTS) == set(ENDPOINTS)++ def test_data_key_matches_resource_name(self) -> None:+ assert all(config.data_key == name for name, config in RECRUITEE_ENDPOINTS.items())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/tests/test_recruitee_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/tests/test_recruitee_source.pynew file mode 100644index 000000000000..30f2666d66a5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/recruitee/tests/test_recruitee_source.py@@ -0,0 +1,151 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import RecruiteeSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.recruitee.recruitee import RecruiteeResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.recruitee.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.recruitee.source import RecruiteeSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestRecruiteeSource:+ def setup_method(self) -> None:+ self.source = RecruiteeSource()+ self.team_id = 123+ self.config = RecruiteeSourceConfig(company_id="acme", api_token="rc-token")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.RECRUITEE++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Recruitee"+ assert config.label == "Recruitee"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source is visible — it must not carry the scaffolding flag.+ assert not config.unreleasedSource+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/recruitee"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["company_id", "api_token"]++ def test_company_id_field_is_non_secret_text(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "company_id")+ assert field.type == SourceFieldInputConfigType.TEXT+ assert field.secret is False+ assert field.required is True++ def test_api_token_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_connection_host_fields_pins_company_id(self) -> None:+ # The secret token is sent to a path derived from company_id, so retargeting the company ID+ # must re-require the token.+ assert self.source.connection_host_fields == ["company_id"]++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["offers"])+ assert len(schemas) == 1+ assert schemas[0].name == "offers"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://api.recruitee.com/c/acme/candidates?limit=100&offset=0",),+ ("403 Client Error: Forbidden for url: https://api.recruitee.com/c/acme/offers?limit=100&offset=0",),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("500 Server Error: Internal Server Error for url: https://api.recruitee.com/c/acme/candidates",),+ ("429 Client Error: Too Many Requests for url: https://api.recruitee.com/c/acme/offers",),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @pytest.mark.parametrize(+ "status, expected_valid, expected_message",+ [+ (200, True, None),+ (401, False, "Invalid Recruitee company ID or API token"),+ (403, False, "Invalid Recruitee company ID or API token"),+ (500, False, "Recruitee returned HTTP 500"),+ (0, False, "Could not connect to Recruitee: boom"),+ ],+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.recruitee.recruitee.check_access")+ def test_validate_credentials(+ self,+ mock_check: mock.MagicMock,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ ) -> None:+ message = (+ "Recruitee returned HTTP 500"+ if status == 500+ else ("Could not connect to Recruitee: boom" if status == 0 else None)+ )+ mock_check.return_value = (status, message)+ is_valid, returned = self.source.validate_credentials(self.config, self.team_id)+ assert is_valid is expected_valid+ assert returned == expected_message++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is RecruiteeResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.recruitee.source.recruitee_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "candidates"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["company_id"] == "acme"+ assert kwargs["api_token"] == "rc-token"+ assert kwargs["endpoint"] == "candidates"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown Recruitee schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)