: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 buzzsprout import source (#66727)
Tom Owers980fac7ca317
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 0e50b093f8e1..1429c6dccbb4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -74,6 +74,7 @@ the row lists both.| bugsnag | HTTP | requests | ✅ || buildbetter | HTTP | requests | ✅ || buildkite | HTTP | requests | ✅ |+| buzzsprout | HTTP | requests | ✅ || calendly | HTTP | requests | ✅ || campaign_monitor | HTTP | requests | ✅ || campayn | HTTP | requests | ✅ |@@ -332,7 +333,6 @@ doesn't conflict with concurrent PRs.- branch- breezy_hr- bunny-- buzzsprout- cal_com- callrail- campaign_manager_360diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/buzzsprout.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/buzzsprout.pynew file mode 100644index 000000000000..2645d427f213--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/buzzsprout.py@@ -0,0 +1,125 @@+from collections.abc import Iterator+from typing import Any++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.buzzsprout.settings import (+ BUZZSPROUT_ENDPOINTS,+ BuzzsproutEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session++BUZZSPROUT_BASE_URL = "https://www.buzzsprout.com/api"++# Buzzsprout blocks requests sent with a default/bot User-Agent, so we identify ourselves explicitly.+USER_AGENT = "PostHog Data Warehouse (https://posthog.com)"++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRY_ATTEMPTS = 5+++class BuzzsproutRetryableError(Exception):+ pass+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Token token={api_token}",+ "User-Agent": USER_AGENT,+ "Accept": "application/json",+ }+++def _build_url(podcast_id: str, config: BuzzsproutEndpointConfig) -> str:+ if config.account_scoped:+ return f"{BUZZSPROUT_BASE_URL}/{config.path}"+ return f"{BUZZSPROUT_BASE_URL}/{podcast_id.strip()}/{config.path}"+++@retry(+ retry=retry_if_exception_type((BuzzsproutRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> list[dict[str, Any]]:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ # Buzzsprout's docs recommend retrying on transient 5xx; 429 is retried too should rate limiting+ # ever be introduced (none is documented today).+ if response.status_code == 429 or response.status_code >= 500:+ raise BuzzsproutRetryableError(f"Buzzsprout API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # Only the status and URL are logged — the upstream response body can carry account-specific+ # data (private episode metadata, emails) that must not be copied into PostHog logs.+ logger.error(f"Buzzsprout API error: status={response.status_code}, url={url}")+ response.raise_for_status()++ data = response.json()+ # Every documented Buzzsprout endpoint returns a bare JSON array.+ return data if isinstance(data, list) else []+++def validate_credentials(api_token: str, podcast_id: str) -> tuple[bool, str | None]:+ podcast_id = podcast_id.strip()+ if not podcast_id:+ return False, "A Buzzsprout podcast ID is required."++ # The episodes endpoint is scoped to the podcast_id, so a 200 confirms both the token and the ID+ # in a single cheap probe.+ url = f"{BUZZSPROUT_BASE_URL}/{podcast_id}/episodes.json"+ try:+ response = make_tracked_session(redact_values=(api_token,)).get(+ url, headers=_get_headers(api_token), timeout=REQUEST_TIMEOUT_SECONDS+ )+ except Exception:+ return False, "Could not reach the Buzzsprout API. Please try again."++ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return False, "Invalid Buzzsprout API token. Create a new token in your Buzzsprout account settings."+ if response.status_code == 404:+ return False, "Buzzsprout podcast not found. Check the podcast ID."+ # A transient 429/5xx (after the session's own retries are exhausted) is not a credential problem,+ # so surface it as a retryable condition rather than rejecting otherwise-valid credentials.+ if response.status_code == 429 or response.status_code >= 500:+ return False, "Buzzsprout API is temporarily unavailable. Please try again in a moment."++ return False, f"Buzzsprout API returned an unexpected status code: {response.status_code}"+++def get_rows(+ api_token: str, podcast_id: str, endpoint: str, logger: FilteringBoundLogger+) -> Iterator[list[dict[str, Any]]]:+ config = BUZZSPROUT_ENDPOINTS[endpoint]+ session = make_tracked_session(redact_values=(api_token,))+ url = _build_url(podcast_id, config)++ # Buzzsprout has no pagination: each endpoint returns its full array in one response, so a single+ # fetch is the whole table. The pipeline batches the yielded list for us.+ rows = _fetch(session, url, _get_headers(api_token), logger)+ if rows:+ yield rows+++def buzzsprout_source(api_token: str, podcast_id: str, endpoint: str, logger: FilteringBoundLogger) -> SourceResponse:+ config = BUZZSPROUT_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(api_token=api_token, podcast_id=podcast_id, endpoint=endpoint, logger=logger),+ 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,+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/canonical_descriptions.pynew file mode 100644index 000000000000..b27f4bcdc4b6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/canonical_descriptions.py@@ -0,0 +1,56 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Sourced from the official Buzzsprout API docs: https://github.com/Buzzsprout/buzzsprout-api+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "episodes": {+ "description": "Every episode for the configured podcast, including publishing metadata and play counts.",+ "docs_url": "https://github.com/Buzzsprout/buzzsprout-api/blob/master/sections/episodes.md",+ "columns": {+ "id": "Unique identifier for the episode.",+ "title": "Episode title.",+ "audio_url": "URL of the episode's audio file.",+ "artwork_url": "URL of the episode's artwork image.",+ "description": "Full episode description (may contain HTML).",+ "summary": "Short episode summary.",+ "artist": "Artist/author name shown for the episode.",+ "tags": "Comma-separated tags applied to the episode.",+ "published_at": "ISO 8601 timestamp the episode was (or is scheduled to be) published.",+ "duration": "Episode length in seconds.",+ "hq": "Whether the episode audio is high quality.",+ "magic_mastering": "Whether Buzzsprout Magic Mastering audio post-processing is enabled.",+ "guid": "Globally unique RSS feed identifier for the episode.",+ "inactive_at": "ISO 8601 timestamp the episode was deactivated, or null if active.",+ "episode_number": "Episode number within its season.",+ "season_number": "Season number the episode belongs to.",+ "explicit": "Whether the episode is marked as explicit.",+ "private": "Whether the episode is private (not published to public feeds).",+ "total_plays": "Cumulative number of plays for the episode.",+ },+ },+ "podcasts": {+ "description": "Podcasts the API token can access, with their channel-level metadata.",+ "docs_url": "https://github.com/Buzzsprout/buzzsprout-api/blob/master/sections/podcasts.md",+ "columns": {+ "id": "Unique identifier for the podcast.",+ "title": "Podcast title.",+ "author": "Podcast author/owner name.",+ "description": "Podcast description.",+ "website_address": "Podcast website URL.",+ "contact_email": "Contact email for the podcast.",+ "keywords": "Comma-separated keywords for the podcast.",+ "explicit": "Whether the podcast is marked as explicit.",+ "main_category": "Primary Apple Podcasts category.",+ "sub_category": "Primary Apple Podcasts subcategory.",+ "main_category2": "Second Apple Podcasts category.",+ "sub_category2": "Second Apple Podcasts subcategory.",+ "main_category3": "Third Apple Podcasts category.",+ "sub_category3": "Third Apple Podcasts subcategory.",+ "language": "Podcast language code.",+ "timezone": "Podcast timezone.",+ "artwork_url": "URL of the podcast artwork image.",+ "background_url": "URL of the podcast background image.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/settings.pynew file mode 100644index 000000000000..0fb3d567e23b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/settings.py@@ -0,0 +1,49 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField+++@dataclass+class BuzzsproutEndpointConfig:+ name: str+ # Path suffix after the (optional) podcast_id segment, e.g. "episodes.json". Buzzsprout requires+ # the ".json" extension — a missing/other extension returns 415 Unsupported Media Type.+ path: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation-time datetime column used for partitioning. Never an `updated_at`-style field.+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ should_sync_default: bool = True+ # Account-scoped endpoints are called without the podcast_id path segment (e.g. /api/podcasts.json).+ account_scoped: bool = False+ description: Optional[str] = None+++# Buzzsprout's v1 API exposes two list resources, both returning the full unpaginated array on every+# request with no server-side timestamp filter — so both are full refresh only.+BUZZSPROUT_ENDPOINTS: dict[str, BuzzsproutEndpointConfig] = {+ "episodes": BuzzsproutEndpointConfig(+ name="episodes",+ path="episodes.json",+ # `published_at` is the episode's publication time; it doesn't move once set, so it's a stable+ # partition key (unlike play counts or edit timestamps).+ partition_key="published_at",+ description="Every episode for the configured podcast. Full refresh — Buzzsprout returns the "+ "complete list on each request and exposes no server-side incremental filter.",+ ),+ "podcasts": BuzzsproutEndpointConfig(+ name="podcasts",+ path="podcasts.json",+ # Account-scoped: returns every podcast the API token can access, so it omits the podcast_id+ # path segment. No datetime field to partition on.+ account_scoped=True,+ description="Podcasts the API token can access, with their metadata. Full refresh.",+ ),+}++ENDPOINTS = tuple(BUZZSPROUT_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in BUZZSPROUT_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/source.pyindex 0fded26d94a9..f14208e5e5dc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/source.py@@ -1,19 +1,41 @@-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.buzzsprout.buzzsprout import (+ buzzsprout_source,+ validate_credentials as validate_buzzsprout_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.buzzsprout.settings import (+ BUZZSPROUT_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BuzzsproutSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass BuzzsproutSource(SimpleSource[BuzzsproutSourceConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.BUZZSPROUT@@ -24,7 +46,88 @@ class BuzzsproutSource(SimpleSource[BuzzsproutSourceConfig]):name=SchemaExternalDataSourceType.BUZZSPROUT,category=DataWarehouseSourceCategory.MARKETING___EMAIL,label="Buzzsprout",- iconPath="/static/services/buzzsprout.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Buzzsprout API token and podcast ID to sync your podcast data into the PostHog Data warehouse.++You can find both your API token and podcast ID in your [Buzzsprout API settings](https://www.buzzsprout.com/my/profile/api).""",+ iconPath="/static/services/buzzsprout.png",+ docsUrl="https://posthog.com/docs/cdp/sources/buzzsprout",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="podcast_id",+ label="Podcast ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="123456",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.buzzsprout.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 token surfaces as a requests HTTPError when `_fetch` calls+ # `raise_for_status()`. Retrying can never satisfy a credential problem. Match the stable+ # status text and base host, not the per-request path.+ "401 Client Error: Unauthorized for url: https://www.buzzsprout.com": "Your Buzzsprout API token is invalid or has been revoked. Create a new token in your Buzzsprout account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://www.buzzsprout.com": "Your Buzzsprout API token does not have access to this podcast. Check the token and podcast ID, then reconnect.",+ }++ def get_schemas(+ self,+ config: BuzzsproutSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ # Buzzsprout returns the full array on every request with no server-side timestamp+ # filter, so an "incremental" sync would cost the same as a full refresh. Ship full+ # refresh only — merge on the primary key keeps mutable fields (e.g. total_plays) fresh.+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=BUZZSPROUT_ENDPOINTS[endpoint].should_sync_default,+ description=BUZZSPROUT_ENDPOINTS[endpoint].description,+ )+ 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: BuzzsproutSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_buzzsprout_credentials(config.api_token, config.podcast_id)++ def source_for_pipeline(self, config: BuzzsproutSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return buzzsprout_source(+ api_token=config.api_token,+ podcast_id=config.podcast_id,+ endpoint=inputs.schema_name,+ logger=inputs.logger,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/tests/test_buzzsprout.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/tests/test_buzzsprout.pynew file mode 100644index 000000000000..9640cca5fb52--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/tests/test_buzzsprout.py@@ -0,0 +1,272 @@+import json+from typing import Any, Optional++import pytest+from unittest import mock++import requests+import tenacity+import structlog++from products.warehouse_sources.backend.temporal.data_imports.sources.buzzsprout.buzzsprout import (+ BUZZSPROUT_BASE_URL,+ USER_AGENT,+ BuzzsproutRetryableError,+ _build_url,+ _fetch,+ _get_headers,+ buzzsprout_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.buzzsprout.settings import (+ BUZZSPROUT_ENDPOINTS,+ ENDPOINTS,+)++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.buzzsprout.buzzsprout"+++def _response(status: int = 200, body: Optional[Any] = None) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.status_code = status+ resp.ok = 200 <= status < 300+ resp.json.return_value = body if body is not None else []+ resp.text = json.dumps(body if body is not None else [])+ if not resp.ok:+ reason = "Unauthorized" if status == 401 else "Forbidden" if status == 403 else "Error"+ resp.raise_for_status.side_effect = requests.HTTPError(+ f"{status} Client Error: {reason} for url: {BUZZSPROUT_BASE_URL}/123456/episodes.json",+ response=requests.Response(),+ )+ return resp+++class TestGetHeaders:+ def test_token_and_user_agent(self):+ headers = _get_headers("abc123")++ # Buzzsprout's documented auth scheme is a static account token in the Authorization header.+ assert headers["Authorization"] == "Token token=abc123"+ # A non-default User-Agent is mandatory or Buzzsprout may block the request.+ assert headers["User-Agent"] == USER_AGENT+++class TestBuildUrl:+ def test_podcast_scoped_includes_id(self):+ url = _build_url("123456", BUZZSPROUT_ENDPOINTS["episodes"])++ assert url == f"{BUZZSPROUT_BASE_URL}/123456/episodes.json"++ def test_account_scoped_omits_id(self):+ # The podcasts endpoint is account-scoped, so the podcast_id must not appear in the path.+ url = _build_url("123456", BUZZSPROUT_ENDPOINTS["podcasts"])++ assert url == f"{BUZZSPROUT_BASE_URL}/podcasts.json"+ assert "123456" not in url++ def test_surrounding_whitespace_is_stripped(self):+ url = _build_url(" 123456 ", BUZZSPROUT_ENDPOINTS["episodes"])++ assert url == f"{BUZZSPROUT_BASE_URL}/123456/episodes.json"+++# tenacity exposes the undecorated function via `__wrapped__`, so status classification can be+# asserted without waiting through retry backoff.+_fetch_once = _fetch.__wrapped__ # type: ignore[attr-defined]+++class TestFetch:+ def test_ok_returns_array(self):+ session = mock.MagicMock()+ session.get.return_value = _response(200, [{"id": 1}, {"id": 2}])++ assert _fetch_once(session, "https://example.com", {}, structlog.get_logger()) == [{"id": 1}, {"id": 2}]++ def test_non_list_body_returns_empty(self):+ # Every documented endpoint returns a bare array; defend against an unexpected object body.+ session = mock.MagicMock()+ session.get.return_value = _response(200, {"unexpected": "object"})++ assert _fetch_once(session, "https://example.com", {}, structlog.get_logger()) == []++ @pytest.mark.parametrize("status", [429, 500, 502, 503, 504])+ def test_retryable_statuses_raise_retryable(self, status):+ session = mock.MagicMock()+ session.get.return_value = _response(status)++ with pytest.raises(BuzzsproutRetryableError):+ _fetch_once(session, "https://example.com", {}, structlog.get_logger())++ @pytest.mark.parametrize("status", [400, 401, 403, 404])+ def test_client_errors_raise_for_status(self, status):+ session = mock.MagicMock()+ session.get.return_value = _response(status)++ with pytest.raises(requests.HTTPError):+ _fetch_once(session, "https://example.com", {}, structlog.get_logger())++ def test_retries_transient_status_then_succeeds(self):+ # Drive the real tenacity decorator (not `__wrapped__`) with no backoff to confirm a transient+ # error is retried rather than re-raised on the first attempt.+ fast_fetch = tenacity.retry(+ retry=tenacity.retry_if_exception_type(+ (BuzzsproutRetryableError, requests.ReadTimeout, requests.ConnectionError)+ ),+ stop=tenacity.stop_after_attempt(5),+ wait=tenacity.wait_none(),+ reraise=True,+ )(_fetch_once)++ session = mock.MagicMock()+ session.get.side_effect = [_response(500), _response(200, [{"id": 1}])]++ result = fast_fetch(session, "https://example.com", {}, structlog.get_logger())++ assert result == [{"id": 1}]+ assert session.get.call_count == 2+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status, expected_valid",+ [+ (200, True),+ (401, False),+ (403, False),+ (404, False),+ (500, False),+ ],+ )+ def test_status_mapping(self, status, expected_valid):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(status)++ is_valid, _ = validate_credentials("test-token", "123456")++ assert is_valid is expected_valid++ def test_blank_podcast_id_is_invalid_without_request(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ is_valid, message = validate_credentials("test-token", " ")++ assert is_valid is False+ assert message is not None+ mock_session.return_value.get.assert_not_called()++ def test_network_error_is_invalid(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = Exception("boom")++ is_valid, message = validate_credentials("test-token", "123456")++ assert is_valid is False+ assert message is not None++ def test_probes_episodes_with_podcast_id_and_headers(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200)++ validate_credentials("test-token", "123456")++ call = mock_session.return_value.get.call_args++ assert call.args[0] == f"{BUZZSPROUT_BASE_URL}/123456/episodes.json"+ assert call.kwargs["headers"]["Authorization"] == "Token token=test-token"++ def test_surrounding_whitespace_in_podcast_id_is_stripped(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200)++ validate_credentials("test-token", " 123456 ")++ call = mock_session.return_value.get.call_args++ assert call.args[0] == f"{BUZZSPROUT_BASE_URL}/123456/episodes.json"++ @pytest.mark.parametrize("status", [429, 500, 503])+ def test_transient_status_is_distinguished_from_invalid_credentials(self, status):+ # A 429/5xx (after the session's own retries) is a temporary outage, not a credential problem,+ # so the message must steer the user to retry rather than recreate their token.+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(status)++ is_valid, message = validate_credentials("test-token", "123456")++ assert is_valid is False+ assert message is not None+ assert "temporarily unavailable" in message++ def test_token_is_redacted_in_tracked_session(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200)++ validate_credentials("secret-token", "123456")++ assert mock_session.call_args.kwargs["redact_values"] == ("secret-token",)+++class TestGetRows:+ def test_yields_single_batch_with_full_array(self):+ # Buzzsprout has no pagination, so a single fetch returns the whole table in one batch.+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200, [{"id": 1}, {"id": 2}])++ batches = list(get_rows("test-token", "123456", "episodes", structlog.get_logger()))++ called_url = mock_session.return_value.get.call_args.args[0]++ assert batches == [[{"id": 1}, {"id": 2}]]+ assert called_url == f"{BUZZSPROUT_BASE_URL}/123456/episodes.json"++ def test_skips_empty_response(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200, [])++ batches = list(get_rows("test-token", "123456", "episodes", structlog.get_logger()))++ assert batches == []++ def test_podcasts_endpoint_omits_podcast_id(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200, [{"id": 9}])++ list(get_rows("test-token", "123456", "podcasts", structlog.get_logger()))++ called_url = mock_session.return_value.get.call_args.args[0]++ assert called_url == f"{BUZZSPROUT_BASE_URL}/podcasts.json"++ def test_token_is_redacted_in_tracked_session(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200, [{"id": 1}])++ list(get_rows("secret-token", "123456", "episodes", structlog.get_logger()))++ assert mock_session.call_args.kwargs["redact_values"] == ("secret-token",)+++class TestBuzzsproutSource:+ def test_episodes_partitions_on_stable_published_at(self):+ response = buzzsprout_source("test-token", "123456", "episodes", structlog.get_logger())++ assert response.name == "episodes"+ assert response.primary_keys == ["id"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["published_at"]+ assert response.sort_mode == "asc"++ def test_podcasts_is_unpartitioned(self):+ # Podcasts carry no stable datetime field, so no datetime partitioning is applied.+ response = buzzsprout_source("test-token", "123456", "podcasts", structlog.get_logger())++ assert response.name == "podcasts"+ assert response.primary_keys == ["id"]+ assert response.partition_mode is None+ assert response.partition_keys is None++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_source_response_names_match_endpoints(self, endpoint):+ response = buzzsprout_source("test-token", "123456", endpoint, structlog.get_logger())++ assert response.name == endpointdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/tests/test_buzzsprout_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/tests/test_buzzsprout_source.pynew file mode 100644index 000000000000..b556d879b429--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buzzsprout/tests/test_buzzsprout_source.py@@ -0,0 +1,137 @@+import pytest+from unittest import mock++import structlog++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.buzzsprout.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.buzzsprout.source import BuzzsproutSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BuzzsproutSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(schema_name: str = "episodes") -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=123,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job-id",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+++class TestBuzzsproutSource:+ def setup_method(self):+ self.source = BuzzsproutSource()+ self.team_id = 123+ self.config = BuzzsproutSourceConfig(api_token="test-token", podcast_id="123456")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.BUZZSPROUT++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Buzzsprout"+ assert config.label == "Buzzsprout"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/buzzsprout.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/buzzsprout"++ def test_get_source_config_fields(self):+ fields = self.source.get_source_config.fields++ by_name = {field.name: field for field in fields if isinstance(field, SourceFieldInputConfig)}+ assert set(by_name) == {"api_token", "podcast_id"}++ token_field = by_name["api_token"]+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.required is True+ assert token_field.secret is True++ podcast_field = by_name["podcast_id"]+ assert podcast_field.type == SourceFieldInputConfigType.TEXT+ assert podcast_field.required is True+ # The podcast ID is not a secret — it scopes the URL but grants no access on its own.+ assert podcast_field.secret is False++ def test_get_schemas_lists_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_get_schemas_full_refresh_only(self, endpoint):+ # Buzzsprout has no server-side timestamp filter, so every endpoint is full refresh only.+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas[endpoint].supports_incremental is False+ assert schemas[endpoint].supports_append is False++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["episodes"])++ assert [schema.name for schema in schemas] == ["episodes"]++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []++ def test_non_retryable_errors_include_auth_failures(self):+ errors = self.source.get_non_retryable_errors()++ assert any("401 Client Error: Unauthorized" in key for key in errors)+ assert any("403 Client Error: Forbidden" in key for key in errors)+ # The match must be anchored to the Buzzsprout host so unrelated 401s don't trip it.+ assert all("https://www.buzzsprout.com" in key for key in errors)++ def test_canonical_descriptions_cover_every_endpoint(self):+ descriptions = self.source.get_canonical_descriptions()++ assert set(descriptions) == set(ENDPOINTS)++ def test_lists_tables_without_credentials(self):+ # The static endpoint catalog has no I/O, so the public docs table list opts in.+ assert self.source.lists_tables_without_credentials is True+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ ((True, None), True, None),+ ((False, "Invalid Buzzsprout API token"), False, "Invalid Buzzsprout API token"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.buzzsprout.source.validate_buzzsprout_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id, "episodes")++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with(self.config.api_token, self.config.podcast_id)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.buzzsprout.source.buzzsprout_source")+ def test_source_for_pipeline_plumbs_args(self, mock_buzzsprout_source):+ inputs = _make_inputs(schema_name="podcasts")++ self.source.source_for_pipeline(self.config, inputs)++ mock_buzzsprout_source.assert_called_once_with(+ api_token="test-token",+ podcast_id="123456",+ endpoint="podcasts",+ logger=inputs.logger,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 06c9b58288d4..adede6289c7f 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@@ -525,7 +525,8 @@ class BunnySourceConfig(config.Config):@config.configclass BuzzsproutSourceConfig(config.Config):- pass+ api_token: str+ podcast_id: str@config.config