: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 smartengage import source (#72648)
Tom Owers1717ee1b8565
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 2b721fda332d..f5bc2a4c1be7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -484,6 +484,7 @@ the row lists both.| skyvern | HTTP | requests | ✅ || slack | HTTP | requests + `rest_source.RESTClient` | ✅ || smaily | HTTP | requests | ✅ |+| smartengage | HTTP | requests + `rest_source.RESTClient` | ✅ || smartreach | HTTP | requests | ✅ || smartsheet | HTTP | requests | ✅ || smartwaiver | HTTP | requests | ✅ |@@ -933,7 +934,6 @@ doesn't conflict with concurrent PRs.- slash- sleekplan- smaily-- smartengage- smartwaiver- solarwinds_service_desk- sonar_clouddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.pyindex ba6b70af0ce7..890643cfc998 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py@@ -63,12 +63,14 @@ def build_dependent_resource(parent_endpoint_extra: Endpoint | None = None,child_endpoint_extra: Endpoint | None = None,child_params_extra: dict[str, Any] | None = None,- page_size_param: str = "limit",+ page_size_param: str | None = "limit",) -> Iterable[Any]:parent_config = endpoint_configs[fanout.parent_name]child_config = endpoint_configs[child_endpoint]- parent_params: dict[str, Any] = {page_size_param: parent_config.page_size}+ # page_size_param=None is for APIs whose list endpoints take no page-size param at all+ # (unpaginated, full-collection responses) — sending one would be an undocumented param.+ parent_params: dict[str, Any] = {} if page_size_param is None else {page_size_param: parent_config.page_size}parent_params.update(fanout.parent_params)parent_path = parent_config.path@@ -104,8 +106,9 @@ def build_dependent_resource("resource": fanout.parent_name,"field": fanout.resolve_field,},- page_size_param: child_config.page_size,}+ if page_size_param is not None:+ child_params[page_size_param] = child_config.page_sizeif child_params_extra:child_params.update(child_params_extra)child_endpoint_config: Endpoint = {diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/smartengage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/smartengage.pyindex dcf48712e9d8..109f78cdcae3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/smartengage.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/smartengage.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass SmartEngageSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/canonical_descriptions.pynew file mode 100644index 000000000000..a7730780b7f0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/canonical_descriptions.py@@ -0,0 +1,46 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://smartengage.com/docs/"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "avatars": {+ "description": "An avatar is a SmartEngage bot/brand persona, typically linked to a Facebook page. Tags, custom fields, and sequences are all scoped to an avatar.",+ "docs_url": _DOCS_URL,+ "columns": {+ "avatar_id": "Unique identifier for the avatar.",+ "brand_image": "URL of the brand image associated with the avatar.",+ "brand_name": "Name of the brand or company the avatar represents.",+ "facebook_page_id": "Identifier of the Facebook page linked to the avatar.",+ "user_role": "Role of the authenticated user on the avatar.",+ },+ },+ "tags": {+ "description": "Tags defined on an avatar, used to segment and trigger automations for subscribers.",+ "docs_url": _DOCS_URL,+ "columns": {+ "avatar_id": "Identifier of the avatar the tag belongs to.",+ "tag_id": "Unique identifier for the tag.",+ "tag_name": "Display name of the tag.",+ },+ },+ "custom_fields": {+ "description": "Custom subscriber profile fields defined on an avatar.",+ "docs_url": _DOCS_URL,+ "columns": {+ "avatar_id": "Identifier of the avatar the custom field belongs to.",+ "custom_field_id": "Unique identifier for the custom field.",+ "custom_field_name": "Display name of the custom field.",+ },+ },+ "sequences": {+ "description": "Automation sequences (drip campaigns) defined on an avatar.",+ "docs_url": _DOCS_URL,+ "columns": {+ "avatar_id": "Identifier of the avatar the sequence belongs to.",+ "sequence_id": "Unique identifier for the sequence.",+ "sequence_name": "Display name of the sequence.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/settings.pynew file mode 100644index 000000000000..cd13a204728f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/settings.py@@ -0,0 +1,69 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField++SMARTENGAGE_BASE_URL = "https://api.smartengage.com"+++@dataclass+class SmartEngageEndpointConfig:+ name: str+ path: str+ primary_key: list[str]+ # SmartEngage exposes no server-side timestamp filters, so every endpoint is full refresh.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+ # List endpoints are unpaginated (full collection per response); never sent as a param.+ page_size: int = 0+ fanout: DependentEndpointConfig | None = None+++def _avatar_fanout() -> DependentEndpointConfig:+ return DependentEndpointConfig(+ parent_name="avatars",+ resolve_param="avatar_id",+ resolve_field="avatar_id",+ include_from_parent=["avatar_id"],+ parent_field_renames={"avatar_id": "avatar_id"},+ )+++SMARTENGAGE_ENDPOINTS: dict[str, SmartEngageEndpointConfig] = {+ "avatars": SmartEngageEndpointConfig(+ name="avatars",+ path="/avatars/list",+ primary_key=["avatar_id"],+ ),+ # The per-avatar list endpoints take avatar_id as a query param, but the rest_source+ # framework only binds resolve params in the path, so the query string carries the+ # placeholder and is formatted per parent row.+ "tags": SmartEngageEndpointConfig(+ name="tags",+ path="/tags/list?avatar_id={avatar_id}",+ # Tag ids are only documented per avatar and this table aggregates every avatar's+ # tags, so the avatar id is part of the key to keep it unique table-wide.+ primary_key=["avatar_id", "tag_id"],+ fanout=_avatar_fanout(),+ ),+ "custom_fields": SmartEngageEndpointConfig(+ name="custom_fields",+ path="/customfields/list?avatar_id={avatar_id}",+ primary_key=["avatar_id", "custom_field_id"],+ fanout=_avatar_fanout(),+ ),+ "sequences": SmartEngageEndpointConfig(+ name="sequences",+ path="/sequences/list?avatar_id={avatar_id}",+ primary_key=["avatar_id", "sequence_id"],+ fanout=_avatar_fanout(),+ ),+}++ENDPOINTS = tuple(SMARTENGAGE_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SMARTENGAGE_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/smartengage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/smartengage.pynew file mode 100644index 000000000000..356f77a70d06--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/smartengage.py@@ -0,0 +1,136 @@+from collections.abc import Callable, Iterable+from typing import Any, cast++from requests.exceptions import RequestException++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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.smartengage.settings import (+ SMARTENGAGE_BASE_URL,+ SMARTENGAGE_ENDPOINTS,+ SmartEngageEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 30+++def _client_config(api_key: str) -> ClientConfig:+ return {+ "base_url": SMARTENGAGE_BASE_URL,+ "auth": {"type": "bearer", "token": api_key},+ "headers": {"Accept": "application/json"},+ }+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ try:+ response = make_tracked_session().get(+ f"{SMARTENGAGE_BASE_URL}/avatars/list",+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ except RequestException as exc:+ return False, f"SmartEngage request failed: {exc}"++ if response.status_code in (401, 403):+ return False, "Invalid SmartEngage API key"+ if response.status_code != 200:+ return False, f"SmartEngage API returned status {response.status_code}"++ # List endpoints return a bare JSON array; anything else (e.g. an error object served+ # with a 200) means the key is not usable.+ try:+ payload = response.json()+ except ValueError:+ return False, "SmartEngage API returned an unexpected response"+ if not isinstance(payload, list):+ return False, "SmartEngage API returned an unexpected response"++ return True, None+++def get_resource(endpoint: str) -> EndpointResource:+ config = SMARTENGAGE_ENDPOINTS[endpoint]+ if config.fanout:+ raise ValueError(f"Fan-out endpoint '{endpoint}' must use the fan-out path")++ endpoint_config: Endpoint = {+ "path": config.path,+ "params": {},+ # List endpoints return a bare JSON array with no pagination.+ "data_selector": "$",+ "paginator": SinglePagePaginator(),+ }++ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+++def _make_source_response(+ endpoint_config: SmartEngageEndpointConfig, items_fn: Callable[[], Iterable[Any]]+) -> SourceResponse:+ # No SmartEngage table exposes a stable timestamp, so there is no partitioning.+ return SourceResponse(+ name=endpoint_config.name,+ items=items_fn,+ primary_keys=endpoint_config.primary_key,+ )+++def smartengage_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+) -> SourceResponse:+ endpoint_config = SMARTENGAGE_ENDPOINTS[endpoint]++ if endpoint_config.fanout:+ dependent_resource = cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=SMARTENGAGE_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=endpoint_config.fanout,+ client_config=_client_config(api_key),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ # SmartEngage list endpoints take no page-size param — they return the+ # full collection in one response.+ page_size_param=None,+ parent_endpoint_extra={"paginator": SinglePagePaginator(), "data_selector": "$"},+ child_endpoint_extra={"paginator": SinglePagePaginator(), "data_selector": "$"},+ ),+ )+ return _make_source_response(endpoint_config, lambda: dependent_resource)++ config: RESTAPIConfig = {+ "client": _client_config(api_key),+ "resource_defaults": {"write_disposition": "replace"},+ "resources": [get_resource(endpoint=endpoint)],+ }++ resource = rest_api_resource(config, team_id, job_id, None)+ return _make_source_response(endpoint_config, lambda: resource)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/source.pyindex e4161e30aceb..6a7d6803ff41 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/source.py@@ -1,32 +1,110 @@-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.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+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.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.smartengage import (SmartEngageSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.smartengage.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.smartengage.smartengage import (+ smartengage_source,+ validate_credentials as validate_smartengage_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass SmartEngageSource(SimpleSource[SmartEngageSourceConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://smartengage.com/docs/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SMARTENGAGE+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid SmartEngage API key. Please update your key and reconnect.",+ "403 Client Error": "Your SmartEngage API key does not have the required permissions. Please update the key and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.smartengage.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: SmartEngageSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self, config: SmartEngageSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_smartengage_credentials(config.api_key)++ def source_for_pipeline(self, config: SmartEngageSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return smartengage_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.SMART_ENGAGE,category=DataWarehouseSourceCategory.MARKETING___EMAIL,label="SmartEngage",+ caption="""Enter your SmartEngage API key to sync avatars, tags, custom fields, and sequences.++You can find your API key in your SmartEngage account settings.+""",+ docsUrl="https://posthog.com/docs/cdp/sources/smartengage",iconPath="/static/services/smartengage.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="se_...",+ secret=True,+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/tests/test_smartengage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/tests/test_smartengage.pynew file mode 100644index 000000000000..14ea555905ee--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/tests/test_smartengage.py@@ -0,0 +1,138 @@+from typing import Any, cast++import pytest+from unittest.mock import Mock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.smartengage.smartengage import (+ get_resource,+ smartengage_source,+ validate_credentials,+)+++class _FakeDltResource:+ def __init__(self, name: str, rows: list[dict]) -> None:+ self.name = name+ self._rows = rows++ def add_map(self, mapper):+ self._rows = [mapper(dict(row)) for row in self._rows]+ return self++ def __iter__(self):+ return iter(self._rows)+++class TestSmartEngageTransport:+ @parameterized.expand(+ [+ ("valid_key", 200, [{"avatar_id": "1"}], (True, None)),+ ("empty_account", 200, [], (True, None)),+ ("unauthorized", 401, {"error": "unauthorized"}, (False, "Invalid SmartEngage API key")),+ ("forbidden", 403, {"error": "forbidden"}, (False, "Invalid SmartEngage API key")),+ ("server_error", 503, {}, (False, "SmartEngage API returned status 503")),+ # An error object served with a 200 must not validate as a working key.+ (+ "error_body_with_200",+ 200,+ {"error": "invalid key"},+ (False, "SmartEngage API returned an unexpected response"),+ ),+ ]+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.smartengage.smartengage.make_tracked_session"+ )+ def test_validate_credentials_status_mapping(self, _name, status, payload, expected, mock_session) -> None:+ response = Mock(status_code=status)+ response.json.return_value = payload+ mock_session.return_value.get.return_value = response++ assert validate_credentials(api_key="se_key") == expected++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.smartengage.smartengage.make_tracked_session"+ )+ def test_validate_credentials_handles_request_exception(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = requests.exceptions.RequestException("boom")+ is_valid, message = validate_credentials(api_key="se_key")+ assert is_valid is False+ assert message is not None and "SmartEngage request failed" in message++ def test_get_resource_avatars_is_unpaginated_root_array(self) -> None:+ resource = cast(dict[str, Any], get_resource(endpoint="avatars"))+ assert resource["name"] == "avatars"+ assert resource["write_disposition"] == "replace"+ assert resource["endpoint"]["path"] == "/avatars/list"+ # SmartEngage returns the full collection as a bare JSON array in one response.+ assert resource["endpoint"]["data_selector"] == "$"++ @parameterized.expand([("tags",), ("custom_fields",), ("sequences",)])+ def test_get_resource_rejects_fanout_endpoints(self, endpoint: str) -> None:+ with pytest.raises(ValueError, match="Fan-out endpoint"):+ get_resource(endpoint=endpoint)++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.smartengage.smartengage.rest_api_resource")+ def test_avatars_source_response(self, mock_rest_api_resource) -> None:+ mock_rest_api_resource.return_value = Mock()+ response = smartengage_source(api_key="se_key", endpoint="avatars", team_id=1, job_id="job-1")++ assert response.name == "avatars"+ assert response.primary_keys == ["avatar_id"]+ # No SmartEngage table has a stable timestamp, so nothing is partitioned.+ assert response.partition_mode is None++ @parameterized.expand(+ [+ ("tags", "tag_id"),+ ("custom_fields", "custom_field_id"),+ ("sequences", "sequence_id"),+ ]+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_fanout_row_format_and_composite_key(self, endpoint, child_id_field, mock_rest_api_resources) -> None:+ mock_rest_api_resources.return_value = [+ _FakeDltResource("avatars", [{"avatar_id": "av_1"}]),+ _FakeDltResource(endpoint, [{child_id_field: "child_1", "_avatars_avatar_id": "av_1"}]),+ ]++ response = smartengage_source(api_key="se_key", endpoint=endpoint, team_id=1, job_id="job-1")++ rows = list(cast(Any, response.items()))+ assert rows == [{child_id_field: "child_1", "avatar_id": "av_1"}]+ # Child ids are only documented per avatar, so the avatar id must stay in the key —+ # dropping it seeds duplicate rows that every later merge multi-matches.+ assert response.primary_keys == ["avatar_id", child_id_field]++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_fanout_binds_avatar_id_in_path_and_sends_no_page_size(self, mock_rest_api_resources) -> None:+ mock_rest_api_resources.return_value = [+ _FakeDltResource("avatars", []),+ _FakeDltResource("tags", []),+ ]++ smartengage_source(api_key="se_key", endpoint="tags", team_id=1, job_id="job-1")++ config = mock_rest_api_resources.call_args.args[0]+ parent, child = config["resources"]++ # The avatar_id resolve param can only be bound via a path placeholder (the framework+ # doesn't support resolve query params), so it must ride the path's query string.+ assert child["endpoint"]["path"] == "/tags/list?avatar_id={avatar_id}"+ assert child["endpoint"]["params"]["avatar_id"] == {+ "type": "resolve",+ "resource": "avatars",+ "field": "avatar_id",+ }+ assert child["include_from_parent"] == ["avatar_id"]++ # SmartEngage endpoints are unpaginated: no undocumented page-size param may be sent.+ assert "limit" not in parent["endpoint"]["params"]+ assert "limit" not in child["endpoint"]["params"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/tests/test_smartengage_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/tests/test_smartengage_source.pynew file mode 100644index 000000000000..2178e4b1556c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartengage/tests/test_smartengage_source.py@@ -0,0 +1,101 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.smartengage import (+ SmartEngageSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.smartengage.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.smartengage.source import SmartEngageSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestSmartEngageSource:+ def setup_method(self) -> None:+ self.source = SmartEngageSource()+ self.team_id = 123+ self.config = SmartEngageSourceConfig(api_key="se_test_key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SMARTENGAGE++ def test_get_source_config_is_released(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "SmartEngage"+ assert config.category == DataWarehouseSourceCategory.MARKETING___EMAIL+ # The source must stay visible: unreleasedSource hides it from every user.+ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/smartengage"++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ assert [f.name for f in config.fields] == ["api_key"]+ field = config.fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_get_schemas_are_full_refresh_only(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ # SmartEngage has no server-side timestamp filters, so no endpoint may advertise+ # incremental sync — a client-side "incremental" would silently miss nothing but+ # cost the same as full refresh and corrupt sync-type expectations.+ for schema in schemas:+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["tags"])+ assert [s.name for s in schemas] == ["tags"]++ @pytest.mark.parametrize(+ "observed_error,expected_non_retryable",+ [+ ("401 Client Error: Unauthorized for url: https://api.smartengage.com/avatars/list", True),+ ("403 Client Error: Forbidden for url: https://api.smartengage.com/tags/list", True),+ ("500 Server Error: Internal Server Error for url: https://api.smartengage.com/avatars/list", False),+ ],+ )+ def test_non_retryable_errors(self, observed_error: str, expected_non_retryable: bool) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable) is expected_non_retryable++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.smartengage.source.validate_smartengage_credentials"+ )+ def test_validate_credentials_plumbs_api_key(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)+ assert mock_validate.call_args.args == ("se_test_key",)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.smartengage.source.smartengage_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_smartengage_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "tags"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"++ self.source.source_for_pipeline(self.config, inputs)++ kwargs = mock_smartengage_source.call_args.kwargs+ assert kwargs == {+ "api_key": "se_test_key",+ "endpoint": "tags",+ "team_id": self.team_id,+ "job_id": "job-1",+ }++ def test_canonical_descriptions_cover_endpoints(self) -> None:+ assert set(self.source.get_canonical_descriptions().keys()) == set(ENDPOINTS)