: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 opinion_stage import source (#68591)
Tom Owers93a1ca4a3f79
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex b1020914d55f..fe4bb08bbdc6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -243,6 +243,7 @@ the row lists both.| omnisend | HTTP | requests | ✅ || onfleet | HTTP (cursor pagination) | requests | ✅ || open_exchange_rates | HTTP | requests | ✅ |+| opinion_stage | HTTP | requests | ✅ || orb | HTTP | requests + `rest_source.RESTClient` | ✅ || openaq | HTTP | requests | ✅ || openfda | HTTP | requests | ✅ |@@ -557,7 +558,6 @@ doesn't conflict with concurrent PRs.- onepagecrm- onesignal- open_data_dc-- opinion_stage- opsgenie- opuswatch- oraclediff --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 dd26bf6fbd33..b32a8a66d66e 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@@ -2282,7 +2282,7 @@ class OpenWeatherSourceConfig(config.Config):@config.configclass OpinionStageSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/canonical_descriptions.pynew file mode 100644index 000000000000..9d432c3d3106--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/canonical_descriptions.py@@ -0,0 +1,18 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Opinion Stage Public Result API (JSON:API). Rows are the raw JSON:API+# resource objects, so the top-level columns are `id`, `type`, and the nested `attributes` object.+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "items": {+ "description": "An Opinion Stage item — an interactive content widget such as a quiz, survey, form, or poll. (The poll format is not returned by this API.)",+ "docs_url": "https://www.opinionstage.com/",+ "columns": {+ "id": "The unique ID of the item (widget), as the JSON:API resource identifier.",+ "type": "The JSON:API resource type for the object (for example, 'items').",+ "attributes": "The item's attributes, including its title, content format/kind, publication state, and created/modified timestamps.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/opinion_stage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/opinion_stage.pynew file mode 100644index 000000000000..4ee918ef2b67--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/opinion_stage.py@@ -0,0 +1,164 @@+import base64+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.opinion_stage.settings import (+ OPINION_STAGE_ENDPOINTS,+)++OPINION_STAGE_BASE_URL = "https://api.opinionstage.com"+# JSON:API `page[size]`. The API does not document a hard maximum, so a moderate page keeps the+# per-page payload bounded while minimising round trips for the small item/widget catalogue.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm the API key is genuine. The personal API key is account-wide, so+# one probe validates access to every list endpoint.+DEFAULT_PROBE_PATH = "/api/v2/items"+# Opinion Stage speaks the JSON:API media type for both request Accept and response Content-Type.+JSON_API_MEDIA_TYPE = "application/vnd.api+json"+++class OpinionStageRetryableError(Exception):+ pass+++class OpinionStageResumeConfig:+ # 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]:+ # HTTP Basic auth: the personal API key is the username and the password is blank, so the+ # credential is base64("<api_key>:"). Precomputing the header keeps the raw key out of URLs.+ token = base64.b64encode(f"{api_key}:".encode()).decode()+ return {"Authorization": f"Basic {token}", "Accept": JSON_API_MEDIA_TYPE}+++@retry(+ retry=retry_if_exception_type((OpinionStageRetryableError, 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,+ per_page: int,+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.get(+ f"{OPINION_STAGE_BASE_URL}{path}",+ params={"page[number]": page, "page[size]": per_page},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise OpinionStageRetryableError(+ f"Opinion Stage API error (retryable): status={response.status_code}, path={path}"+ )++ if not response.ok:+ logger.error(f"Opinion Stage API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ # JSON:API always wraps a collection under a top-level `data` list; missing it means a malformed+ # response, so fail loudly rather than silently advancing the cursor past lost rows.+ if not isinstance(data, dict) or not isinstance(data.get("data"), list):+ raise OpinionStageRetryableError(+ f"Opinion Stage returned an unexpected payload for {path}: {type(data).__name__}"+ )+ return data+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OpinionStageResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = OPINION_STAGE_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"Opinion Stage: resuming {endpoint} from page {page}")++ while True:+ payload = _fetch_page(session, config.path, page, PAGE_SIZE, logger)++ # Yield the raw JSON:API resource objects ({id, type, attributes}); `id` is the primary key.+ items = payload["data"]+ if items:+ yield items++ # JSON:API paginates via `links.next`: a null/absent next link (or an empty page) is the end+ # of the collection.+ next_link = (payload.get("links") or {}).get("next")+ if not next_link or not items:+ 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(OpinionStageResumeConfig(next_page=page))+++def opinion_stage_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OpinionStageResumeConfig],+) -> SourceResponse:+ config = OPINION_STAGE_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 list endpoint to validate the personal 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"{OPINION_STAGE_BASE_URL}{path}",+ params={"page[number]": 1, "page[size]": 1},+ timeout=15,+ )+ except Exception as e:+ return 0, f"Could not connect to Opinion Stage: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Opinion Stage returned HTTP {response.status_code}"++ return 200, Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/settings.pynew file mode 100644index 000000000000..f6289b5eadcd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/settings.py@@ -0,0 +1,24 @@+from dataclasses import dataclass, field+++@dataclass+class OpinionStageEndpointConfig:+ name: str+ path: str+ # JSON:API resource objects carry a top-level `id`, unique within the account, so it is a safe+ # primary key.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++# Opinion Stage Public Result API list endpoints. Only account-level collections that can be listed+# without a parent id are included. Per-item `responses` and `questions` are fan-out (they require an+# item id) and are intentionally excluded from v1.+#+# All are full-refresh only: although the docs mention date-range filtering, the filter parameter+# names are not defined in the OpenAPI spec, so there is no incremental cursor we can advance safely+# (see the implementing-warehouse-sources skill).+OPINION_STAGE_ENDPOINTS: dict[str, OpinionStageEndpointConfig] = {+ "items": OpinionStageEndpointConfig(name="items", path="/api/v2/items"),+}++ENDPOINTS = tuple(OPINION_STAGE_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/source.pyindex f546f25349db..bd094d804466 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/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 OpinionStageSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.opinion_stage.opinion_stage import (+ OpinionStageResumeConfig,+ check_access,+ opinion_stage_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.opinion_stage.settings import (+ ENDPOINTS,+ OPINION_STAGE_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class OpinionStageSource(SimpleSource[OpinionStageSourceConfig]):+class OpinionStageSource(ResumableSource[OpinionStageSourceConfig, OpinionStageResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.OPINIONSTAGE@@ -24,7 +47,94 @@ class OpinionStageSource(SimpleSource[OpinionStageSourceConfig]):name=SchemaExternalDataSourceType.OPINION_STAGE,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Opinion Stage",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Opinion Stage personal API key to pull your interactive content data into the PostHog Data warehouse.++You can find your API key on your account settings page in [Opinion Stage](https://www.opinionstage.com/). The key grants read access to your items (quizzes, surveys, and forms) via the Public Result API.+""",iconPath="/static/services/opinion_stage.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/opinion-stage",+ 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.opinion_stage.canonical_descriptions import ( # noqa: PLC0415+ 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.opinionstage.com": "Your Opinion Stage API key is invalid or has been revoked. Generate a new key on your account settings page, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.opinionstage.com": "Your Opinion Stage API key does not have access to this data. Check the key's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: OpinionStageSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — the documented date-range filter has no parameter+ # names in the OpenAPI spec, so there is no incremental cursor to 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: OpinionStageSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The personal API key is account-wide, so a single probe validates access to every schema.+ status, message = check_access(config.api_key)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Opinion Stage API key"+ return False, message or "Could not validate Opinion Stage API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OpinionStageResumeConfig]:+ return ResumableSourceManager[OpinionStageResumeConfig](inputs, OpinionStageResumeConfig)++ def source_for_pipeline(+ self,+ config: OpinionStageSourceConfig,+ resumable_source_manager: ResumableSourceManager[OpinionStageResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in OPINION_STAGE_ENDPOINTS:+ raise ValueError(f"Unknown Opinion Stage schema '{inputs.schema_name}'")++ return opinion_stage_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/opinion_stage/tests/test_opinion_stage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/tests/test_opinion_stage.pynew file mode 100644index 000000000000..bb7f081170e8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/tests/test_opinion_stage.py@@ -0,0 +1,224 @@+from typing import Any++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.opinion_stage import opinion_stage+from products.warehouse_sources.backend.temporal.data_imports.sources.opinion_stage.opinion_stage import (+ PAGE_SIZE,+ OpinionStageResumeConfig,+ OpinionStageRetryableError,+ check_access,+ get_rows,+ opinion_stage_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.opinion_stage.settings import (+ ENDPOINTS,+ OPINION_STAGE_ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = opinion_stage._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: OpinionStageResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[OpinionStageResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> OpinionStageResumeConfig | None:+ return self._state++ def save_state(self, data: OpinionStageResumeConfig) -> None:+ self.saved.append(data)+++def _page(items: list[dict], next_link: str | None) -> dict[str, Any]:+ # JSON:API collection envelope: rows under `data`, pagination via `links.next`.+ return {"data": items, "meta": {}, "links": {"self": "s", "next": next_link}}+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[int, dict], endpoint: str = "items"+ ) -> list[dict]:+ def fake_fetch(session: Any, path: str, page: int, per_page: int, logger: Any) -> dict:+ return pages[page]++ monkeypatch.setattr(opinion_stage, "_fetch_page", fake_fetch)+ monkeypatch.setattr(opinion_stage, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="os-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_page_yields_items_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {1: _page([{"id": "1"}, {"id": "2"}], next_link=None)})+ assert rows == [{"id": "1"}, {"id": "2"}]+ # No next link, so no resume state is persisted.+ assert manager.saved == []++ def test_follows_pagination_until_next_link_is_null(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ 1: _page([{"id": "1"}], next_link="p2"),+ 2: _page([{"id": "2"}], next_link="p3"),+ 3: _page([{"id": "3"}], next_link=None),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": "1"}, {"id": "2"}, {"id": "3"}]++ def test_saves_next_page_after_yielding_each_batch(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ 1: _page([{"id": "1"}], next_link="p2"),+ 2: _page([{"id": "2"}], next_link=None),+ }+ 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(OpinionStageResumeConfig(next_page=2))+ pages = {+ # Page 1 must never be fetched on resume.+ 2: _page([{"id": "2"}], next_link="p3"),+ 3: _page([{"id": "3"}], next_link=None),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": "2"}, {"id": "3"}]++ def test_empty_data_does_not_yield(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {1: _page([], next_link=None)})+ assert rows == []++ def test_stops_when_page_is_empty_even_with_next_link(self, monkeypatch: Any) -> None:+ # A defensive guard: an empty page terminates the sync even if the API keeps advertising a+ # next link, so we never loop forever on a stale cursor.+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {1: _page([], next_link="p2")})+ 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(OpinionStageRetryableError):+ _fetch_page_unwrapped(session, "/api/v2/items", 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, "/api/v2/items", 1, PAGE_SIZE, MagicMock())++ def test_success_returns_json_body(self) -> None:+ body = _page([{"id": "1"}], next_link=None)+ session = self._session_returning(200, body)+ result = _fetch_page_unwrapped(session, "/api/v2/items", 1, PAGE_SIZE, MagicMock())+ assert result == body++ def test_missing_data_list_is_retryable(self) -> None:+ # A payload without a top-level `data` list is malformed for JSON:API; treat it as transient+ # rather than silently yielding nothing.+ session = self._session_returning(200, {"errors": [{"detail": "nope"}]})+ with pytest.raises(OpinionStageRetryableError):+ _fetch_page_unwrapped(session, "/api/v2/items", 1, PAGE_SIZE, MagicMock())++ def test_request_uses_json_api_page_params(self) -> None:+ session = self._session_returning(200, _page([], next_link=None))+ _fetch_page_unwrapped(session, "/api/v2/items", 3, PAGE_SIZE, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"page[number]": 3, "page[size]": PAGE_SIZE}+++class TestHeaders:+ def test_basic_auth_uses_api_key_as_username_with_blank_password(self) -> None:+ headers = opinion_stage._headers("secret-key")+ # HTTP Basic: base64("secret-key:") — the API key is the username, password is blank.+ assert headers["Authorization"] == "Basic c2VjcmV0LWtleTo="+ assert headers["Accept"] == "application/vnd.api+json"+++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(opinion_stage, "make_tracked_session", lambda **kwargs: session)+ return session++ @pytest.mark.parametrize(+ "status, ok, expected_status, expected_message",+ [+ (200, True, 200, None),+ (401, False, 401, None),+ (403, False, 403, None),+ (500, False, 500, "Opinion Stage returned HTTP 500"),+ ],+ )+ def test_status_mapping(+ self, status: int, ok: bool, expected_status: int, expected_message: str | None, monkeypatch: Any+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ self._patch_session(monkeypatch, response)+ assert check_access("os-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("os-key")+ assert status == 0+ assert message is not None and "boom" in message+++class TestOpinionStageSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = opinion_stage_source(+ api_key="os-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # JSON:API items carry no guaranteed stable creation timestamp column, so we don't partition.+ assert response.partition_mode is None++ def test_every_endpoint_uses_id_primary_key(self) -> None:+ assert all(config.primary_keys == ["id"] for config in OPINION_STAGE_ENDPOINTS.values())+ assert set(OPINION_STAGE_ENDPOINTS) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/tests/test_opinion_stage_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/tests/test_opinion_stage_source.pynew file mode 100644index 000000000000..3ab5a0944c12--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/tests/test_opinion_stage_source.py@@ -0,0 +1,158 @@+import pytest+from unittest import mock++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 OpinionStageSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.opinion_stage.opinion_stage import (+ OpinionStageResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.opinion_stage.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.opinion_stage.source import OpinionStageSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestOpinionStageSource:+ def setup_method(self) -> None:+ self.source = OpinionStageSource()+ self.team_id = 123+ self.config = OpinionStageSourceConfig(api_key="os-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.OPINIONSTAGE++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "OpinionStage"+ assert config.label == "Opinion Stage"+ 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/opinion-stage"++ 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 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)+ # The documented date filter has no OpenAPI parameter names, 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=["items"])+ assert len(schemas) == 1+ assert schemas[0].name == "items"++ 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)++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.opinionstage.com/api/v2/items?page%5Bnumber%5D=1",+ "403 Client Error: Forbidden for url: https://api.opinionstage.com/api/v2/items?page%5Bnumber%5D=2",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @pytest.mark.parametrize(+ "unrelated_error",+ [+ "500 Server Error: Internal Server Error for url: https://api.opinionstage.com/api/v2/items",+ "HTTPSConnectionPool(host='api.opinionstage.com', port=443): Read timed out.",+ "429 Client Error: Too Many Requests for url: https://api.opinionstage.com/api/v2/items",+ ],+ )+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @pytest.mark.parametrize(+ "status, expected_valid, expected_message",+ [+ (200, True, None),+ (401, False, "Invalid Opinion Stage API key"),+ (403, False, "Invalid Opinion Stage API key"),+ (500, False, "Opinion Stage returned HTTP 500"),+ (0, False, "Could not connect to Opinion Stage: boom"),+ ],+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.opinion_stage.source.check_access")+ def test_validate_credentials(+ self,+ mock_check: mock.MagicMock,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ ) -> None:+ message = (+ "Opinion Stage returned HTTP 500"+ if status == 500+ else ("Could not connect to Opinion Stage: 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.opinion_stage.source.check_access")+ def test_validate_credentials_probes_the_account_key(self, mock_check: mock.MagicMock) -> None:+ # The personal 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="items")+ mock_check.assert_called_once_with("os-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 OpinionStageResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.opinion_stage.source.opinion_stage_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "items"+ 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"] == "os-key"+ assert kwargs["endpoint"] == "items"+ 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 Opinion Stage schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)