: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 humanitix import source (#68563)
Tom Owersd3f9438392d2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex fa4067b91421..7e082012f644 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -185,6 +185,7 @@ the row lists both.| height | HTTP | requests | ✅ || hellobaton | HTTP | requests | ✅ || hibob | HTTP | requests | ✅ |+| humanitix | HTTP | requests | ✅ || hubplanner | HTTP | requests | ✅ || hubspot | HTTP | requests | ✅ || hugging_face | HTTP | requests | ✅ |@@ -509,7 +510,6 @@ doesn't conflict with concurrent PRs.- hoorayhr- hubplanner- hugging_face-- humanitix- ikas- illumina_basespace- imaggadiff --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 cea3e99e887c..cba2fbd13a4e 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@@ -1581,7 +1581,7 @@ class HuggingFaceSourceConfig(config.Config):@config.configclass HumanitixSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/canonical_descriptions.pynew file mode 100644index 000000000000..e48c2a78494b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/canonical_descriptions.py@@ -0,0 +1,45 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Humanitix Public API docs (https://api.humanitix.com/v1/documentation).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "events": {+ "description": "A Humanitix event — a ticketed event with its dates, location, capacity, and publishing state.",+ "docs_url": "https://humanitix.stoplight.io/docs/humanitix-public-api/476881e4b5d55-get-events",+ "columns": {+ "_id": "The unique ID of the event.",+ "userId": "The ID of the user that owns the event.",+ "name": "The name of the event.",+ "description": "The event description.",+ "slug": "The URL slug of the event.",+ "dates": "The event's date ranges, each with a start and end time.",+ "startDate": "The start date and time of the event.",+ "endDate": "The end date and time of the event.",+ "timezone": "The IANA timezone the event dates are expressed in.",+ "location": "The event's location as an ISO 3166-1 alpha-2 country code.",+ "eventLocation": "The venue details for the event (address, coordinates, and venue type).",+ "totalCapacity": "The maximum number of attendees the event can hold.",+ "currency": "The currency code used for ticket pricing.",+ "published": "Whether the event is published.",+ "public": "Whether the event is publicly visible.",+ "classification": "The event's type and category classification.",+ "ticketTypes": "The ticket types configured for the event.",+ "createdAt": "The date and time the event was created.",+ "updatedAt": "The date and time the event was last modified.",+ },+ },+ "tags": {+ "description": "A Humanitix tag — a label used to group and organise events in an account.",+ "docs_url": "https://api.humanitix.com/v1/documentation",+ "columns": {+ "_id": "The unique ID of the tag.",+ "name": "The display name of the tag.",+ "userId": "The ID of the user that owns the tag.",+ "location": "The tag's location as an ISO 3166-1 alpha-2 country code.",+ "createdAt": "The date and time the tag was created.",+ "updatedAt": "The date and time the tag was last modified.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/humanitix.py b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/humanitix.pynew file mode 100644index 000000000000..6899056d4e53--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/humanitix.py@@ -0,0 +1,149 @@+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.humanitix.settings import HUMANITIX_ENDPOINTS++HUMANITIX_BASE_URL = "https://api.humanitix.com/v1"+# The list endpoints accept pageSize 1..100; 100 minimises round trips.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm the API key is genuine. The key is account-wide, so one probe+# validates access to every list endpoint.+DEFAULT_PROBE_PATH = "/events"+++class HumanitixRetryableError(Exception):+ pass+++class HumanitixResumeConfig:+ # Next page to fetch (1-indexed). Page-number pagination is deterministic, so a crashed+ # full-refresh sync resumes from the page after the last one yielded; merge dedupes on `_id`.+ next_page: int = 1+++def _headers(api_key: str) -> dict[str, str]:+ return {"x-api-key": api_key, "Accept": "application/json"}+++@retry(+ retry=retry_if_exception_type((HumanitixRetryableError, 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,+ path: str,+ page: int,+ page_size: int,+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ # `page` is required (1-indexed); the API returns the paginated envelope+ # ({total, page, pageSize, <list_key>[]}).+ response = session.get(+ f"{HUMANITIX_BASE_URL}{path}",+ params={"page": page, "pageSize": page_size},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise HumanitixRetryableError(f"Humanitix API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"Humanitix API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ return response.json()+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HumanitixResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = HUMANITIX_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+ page = resume.next_page if resume else 1+ if resume and resume.next_page > 1:+ logger.debug(f"Humanitix: resuming {endpoint} from page {page}")++ while True:+ data = _fetch_page(session, config.path, page, PAGE_SIZE, logger)++ # The row array is always present in the envelope; missing it means a malformed response, so+ # fail loudly rather than silently advancing the cursor past lost rows.+ items = data[config.list_key]+ if items:+ yield items++ # Terminate on a short/empty page, or once the pages fetched cover the reported total.+ if len(items) < PAGE_SIZE:+ break+ total = data.get("total")+ if total is not None and page * PAGE_SIZE >= total:+ break++ page += 1+ # 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(HumanitixResumeConfig(next_page=page))+++def humanitix_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HumanitixResumeConfig],+) -> SourceResponse:+ config = HUMANITIX_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,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single list 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"{HUMANITIX_BASE_URL}{path}", params={"page": 1, "pageSize": 1}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Humanitix: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Humanitix returned HTTP {response.status_code}"++ return 200, Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/settings.pynew file mode 100644index 000000000000..51593d412da7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/settings.py@@ -0,0 +1,31 @@+from dataclasses import dataclass, field+from typing import Optional+++@dataclass+class HumanitixEndpointConfig:+ name: str+ path: str+ # Key of the row array in the paginated response envelope; it differs per endpoint+ # (e.g. `events` for /events, `tags` for /tags) even though the envelope shape is identical.+ list_key: str+ # Humanitix objects are Mongo documents, so `_id` is a stable, globally unique primary key.+ primary_keys: list[str] = field(default_factory=lambda: ["_id"])+ # A stable (never-rewritten) datetime field to partition by. Left unset — every endpoint is+ # full refresh only, so there is no partition cursor to advance.+ partition_key: Optional[str] = None+++# Humanitix Public API list endpoints. Only genuinely top-level, account-scoped list endpoints are+# included: `/events` and `/tags`. Orders and tickets are nested under `/events/{eventId}/...`+# (fan-out per event) and the `/global/*` endpoints return the public marketplace catalog rather+# than the account's own data, so none of those are exposed here.+# All are full-refresh only: the list endpoints expose no server-side incremental cursor to advance.+HUMANITIX_ENDPOINTS: dict[str, HumanitixEndpointConfig] = {+ "events": HumanitixEndpointConfig(name="events", path="/events", list_key="events"),+ "tags": HumanitixEndpointConfig(name="tags", path="/tags", list_key="tags"),+}++ENDPOINTS = tuple(HUMANITIX_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/source.pyindex 2b1e61e05eef..ef49c1ee3adc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/source.py@@ -1,19 +1,42 @@-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 HumanitixSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.humanitix.humanitix import (+ HumanitixResumeConfig,+ check_access,+ humanitix_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.humanitix.settings import (+ ENDPOINTS,+ HUMANITIX_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class HumanitixSource(SimpleSource[HumanitixSourceConfig]):+class HumanitixSource(ResumableSource[HumanitixSourceConfig, HumanitixResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.HUMANITIX@@ -24,7 +47,95 @@ class HumanitixSource(SimpleSource[HumanitixSourceConfig]):name=SchemaExternalDataSourceType.HUMANITIX,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Humanitix",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Humanitix API key to pull your Humanitix data into the PostHog Data warehouse.++You can generate an API key under **Account → Advanced → Public API key** in the Humanitix dashboard. This single key grants read access to your events and tags.+""",iconPath="/static/services/humanitix.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/humanitix",+ 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.humanitix.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked API key surfaces as a requests HTTPError when `_fetch_page` calls+ # `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the sync.+ # Match the stable status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.humanitix.com": "Your Humanitix API key is invalid or has been revoked. Generate a new key under Account → Advanced → Public API key, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.humanitix.com": "Your Humanitix API key does not have access to this data. Check the key's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: HumanitixSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — Humanitix's list endpoints expose no 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: HumanitixSourceConfig, 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; there is+ # no per-endpoint scope to check.+ status, message = check_access(config.api_key)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Humanitix API key"+ return False, message or "Could not validate Humanitix API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HumanitixResumeConfig]:+ return ResumableSourceManager[HumanitixResumeConfig](inputs, HumanitixResumeConfig)++ def source_for_pipeline(+ self,+ config: HumanitixSourceConfig,+ resumable_source_manager: ResumableSourceManager[HumanitixResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in HUMANITIX_ENDPOINTS:+ raise ValueError(f"Unknown Humanitix schema '{inputs.schema_name}'")++ return humanitix_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/humanitix/tests/test_humanitix.py b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/tests/test_humanitix.pynew file mode 100644index 000000000000..6e9dfd74d585--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/tests/test_humanitix.py@@ -0,0 +1,221 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.humanitix import humanitix+from products.warehouse_sources.backend.temporal.data_imports.sources.humanitix.humanitix import (+ PAGE_SIZE,+ HumanitixResumeConfig,+ HumanitixRetryableError,+ check_access,+ get_rows,+ humanitix_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.humanitix.settings import (+ ENDPOINTS,+ HUMANITIX_ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = humanitix._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: HumanitixResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[HumanitixResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> HumanitixResumeConfig | None:+ return self._state++ def save_state(self, data: HumanitixResumeConfig) -> None:+ self.saved.append(data)+++def _page(items: list[dict], total: int, page: int = 1, list_key: str = "events") -> dict[str, Any]:+ return {"total": total, "page": page, "pageSize": PAGE_SIZE, list_key: items}+++def _rows(count: int) -> list[dict]:+ return [{"_id": f"id-{i}"} for i in range(count)]+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[int, dict], endpoint: str = "events"+ ) -> list[dict]:+ def fake_fetch(session: Any, path: str, page: int, page_size: int, logger: Any) -> dict:+ return pages[page]++ monkeypatch.setattr(humanitix, "_fetch_page", fake_fetch)+ monkeypatch.setattr(humanitix, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="hmtx-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_short_page_yields_items_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {1: _page(_rows(2), total=2)})+ assert rows == _rows(2)+ # A short final page means no further pages, so no resume state is persisted.+ assert manager.saved == []++ def test_follows_pagination_until_total_reached(self, monkeypatch: Any) -> None:+ # Two full pages exactly cover the total; a full page whose running count hits total ends it.+ pages = {+ 1: _page(_rows(PAGE_SIZE), total=PAGE_SIZE + 1, page=1),+ 2: _page(_rows(1), total=PAGE_SIZE + 1, page=2),+ }+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, pages)+ assert len(rows) == PAGE_SIZE + 1++ def test_stops_on_full_page_that_reaches_total(self, monkeypatch: Any) -> None:+ # A single full page whose length equals total must terminate without fetching page 2.+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {1: _page(_rows(PAGE_SIZE), total=PAGE_SIZE)})+ assert len(rows) == PAGE_SIZE+ assert manager.saved == []++ def test_saves_next_page_after_yielding_each_batch(self, monkeypatch: Any) -> None:+ pages = {+ 1: _page(_rows(PAGE_SIZE), total=PAGE_SIZE + 1, page=1),+ 2: _page(_rows(1), total=PAGE_SIZE + 1, page=2),+ }+ manager = _FakeResumableManager()+ self._collect(manager, monkeypatch, pages)+ # State is saved AFTER page 1 is yielded (pointing at page 2), and never for the final page.+ assert [s.next_page for s in manager.saved] == [2]++ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(HumanitixResumeConfig(next_page=2))+ pages = {+ # Page 1 must never be fetched on resume. Total spans 3 pages so page 2 (a full page)+ # doesn't hit the total-based stop, and page 3 (a short page) ends the sync.+ 2: _page(_rows(PAGE_SIZE), total=2 * PAGE_SIZE + 1, page=2),+ 3: _page(_rows(1), total=2 * PAGE_SIZE + 1, page=3),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert len(rows) == PAGE_SIZE + 1++ def test_empty_page_does_not_yield(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {1: _page([], total=0)})+ assert rows == []++ def test_uses_endpoint_specific_list_key(self, monkeypatch: Any) -> None:+ # The `tags` endpoint returns its rows under a `tags` key, not `events`.+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {1: _page(_rows(1), total=1, list_key="tags")}, endpoint="tags")+ assert rows == _rows(1)+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: dict | None = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body or {}+ 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(HumanitixRetryableError):+ _fetch_page_unwrapped(session, "/events", 1, 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, "/events", 1, PAGE_SIZE, MagicMock())++ def test_success_returns_json_body(self) -> None:+ body = _page(_rows(1), total=1)+ session = self._session_returning(200, body)+ result = _fetch_page_unwrapped(session, "/events", 1, PAGE_SIZE, MagicMock())+ assert result == body++ def test_request_uses_page_and_page_size_params(self) -> None:+ session = self._session_returning(200, _page([], total=0))+ _fetch_page_unwrapped(session, "/tags", 3, PAGE_SIZE, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"page": 3, "pageSize": PAGE_SIZE}+++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(humanitix, "make_tracked_session", lambda **kwargs: 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, "Humanitix returned HTTP 500"),+ ]+ )+ def test_status_mapping(+ self, _name: str, status: int, ok: bool, expected_status: int, expected_message: str | None+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ session = MagicMock()+ session.get.return_value = response+ with patch.object(humanitix, "make_tracked_session", return_value=session):+ assert check_access("hmtx-key") == (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("hmtx-key")+ assert status == 0+ assert message is not None and "boom" in message+++class TestHumanitixSourceResponse:+ @parameterized.expand([("events",), ("tags",)])+ def test_source_response_uses_id_primary_key(self, endpoint: str) -> None:+ response = humanitix_source(+ api_key="hmtx-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["_id"]+ # Every endpoint is full refresh only, so there is no datetime partitioning.+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_every_endpoint_uses_id_primary_key(self) -> None:+ # Humanitix Mongo `_id`s are globally unique, so a single `_id` key is sufficient table-wide.+ assert all(config.primary_keys == ["_id"] for config in HUMANITIX_ENDPOINTS.values())+ assert set(HUMANITIX_ENDPOINTS) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/tests/test_humanitix_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/tests/test_humanitix_source.pynew file mode 100644index 000000000000..8b67cd948ff9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/humanitix/tests/test_humanitix_source.py@@ -0,0 +1,157 @@+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 HumanitixSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.humanitix.humanitix import HumanitixResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.humanitix.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.humanitix.source import HumanitixSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestHumanitixSource:+ def setup_method(self) -> None:+ self.source = HumanitixSource()+ self.team_id = 123+ self.config = HumanitixSourceConfig(api_key="hmtx-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.HUMANITIX++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Humanitix"+ assert config.label == "Humanitix"+ 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/humanitix"++ 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` itself; the base URL is hardcoded and the account is+ # implicit in the key. There is no non-secret field that retargets where the key is sent.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas is a static catalog with no I/O, so the public docs can render the table list.+ 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)+ # Humanitix's list endpoints have no server-side timestamp filter, so every schema is full refresh.+ 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=["tags"])+ assert len(schemas) == 1+ assert schemas[0].name == "tags"++ 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:+ # Exercises the credential-free catalog path used by the posthog.com docs.+ 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.humanitix.com/v1/events?page=1&pageSize=100",+ ),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.humanitix.com/v1/tags?page=2&pageSize=100"),+ ]+ )+ 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.humanitix.com/v1/events"),+ ("read_timeout", "HTTPSConnectionPool(host='api.humanitix.com', port=443): Read timed out."),+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.humanitix.com/v1/tags"),+ ]+ )+ 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 Humanitix API key"),+ ("forbidden", 403, False, "Invalid Humanitix API key"),+ ("server_error", 500, False, "Humanitix returned HTTP 500"),+ ("connection_error", 0, False, "Could not connect to Humanitix: boom"),+ ]+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.humanitix.source.check_access")+ def test_validate_credentials(+ self,+ _name: str,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_check: mock.MagicMock,+ ) -> None:+ message = (+ "Humanitix returned HTTP 500"+ if status == 500+ else ("Could not connect to Humanitix: 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++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.humanitix.source.check_access")+ def test_validate_credentials_probes_the_account_key(self, mock_check: mock.MagicMock) -> None:+ # The API key is account-wide, so validation probes the key, not a per-schema scope.+ mock_check.return_value = (200, None)+ self.source.validate_credentials(self.config, self.team_id, schema_name="tags")+ mock_check.assert_called_once_with("hmtx-key")++ 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 HumanitixResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.humanitix.source.humanitix_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_humanitix_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "events"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_humanitix_source.assert_called_once()+ kwargs = mock_humanitix_source.call_args.kwargs+ assert kwargs["api_key"] == "hmtx-key"+ assert kwargs["endpoint"] == "events"+ 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 Humanitix schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)