: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 rentcast import source (#68557)
Tom Owers23736de63cd8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex ca85282e72b1..9120ceb6f6ae 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -289,6 +289,7 @@ the row lists both.| recruitee | HTTP | requests | ✅ || reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || redshift | DB protocol | psycopg (Postgres-compatible) | ➖ |+| rentcast | HTTP | requests | ✅ || resend | HTTP | requests | ✅ || revenuecat | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || rippling | HTTP | requests | ✅ |@@ -623,7 +624,6 @@ doesn't conflict with concurrent PRs.- redis- referralhero-- rentcast- repairshopr- reply_io- retail_expressdiff --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 fd11750fe96d..e7b552bef5e5 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@@ -2740,7 +2740,7 @@ class ReferralHeroSourceConfig(config.Config):@config.configclass RentCastSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/canonical_descriptions.pynew file mode 100644index 000000000000..ee2de393a9c1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/canonical_descriptions.py@@ -0,0 +1,79 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the RentCast API docs (https://developers.rentcast.io/reference).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "properties": {+ "description": "A US property record, including its address, physical attributes, ownership, and sale history.",+ "docs_url": "https://developers.rentcast.io/reference/property-records",+ "columns": {+ "id": "The unique RentCast property identifier.",+ "formattedAddress": "The full, formatted property address.",+ "addressLine1": "The first line of the property's street address.",+ "addressLine2": "The second line of the property's street address, if any.",+ "city": "The city the property is located in.",+ "state": "The two-character US state abbreviation.",+ "zipCode": "The 5-digit ZIP code the property is located in.",+ "county": "The county the property is located in.",+ "latitude": "The property's latitude.",+ "longitude": "The property's longitude.",+ "propertyType": "The type of property (e.g. Single Family, Condo, Multi-Family).",+ "bedrooms": "The number of bedrooms.",+ "bathrooms": "The number of bathrooms.",+ "squareFootage": "The livable floor area of the property, in square feet.",+ "lotSize": "The size of the property's lot, in square feet.",+ "yearBuilt": "The year the property was built.",+ "lastSaleDate": "The date the property was most recently sold.",+ "lastSalePrice": "The price the property most recently sold for.",+ "ownerOccupied": "Whether the property is occupied by its owner.",+ "owner": "Details about the property owner, including names, entity type, and mailing address.",+ "features": "Nested physical features such as heating, cooling, garage, pool, and roof type.",+ },+ },+ "sale_listings": {+ "description": "An active or recently seen property sale listing.",+ "docs_url": "https://developers.rentcast.io/reference/sale-listings",+ "columns": {+ "id": "The unique RentCast listing identifier.",+ "formattedAddress": "The full, formatted address of the listed property.",+ "city": "The city the listed property is located in.",+ "state": "The two-character US state abbreviation.",+ "zipCode": "The 5-digit ZIP code the listed property is located in.",+ "propertyType": "The type of property being listed.",+ "bedrooms": "The number of bedrooms.",+ "bathrooms": "The number of bathrooms.",+ "squareFootage": "The livable floor area of the property, in square feet.",+ "price": "The list (asking sale) price.",+ "status": "The listing status (e.g. Active, Inactive).",+ "listingType": "The type of listing (e.g. Standard, New Construction).",+ "listedDate": "The date the property was first listed for sale.",+ "removedDate": "The date the listing was removed, if no longer active.",+ "lastSeenDate": "The date the listing was most recently seen active.",+ "daysOnMarket": "The number of days the property has been on the market.",+ },+ },+ "rental_listings": {+ "description": "An active or recently seen long-term rental listing.",+ "docs_url": "https://developers.rentcast.io/reference/rental-listings-long-term",+ "columns": {+ "id": "The unique RentCast listing identifier.",+ "formattedAddress": "The full, formatted address of the listed property.",+ "city": "The city the listed property is located in.",+ "state": "The two-character US state abbreviation.",+ "zipCode": "The 5-digit ZIP code the listed property is located in.",+ "propertyType": "The type of property being listed.",+ "bedrooms": "The number of bedrooms.",+ "bathrooms": "The number of bathrooms.",+ "squareFootage": "The livable floor area of the property, in square feet.",+ "price": "The listed monthly rent.",+ "status": "The listing status (e.g. Active, Inactive).",+ "listingType": "The type of listing.",+ "listedDate": "The date the property was first listed for rent.",+ "removedDate": "The date the listing was removed, if no longer active.",+ "lastSeenDate": "The date the listing was most recently seen active.",+ "daysOnMarket": "The number of days the property has been on the market.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/rentcast.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/rentcast.pynew file mode 100644index 000000000000..b179a8ab84c4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/rentcast.py@@ -0,0 +1,150 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.rentcast.settings import RENTCAST_ENDPOINTS++RENTCAST_BASE_URL = "https://api.rentcast.io/v1"+# The list endpoints accept a `limit` between 1 and 500; the largest page minimises round trips+# (and paid requests, since RentCast bills per request against a monthly quota).+PAGE_SIZE = 500+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm an API key is genuine. The key is account-wide, so one probe+# validates access to every list endpoint. A `limit` of 1 keeps the billed request small.+DEFAULT_PROBE_PATH = "/properties"+++class RentCastRetryableError(Exception):+ pass+++class RentCastResumeConfig:+ # Offset of the next page to fetch. Offset pagination is deterministic, so a crashed+ # full-refresh sync resumes from the page after the last one yielded; merge dedupes on `id`.+ offset: int = 0+++def _headers(api_key: str) -> dict[str, str]:+ return {"X-Api-Key": api_key, "Accept": "application/json"}+++@retry(+ retry=retry_if_exception_type((RentCastRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ path: str,+ offset: int,+ limit: int,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ response = session.get(+ f"{RENTCAST_BASE_URL}{path}",+ params={"limit": limit, "offset": offset},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise RentCastRetryableError(f"RentCast API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"RentCast API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ # RentCast list endpoints return a bare JSON array of records.+ if not isinstance(data, list):+ raise RentCastRetryableError(f"RentCast returned an unexpected payload for {path}: {type(data).__name__}")+ return data+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RentCastResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = RENTCAST_ENDPOINTS[endpoint]+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume.offset if resume else 0+ if resume and resume.offset > 0:+ logger.debug(f"RentCast: resuming {endpoint} from offset {offset}")++ while True:+ items = _fetch_page(session, config.path, offset, PAGE_SIZE, logger)+ if items:+ yield items++ # A short page (or an empty one) means we've reached the end of the collection.+ if len(items) < PAGE_SIZE:+ break++ offset += PAGE_SIZE+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(RentCastResumeConfig(offset=offset))+++def rentcast_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RentCastResumeConfig],+) -> SourceResponse:+ config = RENTCAST_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the API key.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))+ try:+ response = session.get(f"{RENTCAST_BASE_URL}{path}", params={"limit": 1}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to RentCast: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"RentCast returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid RentCast API key"+ return False, message or "Could not validate RentCast API key"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/settings.pynew file mode 100644index 000000000000..541e123ba69a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/settings.py@@ -0,0 +1,30 @@+from dataclasses import dataclass, field+++@dataclass+class RentCastEndpointConfig:+ name: str+ path: str+ # RentCast assigns each property and listing a stable, globally unique `id`, so it is a safe+ # primary key across full-refresh syncs.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++# RentCast v1 list endpoints. All are full-refresh only: RentCast exposes no server-side+# updated-since cursor (listing search only filters by `daysOld`, days since first listed, which+# isn't a last-modified timestamp), so there is no incremental cursor to advance safely.+#+# Only endpoints that return a record list via limit/offset pagination without a mandatory parent+# id are included. RentCast is a property-lookup API, so these search endpoints accept optional+# geographic filters (city/state/zipCode/lat-long) and fall back to a broad default area when none+# is supplied. The single-object market-statistics endpoint (`/markets`) requires a `zipCode` and+# is intentionally omitted.+RENTCAST_ENDPOINTS: dict[str, RentCastEndpointConfig] = {+ "properties": RentCastEndpointConfig(name="properties", path="/properties"),+ "sale_listings": RentCastEndpointConfig(name="sale_listings", path="/listings/sale"),+ "rental_listings": RentCastEndpointConfig(name="rental_listings", path="/listings/rental/long-term"),+}++ENDPOINTS = tuple(RENTCAST_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/source.pyindex 9c12369acfc3..0b01d5341538 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/source.py@@ -1,19 +1,42 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import RentCastSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.rentcast.rentcast import (+ RentCastResumeConfig,+ rentcast_source,+ validate_credentials as _validate_rentcast_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.rentcast.settings import (+ ENDPOINTS,+ RENTCAST_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class RentCastSource(SimpleSource[RentCastSourceConfig]):+class RentCastSource(ResumableSource[RentCastSourceConfig, RentCastResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.RENTCAST@@ -24,7 +47,86 @@ class RentCastSource(SimpleSource[RentCastSourceConfig]):name=SchemaExternalDataSourceType.RENT_CAST,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="RentCast",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your RentCast API key to pull US real estate data into the PostHog Data warehouse.++You can create an API key under **API dashboard** in [RentCast](https://app.rentcast.io/app/api). The key grants read access to property records and active sale and rental listings.+""",iconPath="/static/services/rentcast.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/rentcast",+ 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.rentcast.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.rentcast.io": "Your RentCast API key is invalid or has been revoked. Generate a new key in the RentCast API dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.rentcast.io": "Your RentCast API key does not have access to this data. Check the key's plan and permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: RentCastSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — RentCast's list endpoints expose no reliably+ # ordered server-side timestamp filter, so there is no incremental cursor to advance.+ 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: RentCastSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API key is account-wide, so a single probe validates access to every schema.+ return _validate_rentcast_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RentCastResumeConfig]:+ return ResumableSourceManager[RentCastResumeConfig](inputs, RentCastResumeConfig)++ def source_for_pipeline(+ self,+ config: RentCastSourceConfig,+ resumable_source_manager: ResumableSourceManager[RentCastResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in RENTCAST_ENDPOINTS:+ raise ValueError(f"Unknown RentCast schema '{inputs.schema_name}'")++ return rentcast_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/tests/test_rentcast.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/tests/test_rentcast.pynew file mode 100644index 000000000000..09c0125a9151--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/tests/test_rentcast.py@@ -0,0 +1,222 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.rentcast import rentcast+from products.warehouse_sources.backend.temporal.data_imports.sources.rentcast.rentcast import (+ PAGE_SIZE,+ RentCastResumeConfig,+ RentCastRetryableError,+ check_access,+ get_rows,+ rentcast_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.rentcast.settings import (+ ENDPOINTS,+ RENTCAST_ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = rentcast._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: RentCastResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[RentCastResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> RentCastResumeConfig | None:+ return self._state++ def save_state(self, data: RentCastResumeConfig) -> None:+ self.saved.append(data)+++def _full_page(start_id: int) -> list[dict]:+ return [{"id": start_id + i} for i in range(PAGE_SIZE)]+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[int, list[dict]], endpoint: str = "properties"+ ) -> list[dict]:+ def fake_fetch(session: Any, path: str, offset: int, limit: int, logger: Any) -> list[dict]:+ return pages[offset]++ monkeypatch.setattr(rentcast, "_fetch_page", fake_fetch)+ monkeypatch.setattr(rentcast, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="rc-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_short_page_yields_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {0: [{"id": 1}, {"id": 2}]})+ assert rows == [{"id": 1}, {"id": 2}]+ # The page is short (< PAGE_SIZE), so we stop without persisting resume state.+ assert manager.saved == []++ def test_follows_offset_pagination_until_short_page(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {0: _full_page(0), PAGE_SIZE: [{"id": 999}]}+ rows = self._collect(manager, monkeypatch, pages)+ assert len(rows) == PAGE_SIZE + 1+ # State is saved after the first full page (offset advances to PAGE_SIZE), then we stop.+ assert [s.offset for s in manager.saved] == [PAGE_SIZE]++ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(RentCastResumeConfig(offset=PAGE_SIZE))+ # Offset 0 must never be fetched on resume.+ pages = {PAGE_SIZE: [{"id": 5}]}+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": 5}]++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {0: []})+ assert rows == []+ assert manager.saved == []+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else []+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(RentCastRetryableError):+ _fetch_page_unwrapped(session, "/properties", 0, PAGE_SIZE, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "/properties", 0, PAGE_SIZE, MagicMock())++ def test_success_returns_list_body(self) -> None:+ body = [{"id": 1}]+ session = self._session_returning(200, body)+ result = _fetch_page_unwrapped(session, "/properties", 0, PAGE_SIZE, MagicMock())+ assert result == body++ def test_non_list_body_is_retryable(self) -> None:+ session = self._session_returning(200, {"error": "nope"})+ with pytest.raises(RentCastRetryableError):+ _fetch_page_unwrapped(session, "/properties", 0, PAGE_SIZE, MagicMock())++ def test_request_uses_limit_and_offset_params(self) -> None:+ session = self._session_returning(200, [])+ _fetch_page_unwrapped(session, "/listings/sale", 1000, PAGE_SIZE, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"limit": PAGE_SIZE, "offset": 1000}+++class TestCheckAccess:+ @staticmethod+ def _session_for(response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return session++ @parameterized.expand(+ [+ ("ok", 200, True, 200, None),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "RentCast returned HTTP 500"),+ ]+ )+ @patch.object(rentcast, "make_tracked_session")+ def test_status_mapping(+ self,+ _name: str,+ status: int,+ ok: bool,+ expected_status: int,+ expected_message: str | None,+ mock_make_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ mock_make_session.return_value = self._session_for(response)+ assert check_access("rc-key") == (expected_status, expected_message)++ @patch.object(rentcast, "make_tracked_session")+ def test_connection_error_maps_to_zero(self, mock_make_session: MagicMock) -> None:+ mock_make_session.return_value = self._session_for(requests.ConnectionError("boom"))+ status, message = check_access("rc-key")+ assert status == 0+ assert message is not None and "boom" in message++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid RentCast API key"),+ ("forbidden", 403, False, "Invalid RentCast API key"),+ ("server_error", 500, False, "RentCast returned HTTP 500"),+ ]+ )+ @patch.object(rentcast, "make_tracked_session")+ def test_validate_credentials(+ self,+ _name: str,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_make_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ mock_make_session.return_value = self._session_for(response)+ assert validate_credentials("rc-key") == (expected_valid, expected_message)+++class TestRentCastSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = rentcast_source(+ api_key="rc-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # No stable creation timestamp is guaranteed across every record, so we don't partition.+ assert response.partition_mode is None++ def test_every_endpoint_uses_id_primary_key(self) -> None:+ assert all(config.primary_keys == ["id"] for config in RENTCAST_ENDPOINTS.values())+ assert set(RENTCAST_ENDPOINTS) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/tests/test_rentcast_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/tests/test_rentcast_source.pynew file mode 100644index 000000000000..b7db188b5f45--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rentcast/tests/test_rentcast_source.py@@ -0,0 +1,125 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import RentCastSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.rentcast.rentcast import RentCastResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.rentcast.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.rentcast.source import RentCastSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestRentCastSource:+ def setup_method(self) -> None:+ self.source = RentCastSource()+ self.team_id = 123+ self.config = RentCastSourceConfig(api_key="rc-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.RENTCAST++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "RentCast"+ assert config.label == "RentCast"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source is visible — it must not carry the scaffolding flag.+ assert not config.unreleasedSource+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/rentcast"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # The only field is the secret API key; the base URL is hardcoded, so there is no non-secret+ # field an editor could retarget to reuse a preserved key against another account.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["sale_listings"])+ assert len(schemas) == 1+ assert schemas[0].name == "sale_listings"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://api.rentcast.io/v1/properties?limit=500&offset=0",),+ ("403 Client Error: Forbidden for url: https://api.rentcast.io/v1/listings/sale?limit=500&offset=0",),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("500 Server Error: Internal Server Error for url: https://api.rentcast.io/v1/properties",),+ ("429 Client Error: Too Many Requests for url: https://api.rentcast.io/v1/listings/sale",),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.rentcast.source._validate_rentcast_credentials"+ )+ def test_validate_credentials_delegates_to_shared_helper(self, mock_validate: mock.MagicMock) -> None:+ # The source method is a thin wrapper; the status->message mapping is covered in test_rentcast.py.+ mock_validate.return_value = (False, "Invalid RentCast API key")+ result = self.source.validate_credentials(self.config, self.team_id)+ assert result == (False, "Invalid RentCast API key")+ mock_validate.assert_called_once_with(self.config.api_key)++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is RentCastResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.rentcast.source.rentcast_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "properties"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "rc-key"+ assert kwargs["endpoint"] == "properties"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown RentCast schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)