Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement google_webfonts import source (#67793)

Tom Owers44ac193b384f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 12b30d9db31a..0aafab3173c1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -162,6 +162,7 @@ the row lists both.
| google_ads | gRPC | google-ads (googleads.client) | ✅ |
| google_analytics | HTTP | requests (`AuthorizedSession` + `TrackedHTTPAdapter`) | ✅ |
| google_sheets | HTTP (vendor SDK) | gspread | ✅ |
+| google_webfonts | HTTP | requests | ✅ |
| granola | HTTP | requests | ✅ |
| gorgias | HTTP | requests | ✅ |
| greenhouse | HTTP | requests | ✅ |
@@ -434,7 +435,6 @@ doesn't conflict with concurrent PRs.
- google_forms
- google_pagespeed_insights
- google_tasks
-- google_webfonts
- google_workspace_admin_reports
- grafana
- greythr
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.py
index 0cdc29c4fab6..a6f3629c1b79 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
@@ -1440,7 +1440,7 @@ class GoogleTasksSourceConfig(config.Config):
@config.config
class GoogleWebfontsSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/canonical_descriptions.py
new file mode 100644
index 000000000000..8772cadb423e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/canonical_descriptions.py
@@ -0,0 +1,30 @@
+"""Canonical, documentation-sourced descriptions for the Google Fonts (Web Fonts Developer API).
+
+Sourced from the official API reference (https://developers.google.com/fonts/docs/developer_api).
+Keyed by the endpoint names in `settings.py` `GOOGLE_WEBFONTS_ENDPOINTS`, which match the
+`ExternalDataSchema.name` of a synced table. 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 = {
+ "webfonts": {
+ "description": "The full catalog of font families served by Google Fonts, one row per family.",
+ "docs_url": "https://developers.google.com/fonts/docs/developer_api",
+ "columns": {
+ "family": "Name of the font family (e.g. 'Roboto'). Unique identifier for the family.",
+ "variants": "List of the available styles/weights for the family (e.g. 'regular', 'italic', '700').",
+ "subsets": "List of character subsets the family supports (e.g. 'latin', 'cyrillic', 'greek').",
+ "version": "Current version string of the family (e.g. 'v30').",
+ "lastModified": "Date the family was last modified, in YYYY-MM-DD format.",
+ "files": "Map of each variant to the URL of its font file.",
+ "category": "Category of the family: serif, sans-serif, monospace, display, or handwriting.",
+ "kind": "Type of the resource; always 'webfonts#webfont' for a family.",
+ "menu": "URL of a font file containing only the glyphs needed to render the family name.",
+ "axes": "For variable fonts, the list of variation axes with their tag, start, and end values.",
+ "colorCapabilities": "For color fonts, the list of supported color formats (e.g. 'COLRv0', 'COLRv1').",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/google_webfonts.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/google_webfonts.py
new file mode 100644
index 000000000000..b74e7754988a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/google_webfonts.py
@@ -0,0 +1,123 @@
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from urllib3.util.retry import Retry
+
+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.google_webfonts.settings import (
+ GOOGLE_WEBFONTS_ENDPOINTS,
+)
+
+GOOGLE_WEBFONTS_BASE_URL = "https://www.googleapis.com"
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+
+
+class GoogleWebfontsRetryableError(Exception):
+ pass
+
+
+def _get_session(api_key: str) -> requests.Session:
+ # The key is sent via the `X-goog-api-key` header rather than the `key` query param so it
+ # never lands in a logged request URL. Google accepts either form.
+ # `retry=Retry(total=0)` disables the adapter's default retries so tenacity is the single
+ # retry layer — otherwise the two stack and multiply the backoff on 429/5xx.
+ return make_tracked_session(
+ headers={"X-goog-api-key": api_key, "Accept": "application/json"},
+ redact_values=(api_key,),
+ retry=Retry(total=0),
+ )
+
+
+def _build_url(path: str, params: dict[str, Any]) -> str:
+ query = urlencode(params)
+ return f"{GOOGLE_WEBFONTS_BASE_URL}{path}?{query}" if query else f"{GOOGLE_WEBFONTS_BASE_URL}{path}"
+
+
+def validate_credentials(api_key: str) -> bool:
+ """Confirm the API key is valid with a single catalog probe.
+
+ An invalid key returns 400 (`API_KEY_INVALID`) and a missing key 403; only a genuine key
+ returns 200. Connection-level failures (DNS, timeout, reset) raise `requests.RequestException`
+ so the caller can tell "unreachable" apart from "invalid key" instead of blaming the credential.
+ """
+ config = GOOGLE_WEBFONTS_ENDPOINTS["webfonts"]
+ params = {"sort": config.sort} if config.sort else {}
+ response = _get_session(api_key).get(
+ _build_url(config.path, params),
+ timeout=10,
+ )
+ return response.status_code == 200
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ config = GOOGLE_WEBFONTS_ENDPOINTS[endpoint]
+ session = _get_session(api_key)
+
+ @retry(
+ retry=retry_if_exception_type(
+ (
+ GoogleWebfontsRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch(path: str, params: dict[str, Any]) -> dict[str, Any]:
+ url = _build_url(path, params)
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise GoogleWebfontsRetryableError(
+ f"Google Webfonts API error (retryable): status={response.status_code}, url={url}"
+ )
+
+ if not response.ok:
+ logger.error(f"Google Webfonts API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ params: dict[str, Any] = {}
+ if config.sort:
+ params["sort"] = config.sort
+
+ # The endpoint is unpaginated: the whole catalog arrives in a single `items` array.
+ data = fetch(config.path, params)
+ items = data.get(config.data_selector, []) or []
+ if items:
+ yield items
+
+
+def google_webfonts_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ config = GOOGLE_WEBFONTS_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/settings.py
new file mode 100644
index 000000000000..ac7b7db853d2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/settings.py
@@ -0,0 +1,28 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class GoogleWebfontsEndpointConfig:
+ name: str
+ # Path under https://www.googleapis.com.
+ path: str
+ # Field selecting each row out of the JSON response body.
+ data_selector: str = "items"
+ primary_keys: list[str] = field(default_factory=lambda: ["family"])
+ # Optional `sort` value passed to the API for a deterministic response order.
+ sort: str | None = None
+
+
+# The Google Fonts Developer API exposes a single read-only endpoint that returns the full
+# catalog of font families in one (unpaginated) response. There is no server-side timestamp
+# filter — each family carries a `lastModified` date but it can't be used to filter the request —
+# so this is full refresh only. `family` is the documented globally-unique identifier.
+GOOGLE_WEBFONTS_ENDPOINTS: dict[str, GoogleWebfontsEndpointConfig] = {
+ "webfonts": GoogleWebfontsEndpointConfig(
+ name="webfonts",
+ path="/webfonts/v1/webfonts",
+ sort="alpha",
+ ),
+}
+
+ENDPOINTS = tuple(GOOGLE_WEBFONTS_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/source.py
index d92f3876d097..7f68c82ccf5a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/source.py
@@ -1,21 +1,41 @@
-from typing import cast
+from typing import Optional, cast
+
+import requests
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (
GoogleWebfontsSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.google_webfonts.google_webfonts import (
+ google_webfonts_source,
+ validate_credentials as validate_google_webfonts_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.google_webfonts.settings import ENDPOINTS
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class GoogleWebfontsSource(SimpleSource[GoogleWebfontsSourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.GOOGLEWEBFONTS
@@ -26,7 +46,84 @@ class GoogleWebfontsSource(SimpleSource[GoogleWebfontsSourceConfig]):
name=SchemaExternalDataSourceType.GOOGLE_WEBFONTS,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Google Webfonts",
- iconPath="/static/services/google_webfonts.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter a Google API key to pull the Google Fonts catalog into the PostHog Data warehouse.
+
+Create an API key in the [Google Cloud Console](https://console.cloud.google.com/apis/credentials) and enable the **Web Fonts Developer API** for the project. No OAuth or scopes are required — the API is a public, read-only metadata catalog.
+""",
+ iconPath="/static/services/google_webfonts.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/google-webfonts",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="AIza...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.google_webfonts.canonical_descriptions import ( # noqa: PLC0415 — lazy import keeps the descriptions off the module import path
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid key returns 400 (`API_KEY_INVALID`) and a missing/unregistered key 403; retrying
+ # can never satisfy a credential problem. Match the stable status text and base URL, not the
+ # per-request query string (the key is sent as a header, so it never appears in the URL).
+ "400 Client Error: Bad Request for url: https://www.googleapis.com/webfonts/v1/webfonts": "Your Google API key is invalid. Create a new key in the Google Cloud Console, enable the Web Fonts Developer API, then reconnect.",
+ "403 Client Error: Forbidden for url: https://www.googleapis.com/webfonts/v1/webfonts": "Your Google API key was rejected. Make sure the Web Fonts Developer API is enabled for the key's project, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: GoogleWebfontsSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # The catalog has no server-side timestamp filter, so it's full refresh only.
+ 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: GoogleWebfontsSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ try:
+ if validate_google_webfonts_credentials(config.api_key):
+ return True, None
+ except requests.RequestException:
+ return False, "Could not reach the Google Fonts API. Check your network connection and try again."
+
+ return False, "Invalid Google API key"
+
+ def source_for_pipeline(self, config: GoogleWebfontsSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return google_webfonts_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/tests/test_google_webfonts.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/tests/test_google_webfonts.py
new file mode 100644
index 000000000000..80afe11b1aec
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/tests/test_google_webfonts.py
@@ -0,0 +1,134 @@
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.google_webfonts.google_webfonts import (
+ MAX_RETRY_ATTEMPTS,
+ GoogleWebfontsRetryableError,
+ get_rows,
+ google_webfonts_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.google_webfonts.settings import (
+ ENDPOINTS,
+ GOOGLE_WEBFONTS_ENDPOINTS,
+)
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.google_webfonts.google_webfonts"
+
+
+def _response(items: list[dict[str, Any]]) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = {"kind": "webfonts#webfontList", "items": items}
+ resp.status_code = 200
+ resp.ok = True
+ return resp
+
+
+def _error_response(status_code: int) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status_code
+ resp.ok = False
+ resp.text = "error"
+ return resp
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, True),
+ (400, False), # invalid key
+ (403, False), # missing/unregistered key
+ (500, False),
+ ],
+ )
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ assert validate_credentials("AIza-key") is expected
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_validate_sends_key_in_header_not_url(self, mock_session):
+ response = mock.MagicMock()
+ response.status_code = 200
+ mock_session.return_value.get.return_value = response
+
+ validate_credentials("AIza-secret")
+
+ # Key must ride the X-goog-api-key header so it never lands in a logged request URL.
+ headers = mock_session.call_args.kwargs["headers"]
+ assert headers["X-goog-api-key"] == "AIza-secret"
+ url = mock_session.return_value.get.call_args.args[0]
+ assert "AIza-secret" not in url
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_validate_credentials_propagates_connection_errors(self, mock_session):
+ # Connection-level failures must surface so the caller can distinguish "unreachable"
+ # from "invalid key" rather than blaming the credential.
+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")
+ with pytest.raises(requests.ConnectionError):
+ validate_credentials("AIza-key")
+
+
+class TestGetRows:
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_yields_items_array_and_requests_stable_sort(self, mock_session):
+ mock_session.return_value.get.return_value = _response([{"family": "Roboto"}, {"family": "Lato"}])
+
+ batches = list(get_rows("AIza-key", "webfonts", mock.MagicMock()))
+
+ assert batches == [[{"family": "Roboto"}, {"family": "Lato"}]]
+ url = mock_session.return_value.get.call_args.args[0]
+ assert urlparse(url).path == "/webfonts/v1/webfonts"
+ assert parse_qs(urlparse(url).query)["sort"] == ["alpha"]
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_empty_catalog_yields_nothing(self, mock_session):
+ mock_session.return_value.get.return_value = _response([])
+
+ assert list(get_rows("AIza-key", "webfonts", mock.MagicMock())) == []
+
+ @mock.patch("time.sleep")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_retries_retryable_status_then_succeeds(self, mock_session, _mock_sleep):
+ mock_session.return_value.get.side_effect = [
+ _error_response(500),
+ _error_response(429),
+ _response([{"family": "Roboto"}]),
+ ]
+
+ batches = list(get_rows("AIza-key", "webfonts", mock.MagicMock()))
+
+ assert batches == [[{"family": "Roboto"}]]
+ assert mock_session.return_value.get.call_count == 3
+
+ @mock.patch("time.sleep")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_retries_exhausted_raises(self, mock_session, _mock_sleep):
+ mock_session.return_value.get.return_value = _error_response(503)
+
+ with pytest.raises(GoogleWebfontsRetryableError):
+ list(get_rows("AIza-key", "webfonts", mock.MagicMock()))
+
+ assert mock_session.return_value.get.call_count == MAX_RETRY_ATTEMPTS
+
+
+class TestGoogleWebfontsSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = GOOGLE_WEBFONTS_ENDPOINTS[endpoint]
+ response = google_webfonts_source("AIza-key", endpoint, mock.MagicMock())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == "asc"
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/tests/test_google_webfonts_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/tests/test_google_webfonts_source.py
new file mode 100644
index 000000000000..3799f6ca1242
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_webfonts/tests/test_google_webfonts_source.py
@@ -0,0 +1,130 @@
+import pytest
+from unittest import mock
+
+import requests
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (
+ GoogleWebfontsSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.google_webfonts.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.google_webfonts.source import GoogleWebfontsSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.google_webfonts.source"
+
+
+class TestGoogleWebfontsSource:
+ def setup_method(self):
+ self.source = GoogleWebfontsSource()
+ self.team_id = 123
+ self.config = GoogleWebfontsSourceConfig(api_key="AIza-key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.GOOGLEWEBFONTS
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "GoogleWebfonts"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/google-webfonts"
+
+ 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
+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "400 Client Error: Bad Request for url: https://www.googleapis.com/webfonts/v1/webfonts?sort=alpha",
+ "403 Client Error: Forbidden for url: https://www.googleapis.com/webfonts/v1/webfonts?sort=alpha",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ # A 400 from an unrelated API must not trip the Google Webfonts credential handler.
+ "400 Client Error: Bad Request for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://www.googleapis.com/webfonts/v1/webfonts",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas_are_full_refresh_only(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ assert all(not schema.supports_incremental for schema in schemas)
+ assert all(not schema.supports_append for schema in schemas)
+ assert all(schema.incremental_fields == [] for schema in schemas)
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["webfonts"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "webfonts"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_without_credentials(self):
+ # Static catalog opt-in powers the posthog.com "Supported tables" section.
+ assert self.source.lists_tables_without_credentials is True
+ tables = self.source.get_documented_tables()
+ webfonts = next(t for t in tables if t["name"] == "webfonts")
+ assert webfonts["sync_methods"] == ["Full refresh"]
+ assert webfonts["description"]
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid Google API key"),
+ ],
+ )
+ @mock.patch(f"{_MODULE}.validate_google_webfonts_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)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with("AIza-key")
+
+ @mock.patch(f"{_MODULE}.validate_google_webfonts_credentials")
+ def test_validate_credentials_reports_connection_failure_distinctly(self, mock_validate):
+ # A transient network failure must not be reported as an invalid key, or the user
+ # wastes time recreating a working credential.
+ mock_validate.side_effect = requests.ConnectionError("boom")
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert error_message == "Could not reach the Google Fonts API. Check your network connection and try again."
+
+ @mock.patch(f"{_MODULE}.google_webfonts_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "webfonts"
+
+ self.source.source_for_pipeline(self.config, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "AIza-key"
+ assert kwargs["endpoint"] == "webfonts"