: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 guardian import source (#67788)
Tom Owersb12d251c8d5a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 69868d858aba..a8f4ceb8546c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -163,6 +163,7 @@ the row lists both.| granola | HTTP | requests | ✅ || gorgias | HTTP | requests | ✅ || greenhouse | HTTP | requests | ✅ |+| guardian | HTTP | requests | ✅ || guru | HTTP | requests | ✅ || hibob | HTTP | requests | ✅ || hubspot | HTTP | requests | ✅ |@@ -436,7 +437,6 @@ doesn't conflict with concurrent PRs.- grafana- greythr- gridly-- guardian- gusto- harness- heapdiff --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 3b2e272f3acd..8773588d895e 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@@ -1482,7 +1482,7 @@ class GridlySourceConfig(config.Config):@config.configclass GuardianSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/canonical_descriptions.pynew file mode 100644index 000000000000..1ecacc0914e0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/canonical_descriptions.py@@ -0,0 +1,70 @@+"""Canonical, documentation-sourced descriptions for Guardian Open Platform endpoints and columns.++Sourced from the official Guardian Open Platform docs (https://open-platform.theguardian.com/documentation/).+Keyed by the endpoint names in `settings.py` `GUARDIAN_ENDPOINTS`, matching each synced table's+`ExternalDataSchema.name`. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "content": {+ "description": "A piece of Guardian content (article, liveblog, gallery, etc.) returned by the search endpoint.",+ "docs_url": "https://open-platform.theguardian.com/documentation/search",+ "columns": {+ "id": "The path to content, and its unique identifier (e.g. 'world/2026/jul/02/...').",+ "type": "The content type (e.g. article, liveblog, gallery, video, interactive).",+ "sectionId": "Identifier of the section the content belongs to.",+ "sectionName": "Display name of the section the content belongs to.",+ "webPublicationDate": "The combined date and time of publication (ISO 8601).",+ "webTitle": "The headline of the content.",+ "webUrl": "The URL of the content on theguardian.com.",+ "apiUrl": "The URL of the content in the Content API.",+ "fields": "Additional content fields requested via show-fields (headline, body, byline, wordcount, thumbnail, etc.).",+ "tags": "Tags associated with the content (keywords, contributors, series, tone, etc.).",+ "references": "External references associated with the content (e.g. ISBNs, IMDB ids).",+ "isHosted": "Whether the content is hosted (paid/commercial) content.",+ "pillarId": "Identifier of the pillar the content sits under (e.g. pillar/news).",+ "pillarName": "Display name of the pillar the content sits under (e.g. News, Sport).",+ },+ },+ "tags": {+ "description": "A Guardian tag used to categorize content — keywords, contributors, series, tones, and more.",+ "docs_url": "https://open-platform.theguardian.com/documentation/tag",+ "columns": {+ "id": "The unique identifier of the tag (its path).",+ "type": "The tag type (e.g. keyword, contributor, series, tone, type, publication).",+ "sectionId": "Identifier of the section the tag is associated with, if any.",+ "sectionName": "Display name of the section the tag is associated with, if any.",+ "webTitle": "The display name of the tag.",+ "webUrl": "The URL of the tag's page on theguardian.com.",+ "apiUrl": "The URL of the tag in the Content API.",+ "keywordType": "For keyword tags, the more specific keyword classification.",+ },+ },+ "sections": {+ "description": "A Guardian section grouping related content (e.g. World news, Football, Technology).",+ "docs_url": "https://open-platform.theguardian.com/documentation/section",+ "columns": {+ "id": "The unique identifier of the section.",+ "webTitle": "The display name of the section.",+ "webUrl": "The URL of the section's page on theguardian.com.",+ "apiUrl": "The URL of the section in the Content API.",+ "editions": "The editions in which this section appears.",+ },+ },+ "editions": {+ "description": "A regional Guardian edition (e.g. UK, US, Australia, International).",+ "docs_url": "https://open-platform.theguardian.com/documentation/edition",+ "columns": {+ "id": "The unique identifier of the edition.",+ "path": "The path of the edition's front page.",+ "edition": "The short code of the edition (e.g. UK, US, AU).",+ "webTitle": "The display name of the edition.",+ "webUrl": "The URL of the edition's front page on theguardian.com.",+ "apiUrl": "The URL of the edition in the Content API.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/guardian.py b/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/guardian.pynew file mode 100644index 000000000000..80308512b8ee--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/guardian.py@@ -0,0 +1,205 @@+import dataclasses+from collections.abc import Iterator+from datetime import date, datetime+from typing import Any, Optional+from urllib.parse import urlencode, urlsplit, urlunsplit++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.guardian.settings import (+ GUARDIAN_ENDPOINTS,+ GuardianEndpointConfig,+)++GUARDIAN_BASE_URL = "https://content.guardianapis.com"++# The free developer tier caps page-size at 200; larger values are rejected.+PAGE_SIZE = 200++REQUEST_TIMEOUT_SECONDS = 60+++class GuardianRetryableError(Exception):+ pass+++class GuardianResumeConfig:+ # The next page number to fetch. The API is 1-indexed. With `order-by=oldest` the result set is+ # ordered ascending and stable within a run, so a page number is a safe resume cursor.+ page: int = 1+++def _headers() -> dict[str, str]:+ return {"Accept": "application/json"}+++def _format_from_date(value: Any) -> str | None:+ """Map the incremental cursor to the API's day-granular `from-date` (YYYY-MM-DD).++ The Guardian only filters by calendar date, not by time, so an incremental sync re-fetches the+ watermark day. Those re-pulled rows dedupe on the `id` primary key at merge time.+ """+ if isinstance(value, datetime):+ return value.date().isoformat()+ if isinstance(value, date):+ return value.isoformat()+ if isinstance(value, str) and value:+ # Cursor persisted as an ISO string (e.g. "2026-07-02T13:12:10Z"); keep the date part.+ return value[:10]+ return None+++def _build_base_params(+ config: GuardianEndpointConfig,+ api_key: str,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, str]:+ params: dict[str, str] = {+ "api-key": api_key,+ "page-size": str(PAGE_SIZE),+ "format": "json",+ **config.extra_params,+ }++ if config.supports_incremental and should_use_incremental_field:+ from_date = _format_from_date(db_incremental_field_last_value)+ if from_date:+ params["from-date"] = from_date++ return params+++def _build_url(path: str, params: dict[str, str]) -> str:+ return f"{GUARDIAN_BASE_URL}{path}?{urlencode(params)}"+++def _scrub_url(url: str | None) -> str:+ # The api-key rides in the query string, so strip the query before the URL reaches any error+ # message or log line — otherwise a non-2xx response would leak the credential into job errors.+ if not url:+ return GUARDIAN_BASE_URL+ parts = urlsplit(url)+ return urlunsplit((parts.scheme, parts.netloc, parts.path, "", ""))+++@retry(+ retry=retry_if_exception_type(+ (+ GuardianRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:+ response = session.get(url, headers=_headers(), timeout=REQUEST_TIMEOUT_SECONDS)++ # 429 (rate limit — the free tier caps ~12 req/s and a daily quota) and 5xx are transient.+ if response.status_code == 429 or response.status_code >= 500:+ raise GuardianRetryableError(f"Guardian API error (retryable): status={response.status_code}")++ if not response.ok:+ logger.error(f"Guardian API error: status={response.status_code}, body={response.text}, url={_scrub_url(url)}")+ # Raise with the api-key scrubbed from the URL rather than calling raise_for_status(), whose+ # message embeds the full credential-bearing URL. The base host stays intact so+ # `get_non_retryable_errors()` can still match on it.+ raise requests.HTTPError(+ f"{response.status_code} Client Error: {response.reason} for url: {_scrub_url(response.url)}",+ response=response,+ )++ return response.json()+++def validate_credentials(api_key: str) -> bool:+ # /sections is a cheap, single-response endpoint — a genuine key returns 200, a bad one 401.+ url = _build_url("/sections", {"api-key": api_key, "page-size": "1"})+ try:+ # The api-key rides in the query string, so redact it from logged URLs and captured samples.+ response = make_tracked_session(redact_values=(api_key,)).get(url, headers=_headers(), timeout=10)+ return response.status_code == 200+ except Exception:+ return False+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GuardianResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = GUARDIAN_ENDPOINTS[endpoint]+ # One session reused across pages so urllib3 keeps the connection alive. The api-key lives in the+ # query string, so redact it from logged URLs and captured samples.+ session = make_tracked_session(redact_values=(api_key,))++ base_params = _build_base_params(config, api_key, should_use_incremental_field, db_incremental_field_last_value)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.page if resume else 1++ while True:+ url = _build_url(config.path, {**base_params, "page": str(page)})+ response = _fetch_page(session, url, logger)["response"]++ results = response.get("results", [])+ if results:+ yield results++ # `sections` / `editions` return every row in one response with no pagination metadata,+ # so default to a single page. `search` / `tags` report `pages` and `currentPage`.+ total_pages = response.get("pages", 1)+ current_page = response.get("currentPage", page)+ if current_page >= total_pages:+ break++ page = current_page + 1+ # Save AFTER yielding so a crash re-fetches (and merge-dedupes) the last page rather than+ # skipping it. We persist the next page to fetch.+ resumable_source_manager.save_state(GuardianResumeConfig(page=page))+++def guardian_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GuardianResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = GUARDIAN_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ 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,+ # Only `content` guarantees an order: `order-by=oldest` returns ascending `webPublicationDate`,+ # matching the watermark direction. The full-refresh reference endpoints have no `order-by`, so+ # their row order is unspecified — leave `sort_mode` unset rather than claim ascending.+ sort_mode="asc" if config.supports_incremental else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/settings.pynew file mode 100644index 000000000000..b946d75e3cc5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/settings.py@@ -0,0 +1,72 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class GuardianEndpointConfig:+ name: str+ path: str+ incremental_fields: list[IncrementalField]+ # Stable publication timestamp used both as the incremental cursor and the partition key.+ # `webPublicationDate` never changes once an article is published, so it's safe to partition on.+ partition_key: Optional[str] = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+ # Extra query params always sent for this endpoint (e.g. field/tag selectors for richer payloads).+ extra_params: dict[str, str] = field(default_factory=dict)+ # Only the /search endpoint honors from-date/order-by=oldest as a server-side forward cursor.+ supports_incremental: bool = False+++# The Guardian Open Platform Content API (https://open-platform.theguardian.com/documentation/).+# `content` is the primary stream (news articles etc.); `tags`, `sections` and `editions` are the+# supporting reference catalogs that content rows reference by id.+GUARDIAN_ENDPOINTS: dict[str, GuardianEndpointConfig] = {+ "content": GuardianEndpointConfig(+ name="content",+ path="/search",+ partition_key="webPublicationDate",+ supports_incremental=True,+ # `show-fields=all` / `show-tags=all` pull the article body, byline, wordcount, associated+ # tags etc. that the API omits by default. `order-by=oldest` + `order-date=published` yields+ # ascending `webPublicationDate` order so the incremental watermark advances correctly.+ extra_params={+ "show-fields": "all",+ "show-tags": "all",+ "show-references": "all",+ "order-by": "oldest",+ "order-date": "published",+ },+ incremental_fields=[+ {+ "label": "webPublicationDate",+ "type": IncrementalFieldType.DateTime,+ "field": "webPublicationDate",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "tags": GuardianEndpointConfig(+ name="tags",+ path="/tags",+ incremental_fields=[],+ ),+ "sections": GuardianEndpointConfig(+ name="sections",+ path="/sections",+ incremental_fields=[],+ ),+ "editions": GuardianEndpointConfig(+ name="editions",+ path="/editions",+ incremental_fields=[],+ ),+}++ENDPOINTS = tuple(GUARDIAN_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in GUARDIAN_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/source.pyindex 3399f413688e..ede7b8e1367e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/source.py@@ -1,19 +1,43 @@-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 GuardianSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.guardian.guardian import (+ GuardianResumeConfig,+ guardian_source,+ validate_credentials as validate_guardian_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.guardian.settings import (+ ENDPOINTS,+ GUARDIAN_ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class GuardianSource(SimpleSource[GuardianSourceConfig]):+class GuardianSource(ResumableSource[GuardianSourceConfig, GuardianResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GUARDIAN@@ -24,7 +48,93 @@ class GuardianSource(SimpleSource[GuardianSourceConfig]):name=SchemaExternalDataSourceType.GUARDIAN,category=DataWarehouseSourceCategory.ANALYTICS,label="The Guardian",- iconPath="/static/services/guardian.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Guardian Open Platform API key to pull Guardian news content into the PostHog Data warehouse.++You can request a free developer key from the [Guardian Open Platform](https://open-platform.theguardian.com/access/). Free keys are rate-limited (~12 requests/second, ~5,000 requests/day), so an initial backfill of the full content archive can take a while.+""",+ iconPath="/static/services/guardian.png",+ docsUrl="https://posthog.com/docs/cdp/sources/guardian",+ keywords=["news", "guardian", "content", "media", "articles"],+ 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.guardian.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked key surfaces as an HTTPError when `_fetch_page` calls+ # `raise_for_status()`. Retrying can never fix a credential problem, so stop the sync.+ "401 Client Error: Unauthorized for url: https://content.guardianapis.com": "Your Guardian API key is invalid or has been revoked. Request a new key from the Guardian Open Platform, then reconnect.",+ "403 Client Error: Forbidden for url: https://content.guardianapis.com": "Your Guardian API key does not have access to this endpoint. Check your key's tier on the Guardian Open Platform, then reconnect.",+ }++ def get_schemas(+ self,+ config: GuardianSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = GUARDIAN_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=endpoint_config.supports_incremental,+ supports_append=endpoint_config.supports_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) 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: GuardianSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_guardian_credentials(config.api_key):+ return True, None++ return False, "Invalid Guardian API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GuardianResumeConfig]:+ return ResumableSourceManager[GuardianResumeConfig](inputs, GuardianResumeConfig)++ def source_for_pipeline(+ self,+ config: GuardianSourceConfig,+ resumable_source_manager: ResumableSourceManager[GuardianResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return guardian_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/tests/test_guardian.py b/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/tests/test_guardian.pynew file mode 100644index 000000000000..e542ef7c5647--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/tests/test_guardian.py@@ -0,0 +1,245 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.guardian import guardian+from products.warehouse_sources.backend.temporal.data_imports.sources.guardian.guardian import (+ GuardianResumeConfig,+ _build_base_params,+ _format_from_date,+ _scrub_url,+ get_rows,+ guardian_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.guardian.settings import GUARDIAN_ENDPOINTS+++class _FakeResumableManager:+ def __init__(self, state: GuardianResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[GuardianResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> GuardianResumeConfig | None:+ return self._state++ def save_state(self, data: GuardianResumeConfig) -> None:+ self.saved.append(data)+++def _page(results: list[dict[str, Any]], *, pages: int = 1, current_page: int = 1) -> dict[str, Any]:+ return {"response": {"status": "ok", "results": results, "pages": pages, "currentPage": current_page}}+++class TestFormatFromDate:+ @pytest.mark.parametrize(+ "value,expected",+ [+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04"),+ (date(2026, 3, 4), "2026-03-04"),+ ("2026-03-04T02:58:14Z", "2026-03-04"),+ ("", None),+ (None, None),+ ],+ )+ def test_format_from_date(self, value: Any, expected: str | None) -> None:+ assert _format_from_date(value) == expected+++class TestBuildBaseParams:+ def test_content_incremental_sets_from_date_and_oldest_order(self) -> None:+ params = _build_base_params(+ GUARDIAN_ENDPOINTS["content"],+ api_key="k",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ assert params["from-date"] == "2026-03-04"+ # Ascending order is what keeps the incremental watermark advancing correctly.+ assert params["order-by"] == "oldest"+ assert params["order-date"] == "published"+ assert params["show-fields"] == "all"++ def test_content_full_refresh_has_no_from_date(self) -> None:+ params = _build_base_params(+ GUARDIAN_ENDPOINTS["content"],+ api_key="k",+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ assert "from-date" not in params++ def test_non_incremental_endpoint_never_sets_from_date(self) -> None:+ # tags advertises no incremental field, so even an accidental cursor value is ignored.+ params = _build_base_params(+ GUARDIAN_ENDPOINTS["tags"],+ api_key="k",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ )+ assert "from-date" not in params+++class TestScrubUrl:+ @pytest.mark.parametrize(+ "url,expected",+ [+ (+ "https://content.guardianapis.com/search?api-key=secret&page=1",+ "https://content.guardianapis.com/search",+ ),+ ("https://content.guardianapis.com/tags", "https://content.guardianapis.com/tags"),+ (None, "https://content.guardianapis.com"),+ ],+ )+ def test_scrub_url_strips_query(self, url: str | None, expected: str) -> None:+ assert _scrub_url(url) == expected+++class TestValidateCredentials:+ @pytest.mark.parametrize("status_code,expected", [(200, True), (401, False), (403, False)])+ def test_status_maps_to_bool(self, status_code: int, expected: bool) -> None:+ response = MagicMock()+ response.status_code = status_code+ session = MagicMock()+ session.get.return_value = response+ with patch.object(guardian, "make_tracked_session", return_value=session):+ assert validate_credentials("some-key") is expected++ def test_network_error_is_false(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(guardian, "make_tracked_session", return_value=session):+ assert validate_credentials("some-key") is False+++class TestGetRows:+ @staticmethod+ def _collect(manager: _FakeResumableManager, pages: dict[str, dict[str, Any]], **kwargs: Any) -> list[dict]:+ def fake_fetch(session: Any, url: str, logger: Any) -> dict[str, Any]:+ # Match by page number embedded in the URL so param ordering doesn't matter.+ for marker, payload in pages.items():+ if f"page={marker}" in url:+ return payload+ raise AssertionError(f"unexpected url: {url}")++ with patch.object(guardian, "make_tracked_session", return_value=MagicMock()):+ with patch.object(guardian, "_fetch_page", side_effect=fake_fetch):+ rows: list[dict] = []+ for batch in get_rows(+ api_key="k",+ endpoint="content",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ return rows++ def test_paginates_until_last_page(self) -> None:+ pages = {+ "1": _page([{"id": "a"}, {"id": "b"}], pages=2, current_page=1),+ "2": _page([{"id": "c"}], pages=2, current_page=2),+ }+ rows = self._collect(_FakeResumableManager(), pages)+ assert [r["id"] for r in rows] == ["a", "b", "c"]++ def test_saves_next_page_after_yield(self) -> None:+ pages = {+ "1": _page([{"id": "a"}], pages=2, current_page=1),+ "2": _page([{"id": "b"}], pages=2, current_page=2),+ }+ manager = _FakeResumableManager()+ self._collect(manager, pages)+ # State is saved once (after page 1 yields), pointing at page 2. The final page saves nothing.+ assert manager.saved == [GuardianResumeConfig(page=2)]++ def test_resumes_from_saved_page(self) -> None:+ pages = {+ "1": _page([{"id": "a"}], pages=3, current_page=1),+ "2": _page([{"id": "b"}], pages=3, current_page=2),+ "3": _page([{"id": "c"}], pages=3, current_page=3),+ }+ manager = _FakeResumableManager(GuardianResumeConfig(page=3))+ rows = self._collect(manager, pages)+ # Resuming at page 3 skips the already-synced earlier pages.+ assert [r["id"] for r in rows] == ["c"]++ def test_single_page_response_without_pagination_metadata(self) -> None:+ # /sections and /editions omit `pages`/`currentPage`; default to a single page.+ def fake_fetch(session: Any, url: str, logger: Any) -> dict[str, Any]:+ return {"response": {"status": "ok", "results": [{"id": "uk"}, {"id": "us"}]}}++ manager = _FakeResumableManager()+ with patch.object(guardian, "make_tracked_session", return_value=MagicMock()):+ with patch.object(guardian, "_fetch_page", side_effect=fake_fetch):+ rows = [r for batch in get_rows("k", "editions", MagicMock(), manager) for r in batch] # type: ignore[arg-type]+ assert [r["id"] for r in rows] == ["uk", "us"]+ assert manager.saved == []+++class TestFetchPageRetries:+ @pytest.mark.parametrize("status_code", [429, 500, 503])+ def test_retryable_status_raises_retryable_error(self, status_code: int) -> None:+ response = MagicMock()+ response.status_code = status_code+ session = MagicMock()+ session.get.return_value = response+ with patch.object(guardian._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ with pytest.raises(guardian.GuardianRetryableError):+ guardian._fetch_page(session, "https://content.guardianapis.com/search?page=1", MagicMock())+ assert session.get.call_count == 5++ def test_transient_network_error_is_retried_then_succeeds(self) -> None:+ good = MagicMock()+ good.status_code = 200+ good.ok = True+ good.json.return_value = _page([{"id": "a"}])+ session = MagicMock()+ session.get.side_effect = [requests.ReadTimeout("timed out"), good]+ with patch.object(guardian._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = guardian._fetch_page(session, "https://content.guardianapis.com/search?page=1", MagicMock())+ assert result == _page([{"id": "a"}])+ assert session.get.call_count == 2++ def test_auth_failure_raises_without_leaking_api_key(self) -> None:+ # The api-key rides in the query string; a non-2xx must not surface it in the exception, but+ # the base host must survive so get_non_retryable_errors() can still match.+ response = MagicMock()+ response.status_code = 401+ response.ok = False+ response.reason = "Unauthorized"+ response.text = "Unauthorized"+ response.url = "https://content.guardianapis.com/search?api-key=super-secret&page=1"+ session = MagicMock()+ session.get.return_value = response+ with pytest.raises(requests.HTTPError) as exc_info:+ guardian._fetch_page(session, response.url, MagicMock())+ message = str(exc_info.value)+ assert "super-secret" not in message+ assert "401 Client Error: Unauthorized for url: https://content.guardianapis.com/search" in message+++class TestGuardianSourceResponse:+ def test_content_partitions_on_stable_publication_date(self) -> None:+ response = guardian_source("k", "content", MagicMock(), MagicMock())+ assert response.primary_keys == ["id"]+ assert response.partition_keys == ["webPublicationDate"]+ assert response.partition_mode == "datetime"+ assert response.sort_mode == "asc"++ @pytest.mark.parametrize("endpoint", ["tags", "sections", "editions"])+ def test_reference_endpoints_are_unpartitioned(self, endpoint: str) -> None:+ response = guardian_source("k", endpoint, MagicMock(), MagicMock())+ assert response.primary_keys == ["id"]+ assert response.partition_keys is None+ assert response.partition_mode is None+ # Full-refresh endpoints carry no order-by, so their order is unspecified.+ assert response.sort_mode is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/tests/test_guardian_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/tests/test_guardian_source.pynew file mode 100644index 000000000000..27d0d873fc2d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/guardian/tests/test_guardian_source.py@@ -0,0 +1,142 @@+import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import GuardianSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.guardian.guardian import GuardianResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.guardian.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.guardian.source import GuardianSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestGuardianSource:+ def setup_method(self):+ self.source = GuardianSource()+ self.config = GuardianSourceConfig(api_key="test-key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.GUARDIAN++ def test_get_source_config(self):+ config = self.source.get_source_config+ assert config.name.value == "Guardian"+ assert config.label == "The Guardian"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/guardian"++ 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):+ 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_get_schemas_lists_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_only_content_supports_incremental(self):+ # /search is the sole endpoint with a server-side from-date cursor; the reference+ # catalogs (tags/sections/editions) have no timestamp filter, so they're full refresh.+ schemas = {s.name: s for s in self.source.get_schemas(self.config, team_id=1)}+ assert schemas["content"].supports_incremental is True+ assert schemas["content"].incremental_fields[0]["field"] == "webPublicationDate"+ for name in ("tags", "sections", "editions"):+ assert schemas[name].supports_incremental is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filters_by_names(self):+ schemas = self.source.get_schemas(self.config, team_id=1, names=["content", "tags"])+ assert {s.name for s in schemas} == {"content", "tags"}++ def test_lists_tables_without_credentials(self):+ # get_schemas does no I/O, so the public docs table catalog can render.+ assert self.source.lists_tables_without_credentials is True+ documented = {t["name"] for t in self.source.get_documented_tables()}+ assert documented == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self):+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://content.guardianapis.com/search",+ "403 Client Error: Forbidden for url: https://content.guardianapis.com/tags",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://content.guardianapis.com/search",+ "500 Server Error: Internal Server Error for url: https://content.guardianapis.com/search",+ "HTTPSConnectionPool(host='content.guardianapis.com', port=443): Read timed out.",+ ],+ )+ def test_transient_errors_stay_retryable(self, other_error):+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)++ def test_validate_credentials_success(self):+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.guardian.source.validate_guardian_credentials",+ return_value=True,+ ):+ assert self.source.validate_credentials(self.config, team_id=1) == (True, None)++ def test_validate_credentials_failure(self):+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.guardian.source.validate_guardian_credentials",+ return_value=False,+ ):+ ok, error = self.source.validate_credentials(self.config, team_id=1)+ assert ok is False+ assert error == "Invalid Guardian API key"++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ inputs = MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is GuardianResumeConfig++ def test_source_for_pipeline_plumbs_incremental_value(self):+ inputs = MagicMock()+ inputs.schema_name = "content"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ manager = MagicMock()++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.guardian.source.guardian_source"+ ) as mock_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["endpoint"] == "content"+ assert kwargs["api_key"] == "test-key"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ def test_source_for_pipeline_omits_incremental_value_when_disabled(self):+ inputs = MagicMock()+ inputs.schema_name = "tags"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ manager = MagicMock()++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.guardian.source.guardian_source"+ ) as mock_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["db_incremental_field_last_value"] is None