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 the smartlook import source (#115529)

Tom Owers7998f16399a7
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 23af3f268cf9..042fa886f714 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -763,6 +763,7 @@ the row lists both.
| smaily | HTTP | requests | ✅ |
| smartengage | HTTP | requests + `rest_source.RESTClient` | ✅ |
| smartlead | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| smartlook | HTTP | requests + `rest_source.RESTClient` | ✅ |
| smartreach | HTTP | requests | ✅ |
| smartsheet | HTTP | requests | ✅ |
| smartwaiver | HTTP | requests | ✅ |
@@ -1435,7 +1436,6 @@ doesn't conflict with concurrent PRs.
- skyvern
- sleuth
- smaily
-- smartlook
- smartrecruiters
- smartwaiver
- smokeball
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/smartlook.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/smartlook.py
index a9f31483952a..c91246ecbdce 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/smartlook.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/smartlook.py
@@ -1,9 +1,12 @@
# This file is automatically generated from `SourceRegistry.get_all_sources()`
# Do not edit manually - run `pnpm generate:source-configs` to regenerate.
+from typing import Literal
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
@config.config
class SmartlookSourceConfig(config.Config):
- pass
+ api_token: str
+ region: Literal["eu", "us"] = config.value(default="eu")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/canonical_descriptions.py
new file mode 100644
index 000000000000..48d8e3c752bf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/canonical_descriptions.py
@@ -0,0 +1,60 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "events": {
+ "description": "Saved event definitions in the Smartlook project.",
+ "docs_url": "https://integrations.smartlook.com/reference/geteventslist",
+ "columns": {
+ "id": "The event definition identifier.",
+ "name": "The event definition name.",
+ "categoryId": "The event category identifier.",
+ "categoryName": "The event category name.",
+ },
+ },
+ "funnels": {
+ "description": "Saved funnels and their ordered event definitions.",
+ "docs_url": "https://integrations.smartlook.com/reference/getfunnelslist",
+ "columns": {
+ "id": "The funnel identifier.",
+ "name": "The funnel name.",
+ "events": "The event definitions that form the funnel.",
+ },
+ },
+ "sessions": {
+ "description": "Session recording metadata and links to the Smartlook player.",
+ "docs_url": "https://integrations.smartlook.com/reference/searchsessions",
+ "columns": {
+ "id": "The session identifier.",
+ "visitorId": "The visitor identifier for the session.",
+ "startedAt": "The time when the session started.",
+ "endedAt": "The time when the session ended.",
+ "duration": "The session duration.",
+ "dashboardURL": "The link to the session in Smartlook.",
+ },
+ },
+ "visitor_events": {
+ "description": "Recorded interactions for each visitor, including custom events, clicks, and errors.",
+ "docs_url": "https://integrations.smartlook.com/reference/getvisitorevents",
+ "columns": {
+ "id": "The recorded event identifier.",
+ "visitor_id": "The visitor identifier from the parent search result.",
+ "visitorId": "The visitor identifier returned with the event.",
+ "sessionId": "The session identifier for the event.",
+ "startedAt": "The time when the event started.",
+ "type": "The interaction type.",
+ "eventName": "The event name.",
+ },
+ },
+ "visitors": {
+ "description": "Visitors with identification properties and the times of their first and last visits.",
+ "docs_url": "https://integrations.smartlook.com/reference/searchvisitors",
+ "columns": {
+ "id": "The visitor identifier.",
+ "firstSeen": "The time when Smartlook first saw the visitor.",
+ "lastSeen": "The time when Smartlook last saw the visitor.",
+ "identification": "The user identifier and custom identification properties.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/settings.py
new file mode 100644
index 000000000000..e6a5adb762a6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/settings.py
@@ -0,0 +1,61 @@
+from dataclasses import field
+from typing import Literal
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.types import IncrementalField
+
+
+@frozen
+class SmartlookEndpoint:
+ name: str
+ path: str
+ data_selector: str
+ primary_keys: tuple[str, ...] = ("id",)
+ partition_key: str | None = None
+ method: Literal["GET", "POST"] = "GET"
+ sort_field: str | None = None
+ fanout: DependentEndpointConfig | None = None
+ page_size: int = 100
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: str | None = None
+
+
+# Timestamp filters need account verification before they can support incremental sync.
+ENDPOINTS: dict[str, SmartlookEndpoint] = {
+ "events": SmartlookEndpoint(name="events", path="/api/v1/events", data_selector="events"),
+ "funnels": SmartlookEndpoint(name="funnels", path="/api/v1/funnels", data_selector="funnels"),
+ "sessions": SmartlookEndpoint(
+ name="sessions",
+ path="/api/v1/sessions/search",
+ data_selector="sessions",
+ partition_key="startedAt",
+ method="POST",
+ sort_field="timeStart",
+ ),
+ "visitor_events": SmartlookEndpoint(
+ name="visitor_events",
+ path="/api/v1/visitors/{visitorId}/events",
+ data_selector="events",
+ primary_keys=("visitor_id", "id"),
+ partition_key="startedAt",
+ fanout=DependentEndpointConfig(
+ parent_name="visitors",
+ resolve_param="visitorId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "visitor_id"},
+ ),
+ ),
+ "visitors": SmartlookEndpoint(
+ name="visitors",
+ path="/api/{api_version}/visitors/search",
+ data_selector="visitors",
+ partition_key="firstSeen",
+ method="POST",
+ sort_field="timeCreate",
+ ),
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/smartlook.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/smartlook.py
new file mode 100644
index 000000000000..19001196af7a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/smartlook.py
@@ -0,0 +1,163 @@
+from typing import Any
+
+from requests.exceptions import HTTPError, RequestException
+from urllib3.util.retry import Retry
+
+from posthog.dataclasses import frozen
+
+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.auth import BearerTokenAuth
+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.rest_client import (
+ RESTClient,
+ RESTClientNonRetryableError,
+ RESTClientRetryableError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.smartlook import (
+ SmartlookSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.smartlook.settings import (
+ ENDPOINTS,
+ SmartlookEndpoint,
+)
+
+REGION_URLS = {"eu": "https://api.eu.smartlook.cloud", "us": "https://api.us.smartlook.cloud"}
+
+
+@frozen
+class SmartlookResumeConfig:
+ paginator_state: dict[str, Any]
+
+
+def client_config(config: SmartlookSourceConfig) -> ClientConfig:
+ if config.region not in REGION_URLS:
+ raise ValueError("Select the EU or US region from your Smartlook project settings.")
+ return {
+ "base_url": REGION_URLS[config.region],
+ "auth": {"type": "bearer", "token": config.api_token},
+ "headers": {"Accept": "application/json"},
+ "paginator": {"type": "json_response", "next_url_path": "_links.nextPage"},
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ "request_timeout": (10, 30),
+ "retry_budget_seconds": 180,
+ "retry_after_max_seconds": 60,
+ }
+
+
+def validate_credentials(config: SmartlookSourceConfig) -> tuple[bool, str | None]:
+ connection = client_config(config)
+ client = RESTClient(
+ base_url=connection["base_url"],
+ auth=BearerTokenAuth(token=config.api_token),
+ allowed_hosts=[],
+ allow_redirects=False,
+ request_timeout=(10, 15),
+ max_retry_attempts=1,
+ session=make_tracked_session(retry=Retry(total=0), redact_values=(config.api_token,)),
+ )
+ try:
+ next(client.paginate("/api/v1/me", paginator=SinglePagePaginator(), data_selector="$"))
+ return True, None
+ except HTTPError as error:
+ status = error.response.status_code if error.response is not None else None
+ if status == 401:
+ return False, "Smartlook rejected the API token. Create a new token in your project settings."
+ if status == 403:
+ return False, "Smartlook denied API access. Check the token, project region, and REST API access."
+ return False, "Smartlook could not validate the token. Try again later."
+ except RESTClientRetryableError:
+ return False, "Smartlook is unavailable or reached its API request limit. Try again later."
+ except RESTClientNonRetryableError:
+ return False, "Smartlook returned an invalid response. Check the project region and try again."
+ except RequestException:
+ return False, "Could not connect to Smartlook. Check the project region and try again."
+
+
+def endpoint_config(endpoint: SmartlookEndpoint, api_version: str) -> Endpoint:
+ result: Endpoint = {
+ "path": endpoint.path.replace("{api_version}", api_version),
+ "method": endpoint.method,
+ "data_selector": endpoint.data_selector,
+ "data_selector_required": True,
+ }
+ if endpoint.method == "POST":
+ assert endpoint.sort_field is not None
+ result["json"] = {"filters": [], "sort": {endpoint.sort_field: "asc"}}
+ return result
+
+
+def smartlook_source(
+ config: SmartlookSourceConfig,
+ manager: ResumableSourceManager[SmartlookResumeConfig],
+ inputs: SourceInputs,
+ api_version: str,
+) -> SourceResponse:
+ settings = ENDPOINTS[inputs.schema_name]
+ connection = client_config(config)
+ resume = manager.load_state() if manager.can_resume() else None
+
+ def save_checkpoint(state: dict[str, Any] | None) -> None:
+ if state is not None:
+ manager.save_state(SmartlookResumeConfig(paginator_state=state))
+
+ if settings.fanout is not None:
+ resource = build_dependent_resource(
+ endpoint_configs=ENDPOINTS,
+ child_endpoint=settings.name,
+ fanout=settings.fanout,
+ client_config=connection,
+ path_format_values={"api_version": api_version},
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ db_incremental_field_last_value=None,
+ parent_endpoint_extra=endpoint_config(ENDPOINTS[settings.fanout.parent_name], api_version),
+ child_endpoint_extra=endpoint_config(settings, api_version),
+ resume_hook=save_checkpoint,
+ initial_paginator_state=resume.paginator_state if resume else None,
+ )
+ else:
+ endpoint = endpoint_config(settings, api_version)
+ endpoint["params"] = {"limit": settings.page_size}
+ rest_config: RESTAPIConfig = {
+ "client": connection,
+ "resources": [
+ {
+ "name": settings.name,
+ "endpoint": endpoint,
+ "write_disposition": "replace",
+ "table_format": "delta",
+ }
+ ],
+ }
+ resource = rest_api_resource(
+ rest_config,
+ inputs.team_id,
+ inputs.job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=resume.paginator_state if resume else None,
+ )
+ return SourceResponse(
+ name=settings.name,
+ items=lambda: resource,
+ primary_keys=list(settings.primary_keys),
+ partition_keys=[settings.partition_key] if settings.partition_key else None,
+ partition_mode="datetime" if settings.partition_key else None,
+ partition_format="month" if settings.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/source.py
index e5f5d1e29e64..d70aa00bf035 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/source.py
@@ -1,27 +1,144 @@
from typing import cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
+)
+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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.smartlook import (
SmartlookSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.smartlook.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.smartlook.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.smartlook.smartlook import (
+ SmartlookResumeConfig,
+ smartlook_source,
+ validate_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SmartlookSource(SimpleSource[SmartlookSourceConfig]):
+class SmartlookSource(ResumableSource[SmartlookSourceConfig, SmartlookResumeConfig]):
+ lists_tables_without_credentials = True
+ # Smartlook versions each endpoint separately. Visitor search uses v2; other resources use v1.
+ supported_versions = ("v2",)
+ default_version = "v2"
+ api_docs_url = "https://integrations.smartlook.com/docs/api-overview"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SMARTLOOK
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Smartlook rejected the API token. Create a new token in your project settings.",
+ "403 Client Error": "Smartlook denied API access. Check the token, project region, and REST API access.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: SmartlookSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ schemas = build_endpoint_schemas(
+ ENDPOINTS,
+ {},
+ names,
+ should_sync_default={"visitor_events": False},
+ )
+ for schema in schemas:
+ schema.detected_primary_keys = list(ENDPOINTS[schema.name].primary_keys)
+ return schemas
+
+ def validate_credentials(
+ self,
+ config: SmartlookSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if not config.api_token or not config.api_token.isascii() or any(c.isspace() for c in config.api_token):
+ return False, "Enter a Smartlook API token without spaces or unsupported characters."
+ if config.region not in ("eu", "us"):
+ return False, "Select the EU or US region from your Smartlook project settings."
+ return validate_credentials(config)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SmartlookResumeConfig]:
+ return ResumableSourceManager(inputs, SmartlookResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SmartlookSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SmartlookResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in ENDPOINTS:
+ raise ValueError(f"Unknown Smartlook table: {inputs.schema_name}")
+ if inputs.should_use_incremental_field:
+ raise ValueError("Smartlook tables support full refresh only. Select full refresh for this table.")
+ return smartlook_source(config, resumable_source_manager, inputs, self.resolve_api_version(inputs.api_version))
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.SMARTLOOK,
category=DataWarehouseSourceCategory.ANALYTICS,
label="Smartlook (Smartlook.com s.r.o. / Cisco)",
+ docsUrl="https://posthog.com/docs/cdp/sources/smartlook",
iconPath="/static/services/smartlook.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption=(
+ "Import visitors, sessions, event definitions, funnels, and visitor events with full refresh. "
+ "Smartlook limits API requests by plan. Large imports can require the REST API add-on. "
+ "Visitor events require requests for each visitor and are disabled by default."
+ ),
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ caption="Ask the project owner to create a token in Project settings > REST API.",
+ ),
+ SourceFieldSelectConfig(
+ name="region",
+ label="Project region",
+ required=True,
+ defaultValue="eu",
+ options=[
+ SourceFieldSelectConfigOption(label="EU", value="eu"),
+ SourceFieldSelectConfigOption(label="US", value="us"),
+ ],
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/tests/test_smartlook.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/tests/test_smartlook.py
new file mode 100644
index 000000000000..a55e1e1368cb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/tests/test_smartlook.py
@@ -0,0 +1,103 @@
+from typing import Literal
+
+import pytest
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.smartlook import (
+ SmartlookSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.smartlook.smartlook import SmartlookResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.smartlook.source import SmartlookSource
+
+
+ ("table", "path", "method", "sort_field", "region"),
+ [
+ ("visitors", "/api/v2/visitors/search", "POST", "timeCreate", "eu"),
+ ("sessions", "/api/v1/sessions/search", "POST", "timeStart", "us"),
+ ("events", "/api/v1/events", "GET", None, "us"),
+ ("funnels", "/api/v1/funnels", "GET", None, "eu"),
+ ],
+)
+def test_import_uses_documented_search_body_and_next_links(
+ region: Literal["eu", "us"], table: str, path: str, method: str, sort_field: str | None
+) -> None:
+ driver = SourceDriver(SmartlookSource(), SmartlookSourceConfig(api_token="test-token", region=region))
+ next_path = f"{path}?after=next-token&limit=100"
+ result = driver.run(
+ table,
+ [
+ ScriptedResponse(
+ json={table: [{"id": "first", "identification": {"uid": None}}], "_links": {"nextPage": next_path}}
+ ),
+ ScriptedResponse(json={table: [{"id": "last"}], "_links": {"nextPage": None}}),
+ ],
+ )
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == ["first", "last"]
+ assert result.paths == [path, path]
+ assert result.params("after") == [None, "next-token"]
+ for request in result.requests:
+ assert request.origin == f"https://api.{region}.smartlook.cloud"
+ assert request.method == method
+ if sort_field:
+ assert request.json() == {"filters": [], "sort": {sort_field: "asc"}}
+ checkpoint = SmartlookResumeConfig(paginator_state={"next_url": f"https://api.{region}.smartlook.cloud{next_path}"})
+ assert result.saved_states == [checkpoint]
+ assert result.committed_states == [checkpoint]
+
+
+def test_resume_starts_at_saved_search_link() -> None:
+ driver = SourceDriver(SmartlookSource(), SmartlookSourceConfig(api_token="test-token", region="eu"))
+ next_url = "https://api.eu.smartlook.cloud/api/v2/visitors/search?after=saved-token&limit=100"
+ result = driver.run(
+ "visitors",
+ [ScriptedResponse(json={"visitors": [{"id": "last"}], "_links": {}})],
+ resume_state=SmartlookResumeConfig(paginator_state={"next_url": next_url}),
+ )
+ assert result.raised is None
+ assert result.urls == [next_url]
+ assert result.requests[0].json() == {"filters": [], "sort": {"timeCreate": "asc"}}
+ assert result.rows == [{"id": "last"}]
+
+
+def test_visitor_events_keep_parent_identity_and_resume_child_pages() -> None:
+ driver = SourceDriver(SmartlookSource(), SmartlookSourceConfig(api_token="test-token", region="eu"))
+ child_next = "/api/v1/visitors/visitor-1/events?after=child-token&limit=100"
+ script = [
+ ScriptedResponse(json={"visitors": [{"id": "visitor-1"}, {"id": "visitor-2"}], "_links": {}}),
+ ScriptedResponse(json={"events": [{"id": "event-1", "value": None}], "_links": {"nextPage": child_next}}),
+ ScriptedResponse(json={"events": [{"id": "event-2", "value": {"custom": True}}], "_links": {}}),
+ ScriptedResponse(json={"events": [{"id": "event-1"}], "_links": {}}),
+ ]
+ result = driver.run("visitor_events", script)
+ assert result.raised is None
+ assert [(row["visitor_id"], row["id"]) for row in result.rows] == [
+ ("visitor-1", "event-1"),
+ ("visitor-1", "event-2"),
+ ("visitor-2", "event-1"),
+ ]
+ assert result.rows[1]["value"] == {"custom": True}
+ assert result.paths == [
+ "/api/v2/visitors/search",
+ "/api/v1/visitors/visitor-1/events",
+ "/api/v1/visitors/visitor-1/events",
+ "/api/v1/visitors/visitor-2/events",
+ ]
+ resumed = driver.run("visitor_events", [script[0], script[2], script[3]], resume_state=result.saved_states[0])
+ assert resumed.raised is None
+ assert resumed.params("after") == [None, "child-token", None]
+ assert [(row["visitor_id"], row["id"]) for row in resumed.rows] == [
+ ("visitor-1", "event-2"),
+ ("visitor-2", "event-1"),
+ ]
+
+
+def test_missing_rows_fail_instead_of_replacing_table_with_empty_data() -> None:
+ driver = SourceDriver(SmartlookSource(), SmartlookSourceConfig(api_token="test-token", region="eu"))
+ result = driver.run("visitors", [ScriptedResponse(json={"unexpected": []})])
+ assert result.raised is not None
+ assert not result.rows
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/tests/test_smartlook_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/tests/test_smartlook_source.py
new file mode 100644
index 000000000000..9f1bfc360bff
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlook/tests/test_smartlook_source.py
@@ -0,0 +1,69 @@
+from typing import Any
+
+import pytest
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.smartlook import (
+ SmartlookSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.smartlook.source import SmartlookSource
+
+
+ ("status", "body", "expected", "message"),
+ [
+ (200, {"projectId": "project-1"}, True, None),
+ (401, {}, False, "rejected the API token"),
+ (403, {}, False, "denied API access"),
+ (400, {}, False, "could not validate"),
+ (429, {}, False, "API request limit"),
+ (503, {}, False, "unavailable"),
+ ],
+)
+def test_credential_probe_maps_vendor_failures(
+ status: int, body: dict[str, str], expected: bool, message: str | None
+) -> None:
+ config = SmartlookSourceConfig(api_token="test-token", region="us")
+ with scripted_network([ScriptedResponse(status=status, json=body)]) as network:
+ valid, error = SmartlookSource().validate_credentials(config, team_id=1)
+ assert valid is expected
+ assert (error is None) if message is None else message in str(error)
+ assert network.requests_log[0].url == "https://api.us.smartlook.cloud/api/v1/me"
+
+
+def test_credential_probe_rejects_non_json_response() -> None:
+ config = SmartlookSourceConfig(api_token="test-token", region="eu")
+ with scripted_network([ScriptedResponse(body=b"<html>Unavailable</html>")]):
+ valid, error = SmartlookSource().validate_credentials(config, team_id=1)
+ assert not valid
+ assert "invalid response" in str(error)
+
+
+ ("token", "region", "message"),
+ [
+ ("", "eu", "API token"),
+ ("token\n", "eu", "API token"),
+ ("tökén", "eu", "API token"),
+ ("test-token", "https://example.com", "EU or US"),
+ ],
+)
+def test_invalid_connection_fields_do_not_send_credentials(token: str, region: Any, message: str) -> None:
+ config = SmartlookSourceConfig(api_token=token, region=region)
+ with scripted_network([]) as network:
+ valid, error = SmartlookSource().validate_credentials(config, team_id=1)
+ assert not valid
+ assert message in str(error)
+ assert not network.requests_log
+
+
[email protected](("table", "incremental"), [("unknown", False), ("visitors", True)])
+def test_pipeline_rejects_unknown_tables_and_unsupported_sync_modes(table: str, incremental: bool) -> None:
+ driver = SourceDriver(SmartlookSource(), SmartlookSourceConfig(api_token="test-token", region="eu"))
+ result = driver.run(table, [], should_use_incremental_field=incremental)
+ assert isinstance(result.raised, ValueError)
+ assert not result.requests