Skip to content

: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.

feat(data-warehouse): implement teamtailor import source (#68584)

Tom Owers740003a202c2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 1e8c938b693a..1c9f003779d8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -308,6 +308,7 @@ the row lists both.
| supabase | DB protocol | psycopg (delegates to PostgresSource) | ➖ |
| surveymonkey | HTTP | requests | ✅ |
| taboola | HTTP | requests | ✅ |
+| teamtailor | HTTP | requests | ✅ |
| teamwork | HTTP | requests | ✅ |
| temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ |
| thinkific | HTTP | requests | ✅ |
@@ -681,7 +682,6 @@ doesn't conflict with concurrent PRs.
- tavus
- tawk_to
- teachable
-- teamtailor
- tempo
- testrail
- thinkific_courses
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 5d5adffe2ad1..134fee12fe29 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
@@ -3242,7 +3242,7 @@ class TeachableSourceConfig(config.Config):
@config.config
class TeamtailorSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/canonical_descriptions.py
new file mode 100644
index 000000000000..ee9693125082
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/canonical_descriptions.py
@@ -0,0 +1,76 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Teamtailor public API docs (https://docs.teamtailor.com/).
+# JSON:API resources nest their columns under `attributes`, plus a top-level `id` and `type`.
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "candidates": {
+ "description": "A person in your Teamtailor account who has applied to or been sourced for a job.",
+ "docs_url": "https://docs.teamtailor.com/",
+ "columns": {
+ "id": "The unique ID of the candidate.",
+ "type": "The JSON:API resource type (always 'candidates').",
+ "first-name": "The candidate's first name.",
+ "last-name": "The candidate's last name.",
+ "email": "The candidate's email address.",
+ "phone": "The candidate's phone number.",
+ "created-at": "When the candidate was created.",
+ "updated-at": "When the candidate was last updated.",
+ "sourced": "Whether the candidate was sourced rather than having applied.",
+ },
+ },
+ "jobs": {
+ "description": "A job posting (position) in your Teamtailor account.",
+ "docs_url": "https://docs.teamtailor.com/",
+ "columns": {
+ "id": "The unique ID of the job.",
+ "type": "The JSON:API resource type (always 'jobs').",
+ "title": "The job title.",
+ "status": "The current status of the job (e.g. open, archived).",
+ "body": "The job description body.",
+ "created-at": "When the job was created.",
+ "updated-at": "When the job was last updated.",
+ "start-date": "The job's start date.",
+ "end-date": "The job's end date.",
+ },
+ },
+ "job_applications": {
+ "description": "An application linking a candidate to a job in Teamtailor.",
+ "docs_url": "https://docs.teamtailor.com/",
+ "columns": {
+ "id": "The unique ID of the job application.",
+ "type": "The JSON:API resource type (always 'job-applications').",
+ "created-at": "When the application was created.",
+ "updated-at": "When the application was last updated.",
+ "sourced": "Whether the application came from a sourced candidate.",
+ "rejected-at": "When the application was rejected, if applicable.",
+ },
+ },
+ "users": {
+ "description": "A user (recruiter or team member) in your Teamtailor account.",
+ "docs_url": "https://docs.teamtailor.com/",
+ "columns": {
+ "id": "The unique ID of the user.",
+ "type": "The JSON:API resource type (always 'users').",
+ "name": "The user's full name.",
+ "email": "The user's email address.",
+ "title": "The user's job title.",
+ "role": "The user's role in Teamtailor.",
+ "created-at": "When the user was created.",
+ "updated-at": "When the user was last updated.",
+ },
+ },
+ "departments": {
+ "description": "A department used to organise jobs and users in Teamtailor.",
+ "docs_url": "https://docs.teamtailor.com/",
+ "columns": {
+ "id": "The unique ID of the department.",
+ "type": "The JSON:API resource type (always 'departments').",
+ "name": "The department name.",
+ "created-at": "When the department was created.",
+ "updated-at": "When the department was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/settings.py
new file mode 100644
index 000000000000..02801f5054bf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/settings.py
@@ -0,0 +1,27 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class TeamtailorEndpointConfig:
+ name: str
+ path: str
+ # Teamtailor resource IDs are globally unique strings within an account, so `id` is a safe
+ # primary key across every JSON:API collection.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# Teamtailor public API top-level list endpoints. All are full-refresh only: the API exposes
+# created-at/updated-at filters, but their exact syntax and ordering guarantees are
+# under-documented, so a client-side scan would cost the same as a full refresh (see the
+# implementing-warehouse-sources skill).
+TEAMTAILOR_ENDPOINTS: dict[str, TeamtailorEndpointConfig] = {
+ "candidates": TeamtailorEndpointConfig(name="candidates", path="/candidates"),
+ "jobs": TeamtailorEndpointConfig(name="jobs", path="/jobs"),
+ "job_applications": TeamtailorEndpointConfig(name="job_applications", path="/job-applications"),
+ "users": TeamtailorEndpointConfig(name="users", path="/users"),
+ "departments": TeamtailorEndpointConfig(name="departments", path="/departments"),
+}
+
+ENDPOINTS = tuple(TEAMTAILOR_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/source.py
index 568d6b4fb55c..4f55bd117274 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/source.py
@@ -1,19 +1,42 @@
-from typing import cast
+from typing import Optional, cast
from 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 SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import TeamtailorSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.teamtailor.settings import (
+ ENDPOINTS,
+ TEAMTAILOR_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.teamtailor.teamtailor import (
+ TeamtailorResumeConfig,
+ teamtailor_source,
+ validate_credentials as _validate_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class TeamtailorSource(SimpleSource[TeamtailorSourceConfig]):
+class TeamtailorSource(ResumableSource[TeamtailorSourceConfig, TeamtailorResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.TEAMTAILOR
@@ -24,7 +47,86 @@ class TeamtailorSource(SimpleSource[TeamtailorSourceConfig]):
name=SchemaExternalDataSourceType.TEAMTAILOR,
category=DataWarehouseSourceCategory.HR___RECRUITING,
label="Teamtailor",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Teamtailor API key to pull your recruiting data into the PostHog Data warehouse.
+
+You can create an API key under **Settings → API keys** in Teamtailor. The key grants read access to your candidates, jobs, job applications, users, and departments.
+""",
iconPath="/static/services/teamtailor.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/teamtailor",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.teamtailor.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.teamtailor.com": "Your Teamtailor API key is invalid or has been revoked. Generate a new key under Settings → API keys, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.teamtailor.com": "Your Teamtailor API key does not have access to this data. Check the key's scope, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: TeamtailorSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — Teamtailor's created-at/updated-at filter syntax is
+ # under-documented, so there is no incremental cursor we can advance safely.
+ 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: TeamtailorSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The API key is account-wide, so a single probe validates access to every schema.
+ return _validate_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TeamtailorResumeConfig]:
+ return ResumableSourceManager[TeamtailorResumeConfig](inputs, TeamtailorResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: TeamtailorSourceConfig,
+ resumable_source_manager: ResumableSourceManager[TeamtailorResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in TEAMTAILOR_ENDPOINTS:
+ raise ValueError(f"Unknown Teamtailor schema '{inputs.schema_name}'")
+
+ return teamtailor_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/teamtailor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/teamtailor.py
new file mode 100644
index 000000000000..b185ab193fa4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/teamtailor.py
@@ -0,0 +1,160 @@
+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.teamtailor.settings import TEAMTAILOR_ENDPOINTS
+
+TEAMTAILOR_BASE_URL = "https://api.teamtailor.com/v1"
+# JSON:API caps `page[size]` at 30; the largest page minimises round trips.
+PAGE_SIZE = 30
+REQUEST_TIMEOUT_SECONDS = 60
+# Every request must pin an API version; this dated value is a documented, stable release.
+API_VERSION = "20240404"
+# Cheap endpoint used to confirm an API key is genuine. The key is account-wide, so one probe
+# validates access to every list endpoint.
+DEFAULT_PROBE_PATH = "/users"
+
+
+class TeamtailorRetryableError(Exception):
+ pass
+
+
+class TeamtailorResumeConfig:
+ # Absolute URL of the next page to fetch, taken verbatim from the JSON:API `links.next`.
+ # `None` starts from the first page. Cursor pagination is deterministic, so a crashed
+ # full-refresh sync resumes from the page after the last one yielded; merge dedupes on `id`.
+ next_url: Optional[str] = None
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Token token={api_key}",
+ "X-Api-Version": API_VERSION,
+ "Accept": "application/vnd.api+json",
+ }
+
+
+@retry(
+ retry=retry_if_exception_type((TeamtailorRetryableError, 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,
+ url: str,
+ params: Optional[dict[str, Any]],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ # `links.next` is a fully-formed URL that already carries the page cursor, so params are only
+ # sent for the first request and omitted once we're following `next`.
+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise TeamtailorRetryableError(f"Teamtailor API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Teamtailor API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ data = response.json()
+ # JSON:API responses are always an object with a top-level `data` array; a non-object payload
+ # means a malformed response, so fail loudly rather than silently ending the sync.
+ if not isinstance(data, dict):
+ raise TeamtailorRetryableError(f"Teamtailor returned an unexpected payload for {url}: {type(data).__name__}")
+ return data
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TeamtailorResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = TEAMTAILOR_ENDPOINTS[endpoint]
+ # `redact_values` masks the API key in logged URLs and captured samples.
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ next_url = resume.next_url if resume else None
+ if next_url:
+ logger.debug(f"Teamtailor: resuming {endpoint} from saved cursor")
+
+ while True:
+ if next_url:
+ data = _fetch_page(session, next_url, None, logger)
+ else:
+ data = _fetch_page(session, f"{TEAMTAILOR_BASE_URL}{config.path}", {"page[size]": PAGE_SIZE}, logger)
+
+ items = data.get("data") or []
+ if items:
+ yield items
+
+ # `links.next` is absent or null on the final page.
+ next_url = (data.get("links") or {}).get("next")
+ if not next_url:
+ break
+
+ # 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(TeamtailorResumeConfig(next_url=next_url))
+
+
+def teamtailor_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TeamtailorResumeConfig],
+) -> SourceResponse:
+ config = TEAMTAILOR_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
+
+def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single endpoint to validate the API key.
+
+ 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_key), redact_values=(api_key,))
+ try:
+ response = session.get(f"{TEAMTAILOR_BASE_URL}{path}", params={"page[size]": 1}, timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to Teamtailor: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Teamtailor returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ status, message = check_access(api_key)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Teamtailor API key"
+ return False, message or "Could not validate Teamtailor API key"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/tests/test_teamtailor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/tests/test_teamtailor.py
new file mode 100644
index 000000000000..3ac7324f3d98
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/tests/test_teamtailor.py
@@ -0,0 +1,249 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.teamtailor import teamtailor
+from products.warehouse_sources.backend.temporal.data_imports.sources.teamtailor.settings import (
+ ENDPOINTS,
+ TEAMTAILOR_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.teamtailor.teamtailor import (
+ API_VERSION,
+ PAGE_SIZE,
+ TeamtailorResumeConfig,
+ TeamtailorRetryableError,
+ check_access,
+ get_rows,
+ teamtailor_source,
+ validate_credentials,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = teamtailor._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: TeamtailorResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[TeamtailorResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> TeamtailorResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: TeamtailorResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _page(rows: list[dict], next_url: str | None) -> dict:
+ return {"data": rows, "links": {"next": next_url} if next_url else {}, "meta": {}}
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: list[dict],
+ endpoint: str = "candidates",
+ ) -> tuple[list[dict], list[str | None]]:
+ calls: list[str | None] = []
+ queue = list(pages)
+
+ def fake_fetch(session: Any, url: str, params: Any, logger: Any) -> dict:
+ # Record whether the first page (params present) or a followed `next` URL was requested.
+ calls.append(None if params is not None else url)
+ return queue.pop(0)
+
+ monkeypatch.setattr(teamtailor, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(teamtailor, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_key="tt-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows, calls
+
+ def test_single_page_yields_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows, _ = self._collect(manager, monkeypatch, [_page([{"id": "1"}, {"id": "2"}], next_url=None)])
+ assert rows == [{"id": "1"}, {"id": "2"}]
+ # Only one page, no `next` link, so nothing is persisted.
+ assert manager.saved == []
+
+ def test_follows_next_link_until_null(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = [
+ _page([{"id": "1"}], next_url="https://api.teamtailor.com/v1/candidates?page%5Bnumber%5D=2"),
+ _page([{"id": "2"}], next_url=None),
+ ]
+ rows, calls = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": "1"}, {"id": "2"}]
+ # First call sends params (first page), the second follows the saved `next` URL verbatim.
+ assert calls == [None, "https://api.teamtailor.com/v1/candidates?page%5Bnumber%5D=2"]
+ assert [s.next_url for s in manager.saved] == ["https://api.teamtailor.com/v1/candidates?page%5Bnumber%5D=2"]
+
+ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ resume_url = "https://api.teamtailor.com/v1/candidates?page%5Bnumber%5D=3"
+ manager = _FakeResumableManager(TeamtailorResumeConfig(next_url=resume_url))
+ rows, calls = self._collect(manager, monkeypatch, [_page([{"id": "9"}], next_url=None)])
+ assert rows == [{"id": "9"}]
+ # The first fetch follows the saved cursor, never re-requesting the first page.
+ assert calls == [resume_url]
+
+ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows, _ = self._collect(manager, monkeypatch, [_page([], next_url=None)])
+ 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 {"data": []}
+ 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(TeamtailorRetryableError):
+ _fetch_page_unwrapped(session, "https://api.teamtailor.com/v1/candidates", None, 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, "https://api.teamtailor.com/v1/candidates", None, MagicMock())
+
+ def test_success_returns_object_body(self) -> None:
+ body = {"data": [{"id": "1"}], "links": {}}
+ session = self._session_returning(200, body)
+ result = _fetch_page_unwrapped(session, "https://api.teamtailor.com/v1/candidates", None, MagicMock())
+ assert result == body
+
+ def test_non_object_body_is_retryable(self) -> None:
+ session = self._session_returning(200, [{"id": "1"}])
+ with pytest.raises(TeamtailorRetryableError):
+ _fetch_page_unwrapped(session, "https://api.teamtailor.com/v1/candidates", None, MagicMock())
+
+ def test_first_page_sends_page_size_param(self) -> None:
+ session = self._session_returning(200, {"data": []})
+ _fetch_page_unwrapped(session, "https://api.teamtailor.com/v1/jobs", {"page[size]": PAGE_SIZE}, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"page[size]": PAGE_SIZE}
+
+ def test_next_url_sent_without_params(self) -> None:
+ session = self._session_returning(200, {"data": []})
+ _fetch_page_unwrapped(session, "https://api.teamtailor.com/v1/jobs?page=2", None, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] is None
+
+
+class TestHeaders:
+ def test_headers_carry_token_and_api_version(self) -> None:
+ headers = teamtailor._headers("tt-key")
+ assert headers["Authorization"] == "Token token=tt-key"
+ assert headers["X-Api-Version"] == API_VERSION
+
+
+class TestCheckAccess:
+ def _configure_session(self, mock_make_session: MagicMock, response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ mock_make_session.return_value = session
+ return session
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, 200, None),
+ ("unauthorized", 401, False, 401, None),
+ ("forbidden", 403, False, 403, None),
+ ("server_error", 500, False, 500, "Teamtailor returned HTTP 500"),
+ ]
+ )
+ @mock.patch.object(teamtailor, "make_tracked_session")
+ def test_status_mapping(
+ self,
+ _name: str,
+ status: int,
+ ok: bool,
+ expected_status: int,
+ expected_message: str | None,
+ mock_make_session: MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ self._configure_session(mock_make_session, response)
+ assert check_access("tt-key") == (expected_status, expected_message)
+
+ @mock.patch.object(teamtailor, "make_tracked_session")
+ def test_connection_error_maps_to_zero(self, mock_make_session: MagicMock) -> None:
+ self._configure_session(mock_make_session, requests.ConnectionError("boom"))
+ status, message = check_access("tt-key")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, None),
+ ("unauthorized", 401, False, "Invalid Teamtailor API key"),
+ ("forbidden", 403, False, "Invalid Teamtailor API key"),
+ ("server_error", 500, False, "Teamtailor returned HTTP 500"),
+ ]
+ )
+ @mock.patch.object(teamtailor, "make_tracked_session")
+ def test_validate_credentials(
+ self,
+ _name: str,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_make_session: MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ self._configure_session(mock_make_session, response)
+ assert validate_credentials("tt-key") == (expected_valid, expected_message)
+
+
+class TestTeamtailorSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = teamtailor_source(
+ api_key="tt-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ 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 TEAMTAILOR_ENDPOINTS.values())
+ assert set(TEAMTAILOR_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/tests/test_teamtailor_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/tests/test_teamtailor_source.py
new file mode 100644
index 000000000000..6b434ef5719a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teamtailor/tests/test_teamtailor_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 TeamtailorSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.teamtailor.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.teamtailor.source import TeamtailorSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.teamtailor.teamtailor import (
+ TeamtailorResumeConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestTeamtailorSource:
+ def setup_method(self) -> None:
+ self.source = TeamtailorSource()
+ self.team_id = 123
+ self.config = TeamtailorSourceConfig(api_key="tt-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.TEAMTAILOR
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Teamtailor"
+ assert config.label == "Teamtailor"
+ 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/teamtailor"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_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_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # The only field is the secret API key; the base URL is hardcoded, so there is no non-secret
+ # field an editor could retarget to reuse a preserved key against another account.
+ assert self.source.connection_host_fields == []
+
+ 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=["jobs"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "jobs"
+
+ 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(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://api.teamtailor.com/v1/candidates?page%5Bsize%5D=30",
+ ),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.teamtailor.com/v1/jobs?page%5Bsize%5D=30"),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, _name: str, 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(
+ [
+ (
+ "server_error",
+ "500 Server Error: Internal Server Error for url: https://api.teamtailor.com/v1/candidates",
+ ),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.teamtailor.com/v1/jobs"),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, None),
+ ("unauthorized", 401, False, "Invalid Teamtailor API key"),
+ ("forbidden", 403, False, "Invalid Teamtailor API key"),
+ ("server_error", 500, False, "Teamtailor returned HTTP 500"),
+ ("connection_error", 0, False, "Could not connect to Teamtailor: boom"),
+ ]
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.teamtailor.teamtailor.check_access")
+ def test_validate_credentials(
+ self,
+ _name: str,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_check: mock.MagicMock,
+ ) -> None:
+ message = (
+ "Teamtailor returned HTTP 500"
+ if status == 500
+ else ("Could not connect to Teamtailor: 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 TeamtailorResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.teamtailor.source.teamtailor_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["api_key"] == "tt-key"
+ 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 Teamtailor schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)