: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 pexels import source (#67805)
Tom Owers6a6b522ed534
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex ce57de2d5f69..920953a5b905 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -227,6 +227,7 @@ the row lists both.| paystack | HTTP | requests + `rest_source.RESTClient` | ✅ || pendo | HTTP | requests | ✅ || personio | HTTP | requests | ✅ |+| pexels | HTTP | requests | ✅ || pingdom | HTTP | requests | ✅ || pinterest_ads | HTTP | requests | ✅ || pipedrive | HTTP | requests | ✅ |@@ -572,7 +573,6 @@ doesn't conflict with concurrent PRs.- perk- persistiq- persona-- pexels- phyllo- picqer- pipelinerdiff --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 49f5a9bc6a6c..a0647ad53148 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@@ -2435,7 +2435,8 @@ class PersonioSourceConfig(config.Config):@config.configclass PexelsSourceConfig(config.Config):- pass+ api_key: str+ search_query: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/canonical_descriptions.pynew file mode 100644index 000000000000..87ad9a726c3f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/canonical_descriptions.py@@ -0,0 +1,82 @@+"""Canonical, documentation-sourced descriptions for Pexels endpoints and columns.++Sourced from the official Pexels API reference (https://www.pexels.com/api/documentation/).+Keyed by the endpoint names in `settings.py` `PEXELS_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced Pexels table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_PHOTO_COLUMNS = {+ "id": "Unique identifier for the photo.",+ "width": "Real width of the photo in pixels.",+ "height": "Real height of the photo in pixels.",+ "url": "Pexels URL where the photo is located.",+ "photographer": "Name of the photographer who took the photo.",+ "photographer_url": "Pexels profile URL of the photographer.",+ "photographer_id": "Unique identifier of the photographer.",+ "avg_color": "Average color of the photo, useful as a placeholder while the image loads.",+ "src": "Object of URLs pointing to different sizes/crops of the photo.",+ "liked": "Whether the authenticated user has liked the photo.",+ "alt": "Text description of the photo for use in an alt attribute.",+}++_VIDEO_COLUMNS = {+ "id": "Unique identifier for the video.",+ "width": "Real width of the video in pixels.",+ "height": "Real height of the video in pixels.",+ "duration": "Duration of the video in seconds.",+ "url": "Pexels URL where the video is located.",+ "image": "URL of a screenshot preview image for the video.",+ "avg_color": "Average color of the video, when available.",+ "full_res": "URL of the full-resolution video, when available.",+ "tags": "List of tags associated with the video.",+ "user": "Object describing the videographer (id, name, profile url).",+ "video_files": "List of downloadable/streamable video file variants (quality, file type, dimensions, link).",+ "video_pictures": "List of preview picture frames extracted from the video.",+}++_COLLECTION_COLUMNS = {+ "id": "Unique identifier for the collection.",+ "title": "Title of the collection.",+ "description": "Description of the collection.",+ "private": "Whether the collection is private.",+ "media_count": "Total number of media items (photos and videos) in the collection.",+ "photos_count": "Number of photos in the collection.",+ "videos_count": "Number of videos in the collection.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "curated_photos": {+ "description": "A real-time selection of photos curated by the Pexels team.",+ "docs_url": "https://www.pexels.com/api/documentation/#photos-curated",+ "columns": _PHOTO_COLUMNS,+ },+ "search_photos": {+ "description": "Photos returned by the Pexels photo search for the configured query.",+ "docs_url": "https://www.pexels.com/api/documentation/#photos-search",+ "columns": _PHOTO_COLUMNS,+ },+ "popular_videos": {+ "description": "The current most popular Pexels videos.",+ "docs_url": "https://www.pexels.com/api/documentation/#videos-popular",+ "columns": _VIDEO_COLUMNS,+ },+ "search_videos": {+ "description": "Videos returned by the Pexels video search for the configured query.",+ "docs_url": "https://www.pexels.com/api/documentation/#videos-search",+ "columns": _VIDEO_COLUMNS,+ },+ "featured_collections": {+ "description": "Collections featured by the Pexels team.",+ "docs_url": "https://www.pexels.com/api/documentation/#collections-featured",+ "columns": _COLLECTION_COLUMNS,+ },+ "my_collections": {+ "description": "Collections owned by the authenticated Pexels account.",+ "docs_url": "https://www.pexels.com/api/documentation/#collections-all",+ "columns": _COLLECTION_COLUMNS,+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/pexels.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/pexels.pynew file mode 100644index 000000000000..d754ff0f0f10--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/pexels.py@@ -0,0 +1,150 @@+import dataclasses+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 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.pexels.settings import (+ PEXELS_ENDPOINTS,+ PexelsEndpointConfig,+)++PEXELS_BASE_URL = "https://api.pexels.com"+# Pexels caps `per_page` at 80; request the max to minimise round trips.+PER_PAGE = 80+REQUEST_TIMEOUT = 30+++class PexelsRetryableError(Exception):+ pass+++class PexelsResumeConfig:+ # 1-based page number to (re-)start from. Pexels uses page-number pagination.+ page: int = 1+++def _get_headers(api_key: str) -> dict[str, str]:+ # Pexels sends the API key as the raw Authorization header value — no "Bearer " prefix.+ return {"Authorization": api_key, "Accept": "application/json"}+++def _build_url(base_url: str, params: dict[str, Any]) -> str:+ return f"{base_url}?{urlencode(params)}" if params else base_url+++@retry(+ retry=retry_if_exception_type(+ (+ PexelsRetryableError,+ 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, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT)++ # 429 (rate limited) and 5xx are transient; retry with backoff. Pexels also exposes+ # X-Ratelimit-Reset, but exponential backoff is sufficient given the retry cap.+ if response.status_code == 429 or response.status_code >= 500:+ raise PexelsRetryableError(f"Pexels API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Pexels API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_key: str) -> bool:+ # The curated endpoint needs no query params and a single row is the cheapest authenticated probe.+ url = _build_url(f"{PEXELS_BASE_URL}/v1/curated", {"per_page": 1})+ try:+ # Pexels sends the key as a raw Authorization value the sampler's name-based scrubber can't+ # recognise, so register it for redaction to keep it out of captured HTTP samples.+ session = make_tracked_session(redact_values=(api_key,))+ response = session.get(url, headers=_get_headers(api_key), timeout=REQUEST_TIMEOUT)+ return response.status_code == 200+ except Exception:+ return False+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PexelsResumeConfig],+ search_query: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = PEXELS_ENDPOINTS[endpoint]+ # `get_schemas` only offers the search tables when a query is set, but fail loudly here rather+ # than let a missing query become a literal `?query=None` if that guard ever regresses.+ if config.requires_query and not search_query:+ raise ValueError(f"Endpoint '{endpoint}' requires a search query but none was provided.")++ headers = _get_headers(api_key)+ # One session reused across every page so urllib3 keeps the connection alive. The raw+ # Authorization key is redacted from captured samples — the sampler can't infer that format.+ session = make_tracked_session(redact_values=(api_key,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.page if resume and resume.page else 1++ while True:+ params: dict[str, Any] = {"per_page": PER_PAGE, "page": page}+ if config.requires_query:+ params["query"] = search_query+ url = _build_url(f"{PEXELS_BASE_URL}{config.path}", params)++ data = _fetch_page(session, url, headers, logger)+ items = data.get(config.data_key, [])+ if not items:+ break++ yield items++ # Save the just-yielded page as the resume point so a crash re-fetches it rather than+ # skipping it; the re-fetched rows dedupe on the `id` primary key when merged.+ resumable_source_manager.save_state(PexelsResumeConfig(page=page))++ # `next_page` is present only while more pages remain; absence terminates pagination.+ if not data.get("next_page"):+ break+ page += 1+++def pexels_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PexelsResumeConfig],+ search_query: str | None = None,+) -> SourceResponse:+ endpoint_config: PexelsEndpointConfig = PEXELS_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ search_query=search_query,+ ),+ primary_keys=endpoint_config.primary_keys,+ # Full refresh only — Pexels resources carry no stable datetime to partition on.+ partition_count=1,+ partition_size=1,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/settings.pynew file mode 100644index 000000000000..ed3fc177fd75--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/settings.py@@ -0,0 +1,66 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField+++@dataclass+class PexelsEndpointConfig:+ name: str+ path: str # relative to PEXELS_BASE_URL+ # Key in the JSON response that holds the list of rows ("photos", "videos" or "collections").+ data_key: str+ # Search endpoints reject a request without a `query`; they're only offered when the user+ # configures a search query on the source.+ requires_query: bool = False+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+ description: str | None = None+++PEXELS_ENDPOINTS: dict[str, PexelsEndpointConfig] = {+ "curated_photos": PexelsEndpointConfig(+ name="curated_photos",+ path="/v1/curated",+ data_key="photos",+ description="A real-time selection of photos curated by the Pexels team.",+ ),+ "popular_videos": PexelsEndpointConfig(+ name="popular_videos",+ path="/videos/popular",+ data_key="videos",+ description="The current most popular Pexels videos.",+ ),+ "featured_collections": PexelsEndpointConfig(+ name="featured_collections",+ path="/v1/collections/featured",+ data_key="collections",+ description="Collections featured by the Pexels team.",+ ),+ "my_collections": PexelsEndpointConfig(+ name="my_collections",+ path="/v1/collections",+ data_key="collections",+ description="Collections owned by the authenticated Pexels account.",+ ),+ "search_photos": PexelsEndpointConfig(+ name="search_photos",+ path="/v1/search",+ data_key="photos",+ requires_query=True,+ description="Photos matching the configured search query. Full refresh only.",+ ),+ "search_videos": PexelsEndpointConfig(+ name="search_videos",+ path="/videos/search",+ data_key="videos",+ requires_query=True,+ description="Videos matching the configured search query. Full refresh only.",+ ),+}++ENDPOINTS = tuple(PEXELS_ENDPOINTS.keys())++# Pexels exposes no server-side timestamp/cursor filter on any endpoint, and its resource objects+# (photos, videos, collections) carry no created/updated timestamp. Every table is therefore full+# refresh only: no incremental fields and no datetime partition key.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in PEXELS_ENDPOINTS}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/source.pyindex 555b20d65097..ff41a8c0e638 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/source.py@@ -1,19 +1,45 @@-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 PexelsSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.pexels.pexels import (+ PexelsResumeConfig,+ pexels_source,+ validate_credentials as validate_pexels_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.pexels.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ PEXELS_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class PexelsSource(SimpleSource[PexelsSourceConfig]):+class PexelsSource(ResumableSource[PexelsSourceConfig, PexelsResumeConfig]):+ # `get_schemas` iterates a static endpoint catalog with no I/O, so the table list is safe to+ # publish to public docs without credentials.+ lists_tables_without_credentials = True+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PEXELS@@ -24,7 +50,109 @@ class PexelsSource(SimpleSource[PexelsSourceConfig]):name=SchemaExternalDataSourceType.PEXELS,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Pexels",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Pexels API key to pull Pexels stock photo and video catalog data into the PostHog Data warehouse.++Generate an API key from your [Pexels API dashboard](https://www.pexels.com/api/).++Attribution to Pexels and to the photographer/videographer is required when you use Pexels content — see the [Pexels API guidelines](https://www.pexels.com/api/documentation/#guidelines).""",iconPath="/static/services/pexels.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/pexels",unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Your Pexels API key",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="search_query",+ label="Search query",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="e.g. nature",+ secret=False,+ caption="Optional. When set, the **search_photos** and **search_videos** tables become available and sync content matching this query.",+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.pexels.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked Pexels API key surfaces as a requests HTTPError when `_fetch_page`+ # calls `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the+ # sync. Match the stable status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.pexels.com": "Your Pexels API key is invalid or has been revoked. Generate a new key from your Pexels API dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.pexels.com": "Your Pexels API key is not permitted to access this data. Check your Pexels account, then reconnect.",+ }++ def get_schemas(+ self,+ config: PexelsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ has_search_query = bool((config.search_query or "").strip())++ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = PEXELS_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ # Pexels has no server-side incremental filter, so every table is full refresh only.+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ description=endpoint_config.description,+ )++ # Search tables require a query; only offer them when one is configured.+ schemas = [+ _build_schema(endpoint)+ for endpoint in ENDPOINTS+ if has_search_query or not PEXELS_ENDPOINTS[endpoint].requires_query+ ]+ 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: PexelsSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_pexels_credentials(config.api_key):+ return True, None++ return False, "Invalid Pexels API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PexelsResumeConfig]:+ return ResumableSourceManager[PexelsResumeConfig](inputs, PexelsResumeConfig)++ def source_for_pipeline(+ self,+ config: PexelsSourceConfig,+ resumable_source_manager: ResumableSourceManager[PexelsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return pexels_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ search_query=config.search_query,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/tests/test_pexels.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/tests/test_pexels.pynew file mode 100644index 000000000000..1727a802f9ac--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/tests/test_pexels.py@@ -0,0 +1,268 @@+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.pexels import pexels+from products.warehouse_sources.backend.temporal.data_imports.sources.pexels.pexels import (+ PexelsResumeConfig,+ _build_url,+ _get_headers,+ get_rows,+ pexels_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.pexels.settings import PEXELS_ENDPOINTS+++class _FakeResumableManager:+ def __init__(self, state: PexelsResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[PexelsResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> PexelsResumeConfig | None:+ return self._state++ def save_state(self, data: PexelsResumeConfig) -> None:+ self.saved.append(data)+++class TestHeaders:+ def test_authorization_header_is_raw_key_without_bearer_prefix(self) -> None:+ # Pexels rejects a "Bearer " prefix — the key must be the raw Authorization value.+ headers = _get_headers("my-secret-key")+ assert headers["Authorization"] == "my-secret-key"+ assert "Bearer" not in headers["Authorization"]+++class TestBuildUrl:+ @parameterized.expand(+ [+ ("encodes_spaces", "https://api.pexels.com/v1/search", {"query": "red car"}, "query=red+car"),+ ("no_params", "https://api.pexels.com/v1/curated", {}, None),+ ("page_param", "https://api.pexels.com/v1/curated", {"per_page": 80, "page": 2}, "per_page=80&page=2"),+ ]+ )+ def test_build_url(self, _name: str, base: str, params: dict, expected_fragment: str | None) -> None:+ url = _build_url(base, params)+ if expected_fragment is None:+ assert url == base+ else:+ assert expected_fragment in url+++class TestGetRows:+ @staticmethod+ def _run(manager: _FakeResumableManager, pages: dict[int, Any], endpoint: str, **kwargs: Any) -> list[dict]:+ def fake_fetch(session: Any, url: str, headers: dict, logger: Any) -> dict:+ # Derive the page number from the URL so the fake mirrors real page-number paging.+ page = int(parse_qs(urlparse(url).query).get("page", ["1"])[0])+ return pages[page]++ with patch.object(pexels, "_fetch_page", fake_fetch), patch.object(pexels, "make_tracked_session", MagicMock()):+ rows: list[dict] = []+ for batch in get_rows(+ api_key="k",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ return rows++ def test_paginates_until_next_page_absent(self) -> None:+ pages = {+ 1: {"photos": [{"id": 1}, {"id": 2}], "next_page": "https://api.pexels.com/v1/curated?page=2&per_page=80"},+ 2: {"photos": [{"id": 3}]}, # no next_page -> terminate+ }+ rows = self._run(_FakeResumableManager(), pages, "curated_photos")+ assert rows == [{"id": 1}, {"id": 2}, {"id": 3}]++ def test_stops_on_empty_page(self) -> None:+ pages = {1: {"photos": [], "next_page": "https://api.pexels.com/v1/curated?page=2&per_page=80"}}+ rows = self._run(_FakeResumableManager(), pages, "curated_photos")+ assert rows == []++ def test_reads_videos_data_key(self) -> None:+ # popular_videos reads the "videos" key, not "photos".+ pages = {1: {"videos": [{"id": 9}], "photos": [{"id": 111}]}}+ rows = self._run(_FakeResumableManager(), pages, "popular_videos")+ assert rows == [{"id": 9}]++ def test_search_endpoint_sends_query_param(self) -> None:+ captured: list[str] = []++ def fake_fetch(session: Any, url: str, headers: dict, logger: Any) -> dict:+ captured.append(url)+ return {"photos": [{"id": 1}]}++ with patch.object(pexels, "_fetch_page", fake_fetch), patch.object(pexels, "make_tracked_session", MagicMock()):+ list(+ get_rows(+ api_key="k",+ endpoint="search_photos",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ search_query="red car",+ )+ )++ assert "query=red+car" in captured[0]+ assert "/v1/search" in captured[0]++ @parameterized.expand([("none", None), ("empty", "")])+ def test_search_endpoint_without_query_raises(self, _name: str, query: str | None) -> None:+ # A missing query on a search endpoint must fail loudly, not send a literal `?query=None`.+ with patch.object(pexels, "make_tracked_session", MagicMock()):+ with pytest.raises(ValueError, match="requires a search query"):+ list(+ get_rows(+ api_key="k",+ endpoint="search_photos",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ search_query=query,+ )+ )++ def test_saves_current_page_after_each_yield(self) -> None:+ # State must point at the just-yielded page so a crash re-fetches (and merge-dedupes) it+ # rather than skipping it.+ manager = _FakeResumableManager()+ pages = {+ 1: {"photos": [{"id": 1}], "next_page": "https://api.pexels.com/v1/curated?page=2&per_page=80"},+ 2: {"photos": [{"id": 2}]},+ }+ self._run(manager, pages, "curated_photos")+ assert [s.page for s in manager.saved] == [1, 2]++ def test_resumes_from_saved_page(self) -> None:+ # A resumed job must start at the saved page, not page 1.+ manager = _FakeResumableManager(PexelsResumeConfig(page=2))+ pages = {+ 1: {"photos": [{"id": 1}]},+ 2: {"photos": [{"id": 2}]},+ }+ rows = self._run(manager, pages, "curated_photos")+ assert rows == [{"id": 2}]+++class TestPexelsSourceResponse:+ @parameterized.expand([(name,) for name in PEXELS_ENDPOINTS])+ def test_response_is_full_refresh_with_id_primary_key(self, endpoint: str) -> None:+ # Every endpoint keys on the global `id` and declares no datetime partition — Pexels has no+ # stable timestamp, so a partition key would rewrite partitions every sync.+ response = pexels_source(+ api_key="k",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.partition_keys is None+ assert response.partition_mode is None+++class TestApiKeyRedaction:+ # Pexels sends the key as a raw Authorization value the sampler can't scrub by name, so the+ # source must register it via redact_values or the plaintext key leaks into captured samples.+ def test_get_rows_registers_api_key_for_redaction(self) -> None:+ factory = MagicMock()+ with (+ patch.object(pexels, "_fetch_page", lambda *_: {"photos": []}),+ patch.object(pexels, "make_tracked_session", factory),+ ):+ list(+ get_rows(+ api_key="secret-key",+ endpoint="curated_photos",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )+ assert factory.call_args.kwargs["redact_values"] == ("secret-key",)++ def test_validate_credentials_registers_api_key_for_redaction(self) -> None:+ factory = MagicMock()+ factory.return_value.get.return_value = MagicMock(status_code=200)+ with patch.object(pexels, "make_tracked_session", factory):+ validate_credentials("secret-key")+ assert factory.call_args.kwargs["redact_values"] == ("secret-key",)+++class TestFetchPageRetries:+ @parameterized.expand(+ [+ ("rate_limited", 429),+ ("server_error", 500),+ ("bad_gateway", 502),+ ]+ )+ def test_retryable_status_codes_are_retried(self, _name: str, status_code: int) -> None:+ bad = MagicMock(status_code=status_code, ok=False)+ good = MagicMock(status_code=200, ok=True)+ good.json.return_value = {"photos": []}+ session = MagicMock()+ session.get.side_effect = [bad, good]++ with patch.object(pexels._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = pexels._fetch_page(session, "https://api.pexels.com/v1/curated", {}, MagicMock())++ assert result == {"photos": []}+ assert session.get.call_count == 2++ @parameterized.expand(+ [+ ("read_timeout", requests.ReadTimeout("Read timed out.")),+ ("connection_error", requests.ConnectionError("Connection reset by peer")),+ ("chunked", requests.exceptions.ChunkedEncodingError("Connection broken")),+ ]+ )+ def test_transient_errors_are_retried(self, _name: str, err: Exception) -> None:+ good = MagicMock(status_code=200, ok=True)+ good.json.return_value = {"photos": []}+ session = MagicMock()+ session.get.side_effect = [err, good]++ with patch.object(pexels._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = pexels._fetch_page(session, "https://api.pexels.com/v1/curated", {}, MagicMock())++ assert result == {"photos": []}+ assert session.get.call_count == 2++ def test_unauthorized_raises_and_is_not_retried(self) -> None:+ # A 401 is a credential problem — it must surface immediately (raise_for_status), not retry.+ response = requests.Response()+ response.status_code = 401+ response._content = b'{"code":"Unauthorized"}'+ response.url = "https://api.pexels.com/v1/curated"+ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(requests.HTTPError):+ pexels._fetch_page(session, "https://api.pexels.com/v1/curated", {}, MagicMock())+ assert session.get.call_count == 1+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ def test_status_maps_to_bool(self, _name: str, status_code: int, expected: bool) -> None:+ session = MagicMock()+ session.get.return_value = MagicMock(status_code=status_code)+ with patch.object(pexels, "make_tracked_session", return_value=session):+ assert validate_credentials("k") is expected++ def test_network_error_is_false(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(pexels, "make_tracked_session", return_value=session):+ assert validate_credentials("k") is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/tests/test_pexels_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/tests/test_pexels_source.pynew file mode 100644index 000000000000..9c868b263258--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pexels/tests/test_pexels_source.py@@ -0,0 +1,127 @@+from unittest import mock++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PexelsSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.pexels.pexels import PexelsResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.pexels.source import PexelsSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestPexelsSource:+ def setup_method(self) -> None:+ self.source = PexelsSource()+ self.team_id = 123++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.PEXELS++ def test_config_fields(self) -> None:+ fields = {f.name: f for f in self.source.get_source_config.fields}+ assert set(fields) == {"api_key", "search_query"}+ api_key, search_query = fields["api_key"], fields["search_query"]+ assert isinstance(api_key, SourceFieldInputConfig)+ assert isinstance(search_query, SourceFieldInputConfig)+ assert api_key.required is True+ assert api_key.secret is True+ assert api_key.type == SourceFieldInputConfigType.PASSWORD+ assert search_query.required is False++ def test_schemas_without_query_exclude_search_tables(self) -> None:+ config = PexelsSourceConfig(api_key="k", search_query=None)+ names = {s.name for s in self.source.get_schemas(config, self.team_id)}+ assert names == {"curated_photos", "popular_videos", "featured_collections", "my_collections"}++ @parameterized.expand([("empty_string", ""), ("whitespace", " ")])+ def test_blank_query_excludes_search_tables(self, _name: str, query: str) -> None:+ config = PexelsSourceConfig(api_key="k", search_query=query)+ names = {s.name for s in self.source.get_schemas(config, self.team_id)}+ assert "search_photos" not in names+ assert "search_videos" not in names++ def test_schemas_with_query_include_search_tables(self) -> None:+ config = PexelsSourceConfig(api_key="k", search_query="nature")+ names = {s.name for s in self.source.get_schemas(config, self.team_id)}+ assert {"search_photos", "search_videos"} <= names++ def test_all_schemas_are_full_refresh_only(self) -> None:+ # Pexels has no server-side timestamp filter, so no table may advertise incremental/append —+ # doing so would silently corrupt syncs since there's no cursor to filter on.+ config = PexelsSourceConfig(api_key="k", search_query="nature")+ for schema in self.source.get_schemas(config, self.team_id):+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_schemas_names_filter(self) -> None:+ config = PexelsSourceConfig(api_key="k", search_query=None)+ schemas = self.source.get_schemas(config, self.team_id, names=["curated_photos"])+ assert [s.name for s in schemas] == ["curated_photos"]++ def test_documented_tables_render_without_credentials(self) -> None:+ # lists_tables_without_credentials=True; the public-docs catalog is built from a placeholder+ # config with no I/O and must not be empty.+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == {+ "curated_photos",+ "popular_videos",+ "featured_collections",+ "my_collections",+ }+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @parameterized.expand([("valid", True, True), ("invalid", False, False)])+ def test_validate_credentials(self, _name: str, probe_result: bool, expected_valid: bool) -> None:+ config = PexelsSourceConfig(api_key="k", search_query=None)+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.pexels.source.validate_pexels_credentials",+ return_value=probe_result,+ ):+ valid, _ = self.source.validate_credentials(config, self.team_id)+ assert valid is expected_valid++ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.pexels.com/v1/curated?per_page=80"),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.pexels.com/videos/popular"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed: str) -> None:+ assert any(key in observed for key in self.source.get_non_retryable_errors())++ @parameterized.expand(+ [+ ("read_timeout", "HTTPSConnectionPool(host='api.pexels.com', port=443): Read timed out."),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.pexels.com/v1/curated"),+ ]+ )+ def test_transient_errors_stay_retryable(self, _name: str, observed: str) -> None:+ assert not any(key in observed for key in self.source.get_non_retryable_errors())++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ inputs = mock.MagicMock(spec=SourceInputs)+ inputs.logger = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is PexelsResumeConfig++ def test_source_for_pipeline_plumbs_endpoint_and_query(self) -> None:+ config = PexelsSourceConfig(api_key="k", search_query="nature")+ inputs = mock.MagicMock(spec=SourceInputs)+ inputs.schema_name = "search_photos"+ inputs.logger = mock.MagicMock()+ manager = mock.MagicMock()++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.pexels.source.pexels_source"+ ) as mock_source:+ self.source.source_for_pipeline(config, manager, inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["api_key"] == "k"+ assert kwargs["endpoint"] == "search_photos"+ assert kwargs["search_query"] == "nature"