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.

chore(data-warehouse): port 36 more sources onto the shared test driver (#115492)

Tom Owers987edb90c8c3
diff --git a/posthog/test/repo_invariants/source_test_mocked_resume_manager_baseline.txt b/posthog/test/repo_invariants/source_test_mocked_resume_manager_baseline.txt
index cca23257ebcb..6dd24ed0cae9 100644
--- a/posthog/test/repo_invariants/source_test_mocked_resume_manager_baseline.txt
+++ b/posthog/test/repo_invariants/source_test_mocked_resume_manager_baseline.txt
@@ -1,15 +1,6 @@
products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably.py
products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably_source.py
-products/warehouse_sources/backend/temporal/data_imports/sources/active_campaign/tests/test_active_campaign.py
-products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia.py
-products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude.py
-products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude_source.py
-products/warehouse_sources/backend/temporal/data_imports/sources/appstack/tests/test_appstack.py
-products/warehouse_sources/backend/temporal/data_imports/sources/arcade/tests/test_arcade.py
-products/warehouse_sources/backend/temporal/data_imports/sources/asaas/tests/test_asaas.py
products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/tests/test_asknicely_source.py
-products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/tests/test_astronomer.py
-products/warehouse_sources/backend/temporal/data_imports/sources/attio/tests/test_attio.py
products/warehouse_sources/backend/temporal/data_imports/sources/autumn/tests/test_autumn.py
products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/tests/test_aws_batch.py
products/warehouse_sources/backend/temporal/data_imports/sources/aws_cloudtrail/tests/test_aws_cloudtrail.py
diff --git a/posthog/test/repo_invariants/source_test_patched_session_baseline.txt b/posthog/test/repo_invariants/source_test_patched_session_baseline.txt
index 641c1e0e1d1d..8ad866d26667 100644
--- a/posthog/test/repo_invariants/source_test_patched_session_baseline.txt
+++ b/posthog/test/repo_invariants/source_test_patched_session_baseline.txt
@@ -1,50 +1,22 @@
products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably.py
products/warehouse_sources/backend/temporal/data_imports/sources/ably/tests/test_ably_source.py
-products/warehouse_sources/backend/temporal/data_imports/sources/acast/tests/test_acast.py
-products/warehouse_sources/backend/temporal/data_imports/sources/active_campaign/tests/test_active_campaign.py
products/warehouse_sources/backend/temporal/data_imports/sources/adjust/tests/test_adjust.py
products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/tests/test_adobe_analytics.py
-products/warehouse_sources/backend/temporal/data_imports/sources/adroll/tests/test_adroll.py
-products/warehouse_sources/backend/temporal/data_imports/sources/aftership/tests/test_aftership.py
-products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm.py
-products/warehouse_sources/backend/temporal/data_imports/sources/aha/tests/test_aha.py
-products/warehouse_sources/backend/temporal/data_imports/sources/aha_ideas/tests/test_aha_ideas.py
products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs.py
-products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/tests/test_airbrake.py
products/warehouse_sources/backend/temporal/data_imports/sources/aircall/tests/test_aircall.py
-products/warehouse_sources/backend/temporal/data_imports/sources/airops/tests/test_airops.py
-products/warehouse_sources/backend/temporal/data_imports/sources/airtable/tests/test_airtable.py
-products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/tests/test_airwallex.py
-products/warehouse_sources/backend/temporal/data_imports/sources/aiven/tests/test_aiven.py
-products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia.py
-products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna.py
products/warehouse_sources/backend/temporal/data_imports/sources/alpha_vantage/tests/test_alpha_vantage.py
products/warehouse_sources/backend/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py
-products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/tests/test_amplemarket.py
-products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude.py
products/warehouse_sources/backend/temporal/data_imports/sources/anthropic/tests/test_anthropic.py
-products/warehouse_sources/backend/temporal/data_imports/sources/anvil/tests/test_anvil.py
-products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/tests/test_apify_dataset.py
-products/warehouse_sources/backend/temporal/data_imports/sources/apitally/tests/test_apitally.py
products/warehouse_sources/backend/temporal/data_imports/sources/apollo/tests/test_apollo.py
products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.py
products/warehouse_sources/backend/temporal/data_imports/sources/appdynamics/tests/test_appdynamics.py
-products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py
products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow_source.py
products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads.py
products/warehouse_sources/backend/temporal/data_imports/sources/applovin/tests/test_applovin.py
products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py
products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/tests/test_appsignal.py
-products/warehouse_sources/backend/temporal/data_imports/sources/appstack/tests/test_appstack.py
-products/warehouse_sources/backend/temporal/data_imports/sources/arcade/tests/test_arcade.py
products/warehouse_sources/backend/temporal/data_imports/sources/argocd/tests/test_argocd.py
-products/warehouse_sources/backend/temporal/data_imports/sources/asaas/tests/test_asaas.py
-products/warehouse_sources/backend/temporal/data_imports/sources/asana/tests/test_asana.py
-products/warehouse_sources/backend/temporal/data_imports/sources/ashby/tests/test_ashby.py
-products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/tests/test_asknicely.py
-products/warehouse_sources/backend/temporal/data_imports/sources/assemblyai/tests/test_assemblyai.py
products/warehouse_sources/backend/temporal/data_imports/sources/attentive/tests/test_attentive_api_client.py
-products/warehouse_sources/backend/temporal/data_imports/sources/attio/tests/test_attio.py
products/warehouse_sources/backend/temporal/data_imports/sources/auth0/tests/test_auth0.py
products/warehouse_sources/backend/temporal/data_imports/sources/automox/tests/test_automox.py
products/warehouse_sources/backend/temporal/data_imports/sources/autumn/tests/test_autumn.py
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/acast/tests/test_acast.py b/products/warehouse_sources/backend/temporal/data_imports/sources/acast/tests/test_acast.py
index 4bcf16437912..7eea906ee42b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/acast/tests/test_acast.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/acast/tests/test_acast.py
@@ -1,73 +1,48 @@
-import json
-from collections.abc import Iterable, Iterator
-from http import HTTPStatus
-from typing import Any, cast
-
import pytest
-from unittest.mock import MagicMock, patch
-from requests import Request, Response
from requests.exceptions import HTTPError
-from products.warehouse_sources.backend.temporal.data_imports.sources.acast.acast import (
- acast_source,
- validate_credentials,
-)
+from products.warehouse_sources.backend.temporal.data_imports.sources.acast.acast import validate_credentials
from products.warehouse_sources.backend.temporal.data_imports.sources.acast.source import AcastSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import UnknownResourceError
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
-
-
-def items(response: SourceResponse) -> Iterable[Any]:
- return cast(Iterable[Any], response.items())
-
-
-def response(body: object, status: int = 200) -> Response:
- result = Response()
- result.status_code = status
- result.reason = HTTPStatus(status).phrase
- result.url = "https://open.acast.com/rest/shows"
- result.headers["Content-Type"] = "application/json"
- result._content = json.dumps(body).encode()
- return result
-
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.acast import AcastSourceConfig
-def http_session() -> Iterator[MagicMock]:
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
- ) as factory:
- session = factory.return_value
- session.headers = {}
- session.prepare_request.side_effect = Request.prepare
- yield session
+def acast_driver() -> SourceDriver:
+ return SourceDriver(AcastSource(), AcastSourceConfig(api_key="fake-acast-key"))
-def test_episode_fanout_keeps_parent_keys_and_continues_after_empty_show(http_session: MagicMock) -> None:
- http_session.send.side_effect = [
- response([{"_id": "show-1"}, {"_id": "show-2"}, {"_id": "show-3"}]),
- response([{"_id": "episode-1", "title": "First episode", "Markers": []}]),
- response([]),
- response([{"_id": "episode-1", "title": "Another episode", "Markers": []}]),
- ]
- result = acast_source("fake-acast-key", "episodes", 1, "job-1")
- rows = [row for batch in items(result) for row in batch]
+def test_episode_fanout_keeps_parent_keys_and_continues_after_empty_show() -> None:
+ result = acast_driver().run(
+ "episodes",
+ [
+ ScriptedResponse(json=[{"_id": "show-1"}, {"_id": "show-2"}, {"_id": "show-3"}]),
+ ScriptedResponse(json=[{"_id": "episode-1", "title": "First episode", "Markers": []}]),
+ ScriptedResponse(json=[]),
+ ScriptedResponse(json=[{"_id": "episode-1", "title": "Another episode", "Markers": []}]),
+ ],
+ )
- assert rows == [
+ assert result.raised is None
+ assert result.rows == [
{"_id": "episode-1", "title": "First episode", "Markers": [], "show_id": "show-1"},
{"_id": "episode-1", "title": "Another episode", "Markers": [], "show_id": "show-3"},
]
- assert result.primary_keys is not None
- assert len({tuple(row[key] for key in result.primary_keys) for row in rows}) == 2
- requests = [call.args[0] for call in http_session.send.call_args_list]
- assert [request.url for request in requests] == [
+ assert result.response is not None
+ assert result.response.primary_keys is not None
+ assert len({tuple(row[key] for key in result.response.primary_keys) for row in result.rows}) == 2
+ assert result.urls == [
"https://open.acast.com/rest/shows",
"https://open.acast.com/rest/shows/show-1/episodes",
"https://open.acast.com/rest/shows/show-2/episodes",
"https://open.acast.com/rest/shows/show-3/episodes",
]
- assert all(request.headers["X-API-Key"] == "fake-acast-key" for request in requests)
+ assert all(request.headers["x-api-key"] == "fake-acast-key" for request in result.requests)
@pytest.mark.parametrize(
@@ -86,51 +61,50 @@ def test_episode_fanout_keeps_parent_keys_and_continues_after_empty_show(http_se
),
],
)
-def test_credential_validation_maps_auth_errors(
- http_session: MagicMock, status: int, message: str, expected: tuple[bool, str | None]
-) -> None:
- http_session.send.side_effect = [
- response([] if status == 200 else {"statusCode": status, "message": message}, status)
- ]
-
- assert validate_credentials("fake-acast-key", 1) == expected
- http_session.send.assert_called_once()
- request = http_session.send.call_args.args[0]
+def test_credential_validation_maps_auth_errors(status: int, message: str, expected: tuple[bool, str | None]) -> None:
+ with scripted_network(
+ [ScriptedResponse(status=status, json=[] if status == 200 else {"statusCode": status, "message": message})]
+ ) as network:
+ assert validate_credentials("fake-acast-key", 1) == expected
+
+ assert len(network.requests_log) == 1
+ request = network.requests_log[0]
assert request.url == "https://open.acast.com/rest/shows"
- assert request.headers["X-API-Key"] == "fake-acast-key"
+ assert request.headers["x-api-key"] == "fake-acast-key"
@pytest.mark.parametrize("status", [401, 403, 404])
-def test_sync_errors_are_not_retried_and_auth_errors_match_user_messages(http_session: MagicMock, status: int) -> None:
- http_session.send.side_effect = [response({"statusCode": status}, status)]
-
- with pytest.raises(HTTPError) as error:
- list(items(acast_source("fake-acast-key", "shows", 1, "job-1")))
+def test_sync_errors_are_not_retried_and_auth_errors_match_user_messages(status: int) -> None:
+ result = acast_driver().run("shows", [ScriptedResponse(status=status, json={"statusCode": status})])
- http_session.send.assert_called_once()
+ assert isinstance(result.raised, HTTPError)
+ assert len(result.requests) == 1
matches = [
- message for pattern, message in AcastSource().get_non_retryable_errors().items() if pattern in str(error.value)
+ message
+ for pattern, message in AcastSource().get_non_retryable_errors().items()
+ if pattern in str(result.raised)
]
assert len(matches) == (0 if status == 404 else 1)
- assert "fake-acast-key" not in str(error.value)
+ assert "fake-acast-key" not in str(result.raised)
-def test_credential_validation_propagates_other_errors(http_session: MagicMock) -> None:
- http_session.send.side_effect = [response({"statusCode": 404}, 404)]
+def test_credential_validation_propagates_other_errors() -> None:
+ with scripted_network([ScriptedResponse(status=404, json={"statusCode": 404})]) as network:
+ with pytest.raises(HTTPError):
+ validate_credentials("fake-acast-key", 1)
- with pytest.raises(HTTPError):
- validate_credentials("fake-acast-key", 1)
+ assert len(network.requests_log) == 1
-def test_unexpected_response_shape_fails_instead_of_importing_an_error(http_session: MagicMock) -> None:
- http_session.send.side_effect = [response({"error": "Unexpected response"})]
+def test_unexpected_response_shape_fails_instead_of_importing_an_error() -> None:
+ result = acast_driver().run("shows", [ScriptedResponse(json={"error": "Unexpected response"})])
- with pytest.raises(ValueError, match="Required a list response body"):
- list(items(acast_source("fake-acast-key", "shows", 1, "job-1")))
+ assert isinstance(result.raised, ValueError)
+ assert "Required a list response body" in str(result.raised)
-def test_unknown_table_fails_before_making_requests(http_session: MagicMock) -> None:
- with pytest.raises(UnknownResourceError):
- acast_source("fake-acast-key", "unknown", 1, "job-1")
+def test_unknown_table_fails_before_making_requests() -> None:
+ result = acast_driver().run("unknown", [])
- http_session.send.assert_not_called()
+ assert isinstance(result.raised, UnknownResourceError)
+ assert result.requests == []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/active_campaign/tests/test_active_campaign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/active_campaign/tests/test_active_campaign.py
index d19de365a6fc..30cd2d498167 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/active_campaign/tests/test_active_campaign.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/active_campaign/tests/test_active_campaign.py
@@ -1,24 +1,28 @@
-import json
-from collections.abc import Iterable
-from typing import Any, cast
+from typing import Any
import pytest
from unittest.mock import MagicMock, patch
-from requests import Response
-
from products.warehouse_sources.backend.temporal.data_imports.sources.active_campaign.active_campaign import (
PAGE_SIZE,
ActiveCampaignPaginator,
ActiveCampaignResumeConfig,
_normalize_base_url,
- active_campaign_source,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.active_campaign.settings import (
ACTIVE_CAMPAIGN_ENDPOINTS,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.active_campaign.source import ActiveCampaignSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.activecampaign import (
+ ActiveCampaignSourceConfig,
+)
def _full_page() -> list[dict[str, Any]]:
@@ -31,6 +35,10 @@ def _meta_response(total: Any) -> MagicMock:
return response
+def _driver(api_url: str = "https://acme.api-us1.com") -> SourceDriver:
+ return SourceDriver(ActiveCampaignSource(), ActiveCampaignSourceConfig(api_url=api_url, api_key="test-key"))
+
+
class TestNormalizeBaseUrl:
@pytest.mark.parametrize(
("raw", "expected"),
@@ -56,55 +64,8 @@ class TestActiveCampaignPaginator:
assert paginator.get_resume_state() is None
-def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:
- resp = Response()
- resp.status_code = status_code
- resp._content = json.dumps(body).encode()
- resp.headers["Content-Type"] = "application/json"
- return resp
-
-
class TestActiveCampaignSourceResumeBehavior:
- """End-to-end resume behaviour of ``active_campaign_source`` via ``rest_api_resource``."""
-
- def _drive(
- self, endpoint: str, manager: MagicMock, responses: list[Response]
- ) -> tuple[MagicMock, list[dict[str, Any]]]:
- sent_params: list[dict[str, Any]] = []
- response_iter = iter(responses)
-
- def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
- sent_params.append(dict(request.params or {}))
- return next(response_iter)
-
- with (
- # The pipeline path builds its own (no-redirect) session and hands it to
- # RESTClient via config, so patch the factory where the source imports it.
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.active_campaign.active_campaign.make_tracked_session"
- ) as MockSession,
- # The SSRF guard runs real DNS resolution when DEBUG=False (as in CI); the
- # fake account host here isn't an SSRF test, so allow it deterministically.
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.active_campaign.active_campaign.is_url_allowed",
- return_value=(True, None),
- ),
- ):
- mock_session = MockSession.return_value
- mock_session.headers = {}
- mock_session.prepare_request.side_effect = lambda req: req
- mock_session.send.side_effect = fake_send
-
- source = active_campaign_source(
- api_url="https://acme.api-us1.com",
- api_key="test-key",
- endpoint=endpoint,
- team_id=123,
- job_id="test_job",
- resumable_source_manager=manager,
- )
- list(cast(Iterable[Any], source.items()))
- return mock_session, sent_params
+ """Tests how the source resumes through the pipeline."""
def _page_body(self, endpoint: str, items: list[dict[str, Any]], total: Any) -> dict[str, Any]:
selector = ACTIVE_CAMPAIGN_ENDPOINTS[endpoint].data_selector
@@ -114,44 +75,40 @@ class TestActiveCampaignSourceResumeBehavior:
"endpoint", ["contacts", "deals", "lists", "campaigns", "deal_activities", "contact_automations"]
)
def test_fresh_run_saves_offset_after_each_non_terminal_page(self, endpoint: str) -> None:
- manager = MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = False
-
- responses = [
- _make_http_response(self._page_body(endpoint, _full_page(), 150)),
- _make_http_response(self._page_body(endpoint, [{"id": "x"}], 150)),
- ]
- _, sent_params = self._drive(endpoint, manager, responses)
+ result = _driver().run(
+ endpoint,
+ [
+ ScriptedResponse(json=self._page_body(endpoint, _full_page(), 150)),
+ ScriptedResponse(json=self._page_body(endpoint, [{"id": "x"}], 150)),
+ ],
+ )
# First request starts at offset 0; the second carries the advanced offset.
- assert [p.get("offset") for p in sent_params] == [0, PAGE_SIZE]
-
- saved = [call.args[0] for call in manager.save_state.call_args_list]
- assert saved == [ActiveCampaignResumeConfig(offset=PAGE_SIZE)]
+ assert result.params("offset") == ["0", str(PAGE_SIZE)]
+ assert result.saved_states == [ActiveCampaignResumeConfig(offset=PAGE_SIZE)]
+ assert len(result.rows) == PAGE_SIZE + 1
+ assert result.raised is None
def test_resume_seeds_paginator_with_saved_offset(self) -> None:
- manager = MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = True
- manager.load_state.return_value = ActiveCampaignResumeConfig(offset=PAGE_SIZE)
+ result = _driver().run(
+ "contacts",
+ [ScriptedResponse(json=self._page_body("contacts", [{"id": "resumed"}], 150))],
+ resume_state=ActiveCampaignResumeConfig(offset=PAGE_SIZE),
+ )
- responses = [
- _make_http_response(self._page_body("contacts", [{"id": "resumed"}], 150)),
- ]
- _, sent_params = self._drive("contacts", manager, responses)
-
- assert [p.get("offset") for p in sent_params] == [PAGE_SIZE]
- manager.load_state.assert_called_once()
+ assert result.params("offset") == [str(PAGE_SIZE)]
+ assert result.rows == [{"id": "resumed"}]
+ assert result.raised is None
def test_does_not_load_state_when_cannot_resume(self) -> None:
- manager = MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = False
-
- responses = [
- _make_http_response(self._page_body("contacts", [{"id": "a"}], 1)),
- ]
- self._drive("contacts", manager, responses)
+ result = _driver().run(
+ "contacts",
+ [ScriptedResponse(json=self._page_body("contacts", [{"id": "a"}], 1))],
+ )
- manager.load_state.assert_not_called()
+ assert result.params("offset") == ["0"]
+ assert result.rows == [{"id": "a"}]
+ assert result.raised is None
class TestValidateCredentials:
@@ -165,28 +122,13 @@ class TestValidateCredentials:
],
)
def test_status_code_mapping(self, status_code: int, expected_valid: bool) -> None:
- # Isolate status-code handling from the SSRF guard (which does real DNS when DEBUG=False).
- with (
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.active_campaign.active_campaign.make_tracked_session"
- ) as MockSession,
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.active_campaign.active_campaign.is_url_allowed",
- return_value=(True, None),
- ),
- ):
- mock_session = MockSession.return_value
- response = MagicMock()
- response.status_code = status_code
- response.is_redirect = False
- mock_session.get.return_value = response
-
+ with scripted_network(always(ScriptedResponse(status=status_code, json={}))) as network:
valid, error = validate_credentials("https://acme.api-us1.com", "test-key")
- assert valid is expected_valid
- if expected_valid:
- assert error is None
- else:
- assert error is not None
+
+ assert valid is expected_valid
+ assert (error is None) is expected_valid
+ assert network.requests_log[0].path == "/api/3/contacts"
+ assert network.requests_log[0].param("limit") == "1"
def test_rejects_non_https_url(self) -> None:
valid, error = validate_credentials("http://acme.api-us1.com", "test-key")
@@ -194,67 +136,33 @@ class TestValidateCredentials:
assert error is not None and "https" in error
def test_network_error_returns_message(self) -> None:
- with (
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.active_campaign.active_campaign.make_tracked_session"
- ) as MockSession,
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.active_campaign.active_campaign.is_url_allowed",
- return_value=(True, None),
- ),
- ):
- MockSession.return_value.get.side_effect = Exception("boom")
+ with scripted_network([Exception("boom")]):
valid, error = validate_credentials("https://acme.api-us1.com", "test-key")
- assert valid is False
- assert error == "boom"
+
+ assert valid is False
+ assert error == "boom"
def test_does_not_follow_redirects(self) -> None:
# Redirect-based SSRF guard: even a host that passes validation must not be
# allowed to 3xx-redirect onto an internal host, so the request disables it.
- with (
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.active_campaign.active_campaign.make_tracked_session"
- ) as MockSession,
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.active_campaign.active_campaign.is_url_allowed",
- return_value=(True, None),
- ),
- ):
- mock_session = MockSession.return_value
- response = MagicMock()
- response.status_code = 302
- response.is_redirect = True
- mock_session.get.return_value = response
-
+ with scripted_network(
+ [ScriptedResponse(status=302, headers={"Location": "https://169.254.169.254/metadata"})]
+ ) as network:
valid, error = validate_credentials("https://acme.api-us1.com", "test-key")
- assert valid is False
- assert error is not None
- assert mock_session.get.call_args.kwargs["allow_redirects"] is False
+ assert valid is False
+ assert error is not None
+ assert len(network.requests_log) == 1
def test_redirect_returns_actionable_account_name_message(self) -> None:
# A redirect means the account name in the URL is likely wrong — surface that
# instead of a bare status code.
- with (
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.active_campaign.active_campaign.make_tracked_session"
- ) as MockSession,
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.active_campaign.active_campaign.is_url_allowed",
- return_value=(True, None),
- ),
- ):
- mock_session = MockSession.return_value
- response = MagicMock()
- response.status_code = 302
- response.is_redirect = True
- mock_session.get.return_value = response
-
+ with scripted_network([ScriptedResponse(status=302, headers={"Location": "/login"})]):
valid, error = validate_credentials("https://acme.api-us1.com", "test-key")
- assert valid is False
- assert error is not None and "account name" in error
- assert "status code" not in error
+ assert valid is False
+ assert error is not None and "account name" in error
+ assert "status code" not in error
class TestSsrfProtection:
@@ -267,44 +175,17 @@ class TestSsrfProtection:
assert error is not None and "not allowed" in error
def test_source_for_pipeline_blocks_internal_host(self) -> None:
- manager = MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = False
-
- with (
- patch("posthog.security.url_validation.is_dev_mode", return_value=False),
- pytest.raises(ValueError, match="not allowed"),
- ):
- active_campaign_source(
- api_url="https://169.254.169.254",
- api_key="test-key",
- endpoint="contacts",
- team_id=123,
- job_id="test_job",
- resumable_source_manager=manager,
- )
+ with patch("posthog.security.url_validation.is_dev_mode", return_value=False):
+ result = _driver("https://169.254.169.254").run("contacts", [])
+
+ assert isinstance(result.raised, ValueError)
+ assert "not allowed" in str(result.raised)
+ assert result.requests == []
def test_source_for_pipeline_disables_redirects(self) -> None:
# The sync path hands RESTClient a session built with redirects off, so a
# 3xx to an internal host can't be followed during a sync either.
- manager = MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = False
-
- with (
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.active_campaign.active_campaign.make_tracked_session"
- ) as MockSession,
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.active_campaign.active_campaign.is_url_allowed",
- return_value=(True, None),
- ),
- ):
- active_campaign_source(
- api_url="https://acme.api-us1.com",
- api_key="test-key",
- endpoint="contacts",
- team_id=123,
- job_id="test_job",
- resumable_source_manager=manager,
- )
-
- assert MockSession.call_args.kwargs["allow_redirects"] is False
+ result = _driver().run("contacts", [ScriptedResponse(json={"contacts": [], "meta": {"total": 0}})])
+
+ assert result.session_options[0]["allow_redirects"] is False
+ assert result.raised is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/tests/test_adjust.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/tests/test_adjust.py
index 5b40aa8a05ca..e9be0457ad0f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/tests/test_adjust.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/tests/test_adjust.py
@@ -1,7 +1,5 @@
-from collections.abc import Iterable
from datetime import UTC, date, datetime
-from typing import Any, cast
-from urllib.parse import parse_qs, urlparse
+from typing import Any
import pytest
from unittest import mock
@@ -14,11 +12,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.adjust imp
from products.warehouse_sources.backend.temporal.data_imports.sources.adjust.adjust import (
MAX_HISTORY_DAYS,
MAX_PAGES_PER_WINDOW,
- REPORT_URL,
AdjustCredentialsError,
AdjustResumeConfig,
AdjustRetryableError,
- adjust_source,
build_report_params,
date_windows,
extract_rows,
@@ -29,7 +25,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.adjust.adj
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.adjust.settings import ADJUST_REPORTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.adjust.source import AdjustSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ RecordedRequest,
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.adjust import AdjustSourceConfig
TODAY = date(2024, 6, 30)
@@ -80,15 +85,20 @@ class _FakeResumeManager(ResumableSourceManager[AdjustResumeConfig]):
self.saved.append(data)
-def _params(url: str) -> dict[str, str]:
- return {key: values[0] for key, values in parse_qs(urlparse(url).query).items()}
-
-
def _page(rows: list[dict[str, Any]], next_url: str | None = None) -> _FakeResponse:
pagination = {"next": next_url} if next_url else None
return _FakeResponse(json_data={"rows": rows, "totals": {}, "pagination": pagination})
+def _scripted_page(rows: list[dict[str, Any]], next_url: str | None = None) -> ScriptedResponse:
+ pagination = {"next": next_url} if next_url else None
+ return ScriptedResponse(json={"rows": rows, "totals": {}, "pagination": pagination})
+
+
+def _driver() -> SourceDriver:
+ return SourceDriver(AdjustSource(), AdjustSourceConfig(api_token="token"))
+
+
def _run_get_rows(
session: _FakeSession,
report: str = "daily_report",
@@ -157,18 +167,32 @@ class TestBuildReportParams:
class TestRequest:
@parameterized.expand([(429,), (500,), (502,), (503,)])
def test_throttle_and_5xx_are_retryable(self, status: int) -> None:
- session = _FakeSession([_FakeResponse(status_code=status)])
- with pytest.raises(AdjustRetryableError):
- adjust._request(cast(requests.Session, session), REPORT_URL, mock.MagicMock())
+ with mock.patch.object(adjust, "_today", return_value=TODAY):
+ result = _driver().run(
+ "daily_report",
+ always(ScriptedResponse(status=status)),
+ incremental_field="day",
+ db_incremental_field_last_value="2024-06-30",
+ )
+
+ assert isinstance(result.raised, AdjustRetryableError)
+ assert len(result.requests) > 1
@parameterized.expand([(400,), (401,), (403,), (404,), (422,)])
def test_client_errors_raise_http_error_with_url(self, status: int) -> None:
- session = _FakeSession([_FakeResponse(status_code=status, text="nope")])
- with pytest.raises(requests.HTTPError) as exc:
- adjust._request(cast(requests.Session, session), REPORT_URL, mock.MagicMock())
+ with mock.patch.object(adjust, "_today", return_value=TODAY):
+ result = _driver().run(
+ "daily_report",
+ # A JSON body that is not an object: the error message must still build.
+ [ScriptedResponse(status=status, body=b"null")],
+ incremental_field="day",
+ db_incremental_field_last_value="2024-06-30",
+ )
+
+ assert isinstance(result.raised, requests.HTTPError)
# get_non_retryable_errors matches on the status text plus the host, so both must be present.
- assert str(status) in str(exc.value)
- assert "https://automate.adjust.com" in str(exc.value)
+ assert str(status) in str(result.raised)
+ assert "https://automate.adjust.com" in str(result.raised)
@parameterized.expand(
[
@@ -178,20 +202,38 @@ class TestRequest:
]
)
def test_error_body_detail_is_surfaced(self, _name: str, body: dict[str, Any], expected: str) -> None:
- session = _FakeSession([_FakeResponse(status_code=400, json_data=body)])
- with pytest.raises(requests.HTTPError) as exc:
- adjust._request(cast(requests.Session, session), REPORT_URL, mock.MagicMock())
- assert expected in str(exc.value)
+ with mock.patch.object(adjust, "_today", return_value=TODAY):
+ result = _driver().run(
+ "daily_report",
+ [ScriptedResponse(status=400, json=body)],
+ incremental_field="day",
+ db_incremental_field_last_value="2024-06-30",
+ )
+
+ assert isinstance(result.raised, requests.HTTPError)
+ assert expected in str(result.raised)
def test_non_json_error_body_does_not_break_error_construction(self) -> None:
- session = _FakeSession([_FakeResponse(status_code=400, json_data=ValueError("no json"), text="<html>")])
- with pytest.raises(requests.HTTPError):
- adjust._request(cast(requests.Session, session), REPORT_URL, mock.MagicMock())
+ with mock.patch.object(adjust, "_today", return_value=TODAY):
+ result = _driver().run(
+ "daily_report",
+ [ScriptedResponse(status=400, body=b"<html>")],
+ incremental_field="day",
+ db_incremental_field_last_value="2024-06-30",
+ )
+
+ assert isinstance(result.raised, requests.HTTPError)
def test_non_dict_payload_raises(self) -> None:
- session = _FakeSession([_FakeResponse(json_data=[{"day": "2024-01-01"}])])
- with pytest.raises(ValueError):
- adjust._request(cast(requests.Session, session), REPORT_URL, mock.MagicMock())
+ with mock.patch.object(adjust, "_today", return_value=TODAY):
+ result = _driver().run(
+ "daily_report",
+ [ScriptedResponse(json=[{"day": "2024-01-01"}])],
+ incremental_field="day",
+ db_incremental_field_last_value="2024-06-30",
+ )
+
+ assert isinstance(result.raised, ValueError)
class TestExtractRows:
@@ -282,16 +324,17 @@ class TestGetRows:
assert len(batches) == MAX_PAGES_PER_WINDOW
def test_resume_skips_windows_already_completed(self) -> None:
- session = _FakeSession([_page([{"day": "2024-06-05"}]) for _ in range(2)])
- manager = _FakeResumeManager(AdjustResumeConfig(next_start_date="2024-05-28"))
- _run_get_rows(
- session,
- manager=manager,
- should_use_incremental_field=True,
- db_incremental_field_last_value="2024-05-01",
- )
+ with mock.patch.object(adjust, "_today", return_value=TODAY):
+ result = _driver().run(
+ "daily_report",
+ [_scripted_page([{"day": "2024-06-05"}]) for _ in range(2)],
+ resume_state=AdjustResumeConfig(next_start_date="2024-05-28"),
+ incremental_field="day",
+ db_incremental_field_last_value="2024-05-01",
+ )
- assert [_params(url)["date_period"] for url in session.requested_urls] == [
+ assert result.raised is None
+ assert result.params("date_period") == [
"2024-05-28:2024-06-26",
"2024-06-27:2024-06-30",
]
@@ -300,55 +343,58 @@ class TestGetRows:
# The tracked session owns 429/5xx retries. Anything that reaches get_rows has already been
# retried, so it must propagate for Temporal to retry the job rather than being re-looped
# here (which would multiply the request count against Adjust's rate limit).
- session = _FakeSession([_FakeResponse(status_code=429), _page([{"day": "2024-06-30"}])])
- with pytest.raises(AdjustRetryableError):
- _run_get_rows(session, should_use_incremental_field=True, db_incremental_field_last_value="2024-06-30")
- assert len(session.requested_urls) == 1
+ with mock.patch.object(adjust, "_today", return_value=TODAY):
+ result = _driver().run(
+ "daily_report",
+ always(ScriptedResponse(status=429)),
+ incremental_field="day",
+ db_incremental_field_last_value="2024-06-30",
+ )
+
+ assert isinstance(result.raised, AdjustRetryableError)
+ assert len(result.requests) == 4
class TestValidateCredentials:
- def _validate(self, response: _FakeResponse, app_tokens: str | None = None) -> bool:
- session = _FakeSession([response])
- with mock.patch.object(adjust, "make_tracked_session", return_value=session):
+ def _validate(self, response: ScriptedResponse, app_tokens: str | None = None) -> bool:
+ with scripted_network(always(response)):
return validate_credentials("token", app_tokens)
def test_probe_is_minimal_and_includes_app_token_filter(self) -> None:
- session = _FakeSession([_FakeResponse(json_data={"rows": []})])
- with mock.patch.object(adjust, "make_tracked_session", return_value=session):
+ with scripted_network([ScriptedResponse(json={"rows": []})]) as network:
validate_credentials("token", "abc123")
- params = _params(session.requested_urls[0])
- assert params["dimensions"] == "day"
- assert params["metrics"] == "installs"
- assert params["app_token__in"] == "abc123"
+ assert network.requests_log[0].param("dimensions") == "day"
+ assert network.requests_log[0].param("metrics") == "installs"
+ assert network.requests_log[0].param("app_token__in") == "abc123"
@parameterized.expand([(429,), (500,), (503,)])
def test_throttle_and_5xx_are_retryable(self, status: int) -> None:
with pytest.raises(AdjustRetryableError):
- self._validate(_FakeResponse(status_code=status))
+ self._validate(ScriptedResponse(status=status))
@parameterized.expand([(401, "API token"), (403, "denied access"), (400, "app tokens"), (404, "app tokens")])
def test_rejections_are_credential_errors_with_specific_messages(self, status: int, expected: str) -> None:
with pytest.raises(AdjustCredentialsError) as exc:
- self._validate(_FakeResponse(status_code=status))
+ self._validate(ScriptedResponse(status=status))
assert expected in str(exc.value)
def test_unexpected_status_does_not_blame_the_token(self) -> None:
with pytest.raises(AdjustCredentialsError) as exc:
- self._validate(_FakeResponse(status_code=418))
+ self._validate(ScriptedResponse(status=418))
assert "unexpected response (HTTP 418)" in str(exc.value)
def test_malformed_app_token_fails_before_any_request(self) -> None:
- session = _FakeSession([])
- with mock.patch.object(adjust, "make_tracked_session", return_value=session):
+ with scripted_network([]) as network:
with pytest.raises(AdjustCredentialsError):
validate_credentials("token", "abc 123")
- assert session.requested_urls == []
+ assert network.requests_log == []
def test_transport_errors_propagate(self) -> None:
- session = mock.MagicMock()
- session.get.side_effect = requests.ConnectionError("boom")
- with mock.patch.object(adjust, "make_tracked_session", return_value=session):
+ def reset_connection(_request: RecordedRequest) -> ScriptedResponse:
+ raise ConnectionResetError("boom")
+
+ with scripted_network(reset_connection):
with pytest.raises(requests.ConnectionError):
validate_credentials("token")
@@ -356,14 +402,17 @@ class TestValidateCredentials:
class TestAdjustSource:
@parameterized.expand([(name,) for name in ADJUST_REPORTS])
def test_source_response_shape(self, name: str) -> None:
- response = adjust_source(
- api_token="token",
- app_tokens=None,
- report=name,
- logger=mock.MagicMock(),
- resumable_source_manager=_FakeResumeManager(),
- )
+ with mock.patch.object(adjust, "_today", return_value=TODAY):
+ result = _driver().run(
+ name,
+ [_scripted_page([])],
+ incremental_field="day",
+ db_incremental_field_last_value="2024-06-30",
+ )
+ assert result.raised is None
+ response = result.response
+ assert response is not None
assert response.name == name
assert response.primary_keys == ADJUST_REPORTS[name].primary_keys
# Windows are walked oldest-first and each report is sorted by day, so rows arrive ascending.
@@ -378,20 +427,13 @@ class TestAdjustSource:
validate_incremental_sync(True, response)
def test_items_streams_rows(self) -> None:
- session = _FakeSession([_page([{"day": "2024-06-30", "installs": "3"}])])
- with (
- mock.patch.object(adjust, "make_tracked_session", return_value=session),
- mock.patch.object(adjust, "_today", return_value=TODAY),
- ):
- response = adjust_source(
- api_token="token",
- app_tokens=None,
- report="daily_report",
- logger=mock.MagicMock(),
- resumable_source_manager=_FakeResumeManager(),
- should_use_incremental_field=True,
+ with mock.patch.object(adjust, "_today", return_value=TODAY):
+ result = _driver().run(
+ "daily_report",
+ [_scripted_page([{"day": "2024-06-30", "installs": "3"}])],
+ incremental_field="day",
db_incremental_field_last_value="2024-06-30",
)
- batches = list(cast(Iterable[Any], response.items()))
- assert batches == [[{"day": "2024-06-30", "installs": "3"}]]
+ assert result.raised is None
+ assert result.items == [[{"day": "2024-06-30", "installs": "3"}]]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/tests/test_adjust_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/tests/test_adjust_source.py
index fcea575d5bec..d2ad25dc7984 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/tests/test_adjust_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adjust/tests/test_adjust_source.py
@@ -1,17 +1,19 @@
+from datetime import date
+
import pytest
from unittest import mock
-import requests
-
-from products.warehouse_sources.backend.temporal.data_imports.sources.adjust.adjust import (
- AdjustCredentialsError,
- AdjustRetryableError,
-)
+from products.warehouse_sources.backend.temporal.data_imports.sources.adjust import adjust
from products.warehouse_sources.backend.temporal.data_imports.sources.adjust.source import AdjustSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ RecordedRequest,
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.adjust import AdjustSourceConfig
-_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.adjust.source"
-
class TestAdjustSource:
def setup_method(self) -> None:
@@ -38,46 +40,48 @@ class TestAdjustSource:
)
assert any(key in observed_error for key in self.source.get_retryable_errors())
- @mock.patch(f"{_SOURCE_MODULE}.validate_adjust_credentials")
- def test_validate_credentials_success(self, mock_validate: mock.MagicMock) -> None:
- mock_validate.return_value = True
-
- assert self.source.validate_credentials(self.config, self.team_id) == (True, None)
- mock_validate.assert_called_once_with("adjust-token", "abc123")
+ def test_validate_credentials_success(self) -> None:
+ with scripted_network([ScriptedResponse(status=200)]) as network:
+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)
- @mock.patch(f"{_SOURCE_MODULE}.validate_adjust_credentials")
- def test_validate_credentials_surfaces_the_specific_rejection(self, mock_validate: mock.MagicMock) -> None:
- mock_validate.side_effect = AdjustCredentialsError("Adjust rejected the API token.")
+ assert network.requests_log[0].headers["authorization"] == "Bearer adjust-token"
+ assert network.requests_log[0].param("app_token__in") == "abc123"
- is_valid, message = self.source.validate_credentials(self.config, self.team_id)
+ def test_validate_credentials_surfaces_the_specific_rejection(self) -> None:
+ with scripted_network([ScriptedResponse(status=401)]):
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id)
assert is_valid is False
- assert message == "Adjust rejected the API token."
+ assert message == (
+ "Adjust rejected the API token. Check that you pasted a valid Adjust API token from "
+ "your account settings in the Adjust dashboard."
+ )
@pytest.mark.parametrize(
- "raised",
- [AdjustRetryableError("status=503"), requests.ConnectionError("boom"), requests.ReadTimeout("slow")],
+ "response",
+ [ScriptedResponse(status=503), ConnectionResetError("boom"), TimeoutError("slow")],
)
- @mock.patch(f"{_SOURCE_MODULE}.validate_adjust_credentials")
- def test_transient_failures_are_not_reported_as_bad_credentials(
- self, mock_validate: mock.MagicMock, raised: Exception
- ) -> None:
- mock_validate.side_effect = raised
+ def test_transient_failures_are_not_reported_as_bad_credentials(self, response: ScriptedResponse | OSError) -> None:
+ def answer(_request: RecordedRequest) -> ScriptedResponse:
+ if isinstance(response, OSError):
+ raise response
+ return response
- is_valid, message = self.source.validate_credentials(self.config, self.team_id)
+ with scripted_network(answer):
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id)
assert is_valid is False
assert message is not None
assert "temporary rate-limit or network issue" in message
- @mock.patch(f"{_SOURCE_MODULE}.adjust_source")
- def test_source_for_pipeline_drops_watermark_when_not_incremental(self, mock_source: mock.MagicMock) -> None:
- inputs = mock.MagicMock()
- inputs.schema_name = "daily_report"
- inputs.should_use_incremental_field = False
- inputs.db_incremental_field_last_value = "2024-06-01"
-
- self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+ def test_source_for_pipeline_drops_watermark_when_not_incremental(self) -> None:
+ with mock.patch.object(adjust, "_today", return_value=date(2024, 6, 30)):
+ result = SourceDriver(self.source, self.config).run(
+ "daily_report",
+ always(ScriptedResponse(json={"rows": []})),
+ db_incremental_field_last_value="2024-06-01",
+ )
# A full refresh must not inherit a stale watermark and silently skip history.
- assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+ assert result.raised is None
+ assert result.requests[0].param("date_period") == "2022-07-01:2022-07-30"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/tests/test_adobe_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/tests/test_adobe_analytics.py
index 20c0dbd211b6..f25b02b3f437 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/tests/test_adobe_analytics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/tests/test_adobe_analytics.py
@@ -12,7 +12,6 @@ from structlog.types import FilteringBoundLogger
from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_analytics.adobe_analytics import (
AdobeAnalyticsClient,
AdobeAnalyticsResumeConfig,
- adobe_analytics_source,
get_rows,
metric_column_names,
parse_date,
@@ -21,7 +20,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_anal
resolve_window,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_analytics.source import AdobeAnalyticsSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.adobeanalytics import (
+ AdobeAnalyticsSourceConfig,
+)
_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.adobe_analytics.adobe_analytics"
@@ -64,6 +72,23 @@ def _response(body: Any, status: int = 200) -> mock.MagicMock:
return response
+def _driver(start_date: str | None = None) -> SourceDriver:
+ return SourceDriver(
+ AdobeAnalyticsSource(),
+ AdobeAnalyticsSourceConfig(
+ client_id="cid",
+ client_secret="sec",
+ global_company_id="gcid",
+ report_suite_id="rs1",
+ start_date=start_date,
+ ),
+ )
+
+
+def _token() -> ScriptedResponse:
+ return ScriptedResponse(json={"access_token": "tok", "expires_in": 86399})
+
+
def _report_payload(rows: list[dict[str, Any]], last_page: bool = True, total_pages: int | None = 1) -> dict[str, Any]:
payload: dict[str, Any] = {"rows": rows, "lastPage": last_page}
if total_pages is not None:
@@ -85,12 +110,6 @@ def _sessions() -> Iterator[tuple[mock.MagicMock, mock.MagicMock]]:
yield api, auth
[email protected](autouse=True)
-def _no_sleep() -> Iterator[mock.MagicMock]:
- with mock.patch(f"{_MODULE}.time.sleep") as sleep:
- yield sleep
-
-
def _get_rows(
api_side_effect: list[mock.MagicMock] | None,
post_side_effect: list[mock.MagicMock] | None,
@@ -226,70 +245,102 @@ class TestReportRows:
class TestClientAuth:
def test_401_remints_the_token_once_and_retries(self) -> None:
- with _sessions() as (api, auth):
- api.get.side_effect = [_response({}, 401), _response({"content": [{"id": "s1"}]})]
+ with scripted_network(
+ [
+ _token(),
+ ScriptedResponse(status=401, json={}),
+ _token(),
+ ScriptedResponse(json={"content": [{"id": "s1"}]}),
+ ]
+ ) as network:
client = AdobeAnalyticsClient("cid", "sec", _LOGGER, "gcid", min_request_interval=0)
assert client.get_json("/segments") == {"content": [{"id": "s1"}]}
- assert auth.post.call_count == 2
- assert api.get.call_count == 2
+ assert network.requests_log[0].path == "/ims/token/v3"
+ assert [request.path for request in network.requests_log] == [
+ "/ims/token/v3",
+ "/api/gcid/segments",
+ "/ims/token/v3",
+ "/api/gcid/segments",
+ ]
def test_persistent_401_raises(self) -> None:
- with _sessions() as (api, _auth):
- api.get.side_effect = [_response({}, 401), _response({}, 401)]
+ with scripted_network(
+ [_token(), ScriptedResponse(status=401), _token(), ScriptedResponse(status=401)]
+ ) as network:
client = AdobeAnalyticsClient("cid", "sec", _LOGGER, "gcid", min_request_interval=0)
with pytest.raises(requests.HTTPError):
client.get_json("/segments")
+ assert [request.path for request in network.requests_log] == [
+ "/ims/token/v3",
+ "/api/gcid/segments",
+ "/ims/token/v3",
+ "/api/gcid/segments",
+ ]
@pytest.mark.parametrize("status", [400, 403, 404])
def test_error_statuses_raise(self, status: int) -> None:
- with _sessions() as (api, _auth):
- api.get.return_value = _response({}, status)
+ with scripted_network([_token(), ScriptedResponse(status=status, json={})]) as network:
client = AdobeAnalyticsClient("cid", "sec", _LOGGER, "gcid", min_request_interval=0)
with pytest.raises(requests.HTTPError):
client.get_json("/segments")
+ assert [request.path for request in network.requests_log] == ["/ims/token/v3", "/api/gcid/segments"]
class TestGlobalCompanyIdDiscovery:
@pytest.mark.parametrize("payload", [{}, {"imsOrgs": []}, {"imsOrgs": [{"companies": []}]}])
def test_missing_company_raises_actionable_error(self, payload: dict[str, Any]) -> None:
- with _sessions() as (api, _auth):
- api.get.return_value = _response(payload)
+ with scripted_network([_token(), ScriptedResponse(json=payload)]) as network:
client = AdobeAnalyticsClient("cid", "sec", _LOGGER, None, min_request_interval=0)
with pytest.raises(ValueError, match="global company ID"):
client.resolve_global_company_id()
+ assert [request.path for request in network.requests_log] == ["/ims/token/v3", "/discovery/me"]
class TestValidateCredentials:
def test_valid_credentials(self) -> None:
- with _sessions() as (api, _auth):
- api.get.return_value = _response({"content": []})
-
+ with scripted_network([_token(), ScriptedResponse(json={"content": []})]) as network:
assert validate_credentials("cid", "sec", "gcid", _LOGGER) == (True, None)
+ assert [request.path for request in network.requests_log] == [
+ "/ims/token/v3",
+ "/api/gcid/collections/suites",
+ ]
def test_bad_client_credentials_are_reported(self) -> None:
- with _sessions() as (api, _auth):
- api.get.return_value = _response({}, 401)
-
+ with scripted_network(
+ [_token(), ScriptedResponse(status=401), _token(), ScriptedResponse(status=401)]
+ ) as network:
valid, message = validate_credentials("cid", "sec", None, _LOGGER)
assert valid is False
assert message is not None and "client ID and secret" in message
+ assert [request.path for request in network.requests_log] == [
+ "/ims/token/v3",
+ "/discovery/me",
+ "/ims/token/v3",
+ "/discovery/me",
+ ]
def test_missing_product_profile_is_reported(self) -> None:
- with _sessions() as (api, _auth):
- api.get.side_effect = [
- _response({"imsOrgs": [{"companies": [{"globalCompanyId": "gcid"}]}]}),
- _response({}, 403),
+ with scripted_network(
+ [
+ _token(),
+ ScriptedResponse(json={"imsOrgs": [{"companies": [{"globalCompanyId": "gcid"}]}]}),
+ ScriptedResponse(status=403, json={}),
]
-
+ ) as network:
valid, message = validate_credentials("cid", "sec", None, _LOGGER)
assert valid is False
assert message is not None and "product profile" in message
+ assert [request.path for request in network.requests_log] == [
+ "/ims/token/v3",
+ "/discovery/me",
+ "/api/gcid/collections/suites",
+ ]
class TestMetadataEndpoints:
@@ -342,97 +393,51 @@ class TestMetadataEndpoints:
class TestReportEndpoint:
@mock.patch(f"{_MODULE}._today", return_value=date(2024, 1, 3))
def test_resumes_mid_window_from_saved_day_and_page(self, _mock_today: mock.MagicMock) -> None:
- manager = FakeResumeManager(AdobeAnalyticsResumeConfig(page=2, next_date="2024-01-03"))
-
- with _sessions() as (api, _auth):
- api.post.return_value = _response(_report_payload([]))
- list(
- get_rows(
- client_id="cid",
- client_secret="sec",
- global_company_id="gcid",
- report_suite_id="rs1",
- report_dimension=None,
- report_metrics=None,
- start_date="2024-01-01",
- endpoint="report",
- logger=_LOGGER,
- resumable_source_manager=manager,
- )
- )
+ result = _driver(start_date="2024-01-01").run(
+ "report",
+ [_token(), ScriptedResponse(json=_report_payload([]))],
+ resume_state=AdobeAnalyticsResumeConfig(page=2, next_date="2024-01-03"),
+ )
- assert api.post.call_count == 1
- body = api.post.call_args.kwargs["json"]
- assert body["globalFilters"][0]["dateRange"].startswith("2024-01-03")
- assert body["settings"]["page"] == 2
+ assert result.raised is None
+ assert result.paths == ["/ims/token/v3", "/api/gcid/reports"]
+ body = result.requests[1].json()
+ assert body["globalFilters"][0]["dateRange"].startswith("2024-01-03")
+ assert body["settings"]["page"] == 2
@mock.patch(f"{_MODULE}._today", return_value=date(2024, 3, 6))
def test_incremental_run_re_reads_the_restatement_window(self, _mock_today: mock.MagicMock) -> None:
- manager = FakeResumeManager()
-
- with _sessions() as (api, _auth):
- api.post.return_value = _response(_report_payload([]))
- list(
- get_rows(
- client_id="cid",
- client_secret="sec",
- global_company_id="gcid",
- report_suite_id="rs1",
- report_dimension=None,
- report_metrics=None,
- start_date="2020-01-01",
- endpoint="report",
- logger=_LOGGER,
- resumable_source_manager=manager,
- should_use_incremental_field=True,
- db_incremental_field_last_value="2024-03-05",
- )
- )
+ result = _driver(start_date="2020-01-01").run(
+ "report",
+ [_token(), *(ScriptedResponse(json=_report_payload([])) for _ in range(3))],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-03-05",
+ )
- days = [call.kwargs["json"]["globalFilters"][0]["dateRange"][:10] for call in api.post.call_args_list]
- assert days == ["2024-03-04", "2024-03-05", "2024-03-06"]
+ assert result.raised is None
+ assert result.paths == ["/ims/token/v3", "/api/gcid/reports", "/api/gcid/reports", "/api/gcid/reports"]
+ days = [request.json()["globalFilters"][0]["dateRange"][:10] for request in result.requests[1:]]
+ assert days == ["2024-03-04", "2024-03-05", "2024-03-06"]
@mock.patch(f"{_MODULE}.MAX_REPORT_PAGES", 3)
@mock.patch(f"{_MODULE}._today", return_value=date(2024, 1, 1))
def test_page_cap_terminates_a_report_that_never_signals_completion(self, _mock_today: mock.MagicMock) -> None:
- manager = FakeResumeManager()
+ # No `lastPage`, no `totalPages`, always rows — the cap is the only exit.
+ page = ScriptedResponse(json={"rows": [{"itemId": "1", "value": "a", "data": [1]}]})
+ result = _driver(start_date="2024-01-01").run("report", [_token(), page, page, page])
- with _sessions() as (api, _auth):
- # No `lastPage`, no `totalPages`, always rows — the cap is the only exit.
- api.post.return_value = _response({"rows": [{"itemId": "1", "value": "a", "data": [1]}]})
- batches = list(
- get_rows(
- client_id="cid",
- client_secret="sec",
- global_company_id="gcid",
- report_suite_id="rs1",
- report_dimension=None,
- report_metrics=None,
- start_date="2024-01-01",
- endpoint="report",
- logger=_LOGGER,
- resumable_source_manager=manager,
- )
- )
-
- assert len(batches) == 3
- assert api.post.call_count == 3
+ assert result.raised is None
+ assert len(result.items) == 3
+ assert result.paths == ["/ims/token/v3", "/api/gcid/reports", "/api/gcid/reports", "/api/gcid/reports"]
+ assert [request.json()["settings"]["page"] for request in result.requests[1:]] == [0, 1, 2]
class TestAdobeAnalyticsSourceResponse:
def test_metadata_tables_are_not_datetime_partitioned(self) -> None:
- response = adobe_analytics_source(
- client_id="cid",
- client_secret="sec",
- global_company_id="gcid",
- report_suite_id="rs1",
- report_dimension=None,
- report_metrics=None,
- start_date=None,
- endpoint="segments",
- logger=_LOGGER,
- resumable_source_manager=FakeResumeManager(),
- )
+ result = _driver().run("segments", [_token(), ScriptedResponse(json={"content": [], "lastPage": True})])
+ assert result.raised is None
+ response = result.response
+ assert response is not None
assert response.partition_mode is None
assert response.partition_keys is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/tests/test_adroll.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/tests/test_adroll.py
index 091614ab3f9d..b62af503f84c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/tests/test_adroll.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adroll/tests/test_adroll.py
@@ -1,89 +1,34 @@
-import json
from typing import Any
-from urllib.parse import parse_qs, urlparse
import pytest
-from unittest import mock
-
-from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.adroll.adroll import (
MAX_RETRY_ATTEMPTS,
AdRollResumeConfig,
- adroll_source,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.adroll.settings import ADROLL_ENDPOINTS, ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.adroll.source import AdRollSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
RESTClientRetryableError,
)
-
-# RESTClient builds its session via make_tracked_session in the rest_client module.
-CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
-# validate_credentials builds its own tracked session in the adroll module.
-ADROLL_SESSION_PATCH = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.adroll.adroll.make_tracked_session"
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.adroll import AdRollSourceConfig
CAMPAIGNS_PATH = ADROLL_ENDPOINTS["campaigns"].path
-ADS_PATH = ADROLL_ENDPOINTS["ads"].path
-
-
-def _response(results: list[dict[str, Any]] | None, *, drop_results: bool = False, status_code: int = 200) -> Response:
- body: dict[str, Any] = {}
- if not drop_results:
- body["results"] = results or []
- resp = Response()
- resp.status_code = status_code
- resp._content = json.dumps(body).encode()
- return resp
-
-
-def _error_response(status_code: int) -> Response:
- resp = Response()
- resp.status_code = status_code
- resp._content = b'{"error": "boom"}'
- return resp
-
-
-def _make_manager(resume_state: AdRollResumeConfig | None = None) -> mock.MagicMock:
- manager = mock.MagicMock()
- manager.can_resume.return_value = resume_state is not None
- manager.load_state.return_value = resume_state
- return manager
-
-
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
- """Wire a mock session and return snapshots of each request AT PREPARE TIME.
- ``request.params`` dicts can be mutated/rebuilt across requests, so snapshot a copy
- when each request is prepared instead of inspecting after the run.
- """
- session.headers = {}
- snapshots: list[dict[str, Any]] = []
- def _prepare(request: Any) -> mock.MagicMock:
- snapshots.append({"url": request.url, "params": dict(request.params or {}), "auth": request.auth})
- return mock.MagicMock()
+def _driver() -> SourceDriver:
+ return SourceDriver(AdRollSource(), AdRollSourceConfig(client_id="cid", personal_access_token="pat"))
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = responses
- return snapshots
-
-def _rows(source_response) -> list[dict[str, Any]]:
- return [row for page in source_response.items() for row in page]
-
-
-def _source(endpoint: str, manager: mock.MagicMock | None = None):
- return adroll_source(
- client_id="cid",
- personal_access_token="pat",
- endpoint=endpoint,
- team_id=1,
- job_id="j",
- resumable_source_manager=manager if manager is not None else _make_manager(),
- )
+def _page(results: list[dict[str, Any]]) -> ScriptedResponse:
+ return ScriptedResponse(json={"results": results})
class TestValidateCredentials:
@@ -96,101 +41,89 @@ class TestValidateCredentials:
(500, False),
],
)
- @mock.patch(ADROLL_SESSION_PATCH)
- def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):
- mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)
+ def test_validate_credentials_status_mapping(self, status_code: int, expected: bool) -> None:
+ with scripted_network(always(ScriptedResponse(status=status_code))) as network:
+ assert validate_credentials("cid", "pat") is expected
- assert validate_credentials("cid", "pat") is expected
+ assert network.requests_log[0].path == ADROLL_ENDPOINTS["organization"].path
+ assert network.requests_log[0].param("apikey") == "cid"
+ assert network.requests_log[0].headers["authorization"] == "Token pat"
class TestRows:
@pytest.mark.parametrize("endpoint", ["advertisable_reports", "campaign_reports", "ad_reports"])
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_report_endpoints_filter_by_advertisables_in_entity_format(self, MockSession, endpoint):
- session = MockSession.return_value
- snapshots = _wire(
- session,
+ def test_report_endpoints_filter_by_advertisables_in_entity_format(self, endpoint: str) -> None:
+ result = _driver().run(
+ endpoint,
[
- _response([{"eid": "ADV1"}]),
- _response([{"eid": "C1", "impressions": 5}]),
+ _page([{"eid": "ADV1"}]),
+ _page([{"eid": "C1", "impressions": 5}]),
],
)
- rows = _rows(_source(endpoint))
-
- assert rows == [{"eid": "C1", "impressions": 5, "_advertisable_eid": "ADV1"}]
- assert urlparse(snapshots[1]["url"]).path == ADROLL_ENDPOINTS[endpoint].path
+ assert result.raised is None
+ assert result.rows == [{"eid": "C1", "impressions": 5, "_advertisable_eid": "ADV1"}]
+ assert result.paths[1] == ADROLL_ENDPOINTS[endpoint].path
# The reporting endpoints take a list of advertisables, not a single one.
- assert parse_qs(urlparse(snapshots[1]["url"]).query)["advertisables"] == ["ADV1"]
- assert snapshots[1]["params"]["data_format"] == "entity"
+ assert result.requests[1].param("advertisables") == "ADV1"
+ assert result.requests[1].param("data_format") == "entity"
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_advertisables_without_eid_are_skipped(self, MockSession):
- session = MockSession.return_value
- _wire(session, [_response([{"name": "broken"}])])
+ def test_advertisables_without_eid_are_skipped(self) -> None:
+ result = _driver().run("ads", [_page([{"name": "broken"}])])
- assert _rows(_source("ads")) == []
- assert session.send.call_count == 1
+ assert result.raised is None
+ assert result.rows == []
+ assert len(result.requests) == 1
- @mock.patch("time.sleep")
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_retries_exhausted_raises(self, MockSession, _mock_sleep):
- session = MockSession.return_value
- _wire(session, [_error_response(500)] * MAX_RETRY_ATTEMPTS)
+ def test_retries_exhausted_raises(self) -> None:
+ result = _driver().run("advertisables", always(ScriptedResponse(status=500, json={"error": "boom"})))
- with pytest.raises(RESTClientRetryableError):
- _rows(_source("advertisables"))
+ assert isinstance(result.raised, RESTClientRetryableError)
+ assert len(result.requests) == MAX_RETRY_ATTEMPTS
- assert session.send.call_count == MAX_RETRY_ATTEMPTS
+ def test_non_retryable_client_error_raises(self) -> None:
+ result = _driver().run("advertisables", [ScriptedResponse(status=401, json={"error": "boom"})])
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_non_retryable_client_error_raises(self, MockSession):
- session = MockSession.return_value
- _wire(session, [_error_response(401)])
-
- with pytest.raises(Exception, match="401"):
- _rows(_source("advertisables"))
-
- assert session.send.call_count == 1
+ assert isinstance(result.raised, Exception)
+ assert "401" in str(result.raised)
+ assert len(result.requests) == 1
class TestFanOutResume:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_resume_skips_completed_advertisables(self, MockSession):
- session = MockSession.return_value
- snapshots = _wire(
- session,
+ def test_resume_skips_completed_advertisables(self) -> None:
+ result = _driver().run(
+ "campaigns",
[
- _response([{"eid": "ADV1"}, {"eid": "ADV2"}]),
- _response([{"eid": "C2"}]),
+ _page([{"eid": "ADV1"}, {"eid": "ADV2"}]),
+ _page([{"eid": "C2"}]),
],
- )
-
- manager = _make_manager(
- AdRollResumeConfig(
+ resume_state=AdRollResumeConfig(
fanout_state={
"completed": [f"{CAMPAIGNS_PATH}?advertisable=ADV1"],
"current": None,
"child_state": None,
}
- )
+ ),
)
- rows = _rows(_source("campaigns", manager))
# ADV1 was already synced — only the parent list and ADV2's campaigns are fetched.
- assert [(c["eid"], c["_advertisable_eid"]) for c in rows] == [("C2", "ADV2")]
- assert session.send.call_count == 2
- assert parse_qs(urlparse(snapshots[1]["url"]).query)["advertisable"] == ["ADV2"]
+ assert result.raised is None
+ assert [(row["eid"], row["_advertisable_eid"]) for row in result.rows] == [("C2", "ADV2")]
+ assert len(result.requests) == 2
+ assert result.requests[1].param("advertisable") == "ADV2"
class TestAdRollSourceResponse:
@pytest.mark.parametrize("endpoint", list(ENDPOINTS))
- def test_response_metadata_per_endpoint(self, endpoint):
+ def test_response_metadata_per_endpoint(self, endpoint: str) -> None:
config = ADROLL_ENDPOINTS[endpoint]
- response = _source(endpoint)
-
- assert response.name == endpoint
- assert response.primary_keys == [config.primary_key]
- assert response.sort_mode == "asc"
- assert response.partition_mode is None
- assert response.partition_keys is None
+ answer = ScriptedResponse(json={"eid": "ORG1"}) if endpoint == "organization" else _page([])
+ result = _driver().run(endpoint, [answer])
+
+ assert result.raised is None
+ assert result.response is not None
+ assert result.response.name == endpoint
+ assert result.response.primary_keys == [config.primary_key]
+ assert result.response.sort_mode == "asc"
+ assert result.response.partition_mode is None
+ assert result.response.partition_keys is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/tests/test_aftership.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/tests/test_aftership.py
index 6a669034f3ed..1e701d2f3817 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/tests/test_aftership.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/tests/test_aftership.py
@@ -1,76 +1,44 @@
-import json
-from collections.abc import Iterable
from datetime import UTC, datetime, timedelta, timezone
-from typing import Any, Optional, cast
-
-import pytest
-from unittest import mock
+from typing import Any, Optional
from parameterized import parameterized
-from requests import HTTPError, Response
+from requests import HTTPError
from products.warehouse_sources.backend.temporal.data_imports.sources.aftership.aftership import (
API_KEY_HEADER,
AftershipResumeConfig,
_to_aftership_datetime,
- aftership_source,
check_access,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.aftership.settings import DEFAULT_VERSION
+from products.warehouse_sources.backend.temporal.data_imports.sources.aftership.source import AftershipSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.aftership import (
+ AftershipSourceConfig,
+)
BASE_URL = f"https://api.aftership.com/tracking/{DEFAULT_VERSION}"
-# RESTClient builds its session via make_tracked_session in the rest_client module.
-CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
-PROBE_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.aftership.aftership.validate_via_probe"
-def _response(
+def _page(
key: str,
items: Optional[list[dict[str, Any]]] = None,
*,
next_cursor: Optional[str] = None,
status_code: int = 200,
-) -> Response:
+) -> ScriptedResponse:
data: dict[str, Any] = {key: items or []}
if next_cursor is not None:
data["pagination"] = {"next_cursor": next_cursor, "has_next_page": True}
- resp = Response()
- resp.status_code = status_code
- resp.url = f"{BASE_URL}/trackings"
- resp._content = json.dumps({"meta": {"code": 200}, "data": data}).encode()
- return resp
-
-
-def _make_manager(resume_state: Optional[AftershipResumeConfig] = None) -> mock.MagicMock:
- manager = mock.MagicMock()
- manager.can_resume.return_value = resume_state is not None
- manager.load_state.return_value = resume_state
- return manager
-
-
-def _wire(session: mock.MagicMock, responses: list[Response]) -> tuple[list[dict[str, Any]], list[str]]:
- # ``request.params`` is one dict mutated in place across pages, so snapshot a copy while each
- # request is prepared rather than reading it after the run.
- session.headers = {}
- param_snapshots: list[dict[str, Any]] = []
- url_snapshots: list[str] = []
+ return ScriptedResponse(status=status_code, json={"meta": {"code": 200}, "data": data})
- def _prepare(request: Any) -> mock.MagicMock:
- param_snapshots.append(dict(request.params or {}))
- url_snapshots.append(request.url)
- return mock.MagicMock()
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = responses
- return param_snapshots, url_snapshots
-
-
-def _rows(source_response: Any) -> list[dict[str, Any]]:
- return [row for page in cast("Iterable[Any]", source_response.items()) for row in page]
-
-
-def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any) -> Any:
- return aftership_source("key", endpoint, team_id=1, job_id="j", resumable_source_manager=manager, **kwargs)
+def _driver() -> SourceDriver:
+ return SourceDriver(AftershipSource(), AftershipSourceConfig(api_key="key"))
class TestToAftershipDatetime:
@@ -101,18 +69,14 @@ class TestToAftershipDatetime:
class TestPagination:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_couriers_is_single_page_and_never_sends_a_cursor(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
+ def test_couriers_is_single_page_and_never_sends_a_cursor(self) -> None:
# A next_cursor in the body must not restart pagination for an endpoint that has none.
- params, urls = _wire(session, [_response("couriers", [{"slug": "usps"}], next_cursor="cur-1")])
-
- rows = _rows(_source("couriers", _make_manager()))
+ result = _driver().run("couriers", [_page("couriers", [{"slug": "usps"}], next_cursor="cur-1")])
- assert [r["slug"] for r in rows] == ["usps"]
- assert session.send.call_count == 1
- assert urls[0] == f"{BASE_URL}/couriers"
- assert params[0] == {}
+ assert result.raised is None
+ assert [row["slug"] for row in result.rows] == ["usps"]
+ assert result.urls == [f"{BASE_URL}/couriers"]
+ assert result.queries == [{}]
class TestIncrementalFiltering:
@@ -122,25 +86,19 @@ class TestIncrementalFiltering:
("created_at", "created_at", "created_at_min"),
]
)
- @mock.patch(CLIENT_SESSION_PATCH)
def test_users_incremental_field_picks_the_server_side_filter(
- self, _name: str, incremental_field_name: str, expected_param: str, MockSession: mock.MagicMock
+ self, _name: str, incremental_field_name: str, expected_param: str
) -> None:
- session = MockSession.return_value
- params, _urls = _wire(session, [_response("trackings", [{"id": "1"}])])
-
- _rows(
- _source(
- "trackings",
- _make_manager(),
- should_use_incremental_field=True,
- incremental_field_name=incremental_field_name,
- db_incremental_field_last_value=datetime(2026, 1, 15, 12, 0, 0, tzinfo=UTC),
- )
+ result = _driver().run(
+ "trackings",
+ [_page("trackings", [{"id": "1"}])],
+ incremental_field=incremental_field_name,
+ db_incremental_field_last_value=datetime(2026, 1, 15, 12, 0, 0, tzinfo=UTC),
)
- assert params[0][expected_param] == "2026-01-15T12:00:00+00:00"
- assert len([key for key in params[0] if key.endswith("_min")]) == 1
+ assert result.raised is None
+ assert result.requests[0].param(expected_param) == "2026-01-15T12:00:00+00:00"
+ assert len([key for key in result.queries[0] if key.endswith("_min")]) == 1
@parameterized.expand(
[
@@ -148,91 +106,61 @@ class TestIncrementalFiltering:
("full_refresh_endpoint", "courier_connections", "updated_at"),
]
)
- @mock.patch(CLIENT_SESSION_PATCH)
def test_no_filter_sent_when_the_field_has_no_server_side_param(
- self, _name: str, endpoint: str, incremental_field_name: str, MockSession: mock.MagicMock
+ self, _name: str, endpoint: str, incremental_field_name: str
) -> None:
- session = MockSession.return_value
- params, _urls = _wire(session, [_response(endpoint, [])])
-
- _rows(
- _source(
- endpoint,
- _make_manager(),
- should_use_incremental_field=True,
- incremental_field_name=incremental_field_name,
- db_incremental_field_last_value=datetime(2026, 1, 15, tzinfo=UTC),
- )
+ result = _driver().run(
+ endpoint,
+ [_page(endpoint, [])],
+ incremental_field=incremental_field_name,
+ db_incremental_field_last_value=datetime(2026, 1, 15, tzinfo=UTC),
)
- assert not [key for key in params[0] if key.endswith("_min")]
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_filter_is_resent_on_every_page(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- params, _urls = _wire(
- session,
- [_response("trackings", [{"id": "1"}], next_cursor="cur-1"), _response("trackings", [{"id": "2"}])],
- )
+ assert result.raised is None
+ assert not [key for key in result.queries[0] if key.endswith("_min")]
- _rows(
- _source(
- "trackings",
- _make_manager(),
- should_use_incremental_field=True,
- incremental_field_name="updated_at",
- db_incremental_field_last_value=datetime(2026, 1, 15, tzinfo=UTC),
- )
+ def test_filter_is_resent_on_every_page(self) -> None:
+ result = _driver().run(
+ "trackings",
+ [_page("trackings", [{"id": "1"}], next_cursor="cur-1"), _page("trackings", [{"id": "2"}])],
+ incremental_field="updated_at",
+ db_incremental_field_last_value=datetime(2026, 1, 15, tzinfo=UTC),
)
- assert all(page["updated_at_min"] == "2026-01-15T00:00:00+00:00" for page in params)
+ assert result.raised is None
+ assert result.params("updated_at_min") == ["2026-01-15T00:00:00+00:00"] * 2
class TestResume:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_saves_cursor_and_window_after_yielding_each_page(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- _wire(
- session,
- [_response("trackings", [{"id": "1"}], next_cursor="cur-1"), _response("trackings", [{"id": "2"}])],
- )
-
- manager = _make_manager()
- _rows(
- _source(
- "trackings",
- manager,
- should_use_incremental_field=True,
- incremental_field_name="updated_at",
- db_incremental_field_last_value=datetime(2026, 1, 15, tzinfo=UTC),
- )
+ def test_saves_cursor_and_window_after_yielding_each_page(self) -> None:
+ result = _driver().run(
+ "trackings",
+ [_page("trackings", [{"id": "1"}], next_cursor="cur-1"), _page("trackings", [{"id": "2"}])],
+ incremental_field="updated_at",
+ db_incremental_field_last_value=datetime(2026, 1, 15, tzinfo=UTC),
)
- manager.save_state.assert_called_once_with(
+ assert result.raised is None
+ assert result.saved_states == [
AftershipResumeConfig(cursor="cur-1", incremental_start="2026-01-15T00:00:00+00:00")
+ ]
+ assert result.committed_states == result.saved_states
+
+ def test_resumes_from_saved_cursor_and_reuses_the_saved_window(self) -> None:
+ result = _driver().run(
+ "trackings",
+ [_page("trackings", [{"id": "9"}])],
+ resume_state=AftershipResumeConfig(cursor="cur-8", incremental_start="2026-01-01T00:00:00+00:00"),
+ incremental_field="updated_at",
+ # The watermark advanced from committed batches; narrowing the window mid-walk
+ # would leave the saved cursor pointing outside the filtered result set.
+ db_incremental_field_last_value=datetime(2026, 2, 1, tzinfo=UTC),
)
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_resumes_from_saved_cursor_and_reuses_the_saved_window(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- params, _urls = _wire(session, [_response("trackings", [{"id": "9"}])])
-
- manager = _make_manager(AftershipResumeConfig(cursor="cur-8", incremental_start="2026-01-01T00:00:00+00:00"))
- rows = _rows(
- _source(
- "trackings",
- manager,
- should_use_incremental_field=True,
- incremental_field_name="updated_at",
- # The watermark advanced from committed batches; narrowing the window mid-walk
- # would leave the saved cursor pointing outside the filtered result set.
- db_incremental_field_last_value=datetime(2026, 2, 1, tzinfo=UTC),
- )
- )
-
- assert [r["id"] for r in rows] == ["9"]
- assert params[0]["cursor"] == "cur-8"
- assert params[0]["updated_at_min"] == "2026-01-01T00:00:00+00:00"
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == ["9"]
+ assert result.params("cursor") == ["cur-8"]
+ assert result.params("updated_at_min") == ["2026-01-01T00:00:00+00:00"]
class TestSourceResponse:
@@ -246,8 +174,11 @@ class TestSourceResponse:
def test_primary_keys_and_partitioning(
self, _name: str, endpoint: str, expected_keys: list[str], expected_partition_keys: Optional[list[str]]
) -> None:
- response = _source(endpoint, _make_manager())
+ result = _driver().run(endpoint, [_page(endpoint, [])])
+ response = result.response
+ assert result.raised is None
+ assert response is not None
assert response.name == endpoint
assert response.primary_keys == expected_keys
assert response.partition_keys == expected_partition_keys
@@ -257,56 +188,33 @@ class TestSourceResponse:
class TestRequestShape:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_api_key_is_sent_in_the_as_api_key_header(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- session.headers = {}
- prepared: list[Any] = []
-
- def _prepare(request: Any) -> mock.MagicMock:
- fake = mock.MagicMock()
- fake.headers = {}
- fake.url = request.url
- # `auth` is a callable applied to the prepared request by the framework.
- prepared.append(request.auth(fake) if request.auth else fake)
- return fake
-
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = [_response("trackings", [])]
-
- _rows(_source("trackings", _make_manager()))
+ def test_api_key_is_sent_in_the_as_api_key_header(self) -> None:
+ result = _driver().run("trackings", [_page("trackings", [])])
+ assert result.raised is None
# The legacy `aftership-api-key` header stopped working at API version 2023-10.
- assert prepared[0].headers[API_KEY_HEADER] == "key"
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_api_version_is_a_path_segment(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- _params, urls = _wire(session, [_response("trackings", [])])
+ assert result.requests[0].headers[API_KEY_HEADER] == "key"
- _rows(_source("trackings", _make_manager(), api_version="2026-01"))
+ def test_api_version_is_a_path_segment(self) -> None:
+ result = _driver().run("trackings", [_page("trackings", [])], api_version="2026-01")
- assert urls[0] == "https://api.aftership.com/tracking/2026-01/trackings"
+ assert result.raised is None
+ assert result.paths == ["/tracking/2026-01/trackings"]
@parameterized.expand([(401,), (403,)])
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_auth_errors_raise_a_matchable_http_error(self, status_code: int, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- _wire(session, [_response("trackings", [], status_code=status_code)])
+ def test_auth_errors_raise_a_matchable_http_error(self, status_code: int) -> None:
+ result = _driver().run("trackings", [_page("trackings", [], status_code=status_code)])
- with pytest.raises(HTTPError) as exc:
- _rows(_source("trackings", _make_manager()))
- assert f"{status_code} Client Error" in str(exc.value)
+ assert isinstance(result.raised, HTTPError)
+ assert f"{status_code} Client Error" in str(result.raised)
class TestCourierConnectionRedaction:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_carrier_credentials_never_reach_the_warehouse(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- _wire(
- session,
+ def test_carrier_credentials_never_reach_the_warehouse(self) -> None:
+ result = _driver().run(
+ "courier_connections",
[
- _response(
+ _page(
"courier_connections",
[
{
@@ -320,9 +228,8 @@ class TestCourierConnectionRedaction:
],
)
- rows = _rows(_source("courier_connections", _make_manager()))
-
- assert rows == [{"id": "conn-1", "courier_slug": "dhl-api", "created_at": "2026-01-01T00:00:00+00:00"}]
+ assert result.raised is None
+ assert result.rows == [{"id": "conn-1", "courier_slug": "dhl-api", "created_at": "2026-01-01T00:00:00+00:00"}]
class TestCheckAccess:
@@ -333,21 +240,17 @@ class TestCheckAccess:
("single_page_endpoint", "couriers", f"{BASE_URL}/couriers"),
]
)
- @mock.patch(PROBE_PATCH)
- def test_probe_url_per_schema(
- self, _name: str, schema_name: Optional[str], expected_url: str, mock_probe: mock.MagicMock
- ) -> None:
- mock_probe.return_value = (True, 200)
-
- assert check_access("key", schema_name) == (True, 200)
- assert mock_probe.call_args.args[1] == expected_url
+ def test_probe_url_per_schema(self, _name: str, schema_name: Optional[str], expected_url: str) -> None:
+ with scripted_network([ScriptedResponse()]) as network:
+ assert check_access("key", schema_name) == (True, 200)
- @mock.patch(PROBE_PATCH)
- def test_probe_does_not_follow_redirects(self, mock_probe: mock.MagicMock) -> None:
- mock_probe.return_value = (True, 200)
+ assert network.requests_log[0].url == expected_url
- check_access("key")
+ def test_probe_does_not_follow_redirects(self) -> None:
+ redirect = ScriptedResponse(status=302, headers={"Location": "https://example.com/elsewhere"})
+ with scripted_network([redirect]) as network:
+ assert check_access("key") == (False, 302)
# The key rides a custom header, which requests would replay to a redirect target.
- assert mock_probe.call_args.kwargs["allow_redirects"] is False
- assert mock_probe.call_args.kwargs["headers"] == {API_KEY_HEADER: "key"}
+ assert len(network.requests_log) == 1
+ assert network.requests_log[0].headers[API_KEY_HEADER] == "key"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/tests/test_aftership_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/tests/test_aftership_source.py
index 00f0243ce7b3..f4fb18e003ec 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/tests/test_aftership_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aftership/tests/test_aftership_source.py
@@ -6,11 +6,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.aftership.
CANONICAL_DESCRIPTIONS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.aftership.source import AftershipSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ scripted_network,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.aftership import (
AftershipSourceConfig,
)
-CHECK_ACCESS_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.aftership.source.check_access"
AFTERSHIP_SOURCE_PATH = (
"products.warehouse_sources.backend.temporal.data_imports.sources.aftership.source.aftership_source"
)
@@ -42,28 +45,27 @@ class TestAftershipSource:
("unreachable", False, None, None, False, "Could not validate your AfterShip API key"),
]
)
- @mock.patch(CHECK_ACCESS_PATH)
def test_validate_credentials(
self,
_name: str,
- probe_valid: bool,
+ _probe_valid: bool,
status: int | None,
schema_name: str | None,
expected_valid: bool,
expected_message: str | None,
- mock_check: mock.MagicMock,
) -> None:
- mock_check.return_value = (probe_valid, status)
- is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+ answer = ConnectionResetError("reset") if status is None else ScriptedResponse(status=status)
+ with scripted_network([answer]):
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
assert is_valid is expected_valid
assert message == expected_message
- @mock.patch(CHECK_ACCESS_PATH)
- def test_validate_credentials_rejects_unknown_table_without_probing(self, mock_check: mock.MagicMock) -> None:
- is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name="not_a_table")
+ def test_validate_credentials_rejects_unknown_table_without_probing(self) -> None:
+ with scripted_network([]) as network:
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name="not_a_table")
assert is_valid is False
assert message == "Unknown AfterShip table 'not_a_table'"
- mock_check.assert_not_called()
+ assert network.requests_log == []
@parameterized.expand(
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm.py
index 3037613a9515..c2d061ab881f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm.py
@@ -1,77 +1,32 @@
-import json
-from typing import Any
-
import pytest
-from unittest import mock
from parameterized import parameterized
-from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.agilecrm import (
AgileCRMResumeConfig,
- agilecrm_source,
base_url,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.settings import AGILECRM_ENDPOINTS
-
-# RESTClient builds its session via make_tracked_session in the rest_client module.
-CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
-# validate_credentials builds its own tracked session in the agilecrm module.
-AGILECRM_SESSION_PATCH = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.agilecrm.make_tracked_session"
+from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.source import AgileCRMSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.agilecrm import (
+ AgileCRMSourceConfig,
)
PAGE_SIZE = AGILECRM_ENDPOINTS["contacts"].page_size
-def _response(body: Any) -> Response:
- # Agile CRM list endpoints return a bare JSON array as the body.
- resp = Response()
- resp.status_code = 200
- resp._content = json.dumps(body).encode()
- return resp
-
-
-def _make_manager(resume_state: AgileCRMResumeConfig | None = None) -> mock.MagicMock:
- manager = mock.MagicMock()
- manager.can_resume.return_value = resume_state is not None
- manager.load_state.return_value = resume_state
- return manager
-
-
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
- """Wire a mock session and return a list that captures each request's params AT SEND TIME.
+def _driver() -> SourceDriver:
+ return SourceDriver(AgileCRMSource(), AgileCRMSourceConfig(domain="acme", email="[email protected]", api_key="key"))
- ``request.params`` is a single dict mutated in place across pages, so inspecting it after the run
- shows only the final state — snapshot a copy when each request is prepared instead.
- """
- session.headers = {}
- param_snapshots: list[dict[str, Any]] = []
- def _prepare(request: Any) -> mock.MagicMock:
- param_snapshots.append(dict(request.params or {}))
- return mock.MagicMock()
-
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = responses
- return param_snapshots
-
-
-def _rows(source_response) -> list[dict[str, Any]]:
- return [row for page in source_response.items() for row in page]
-
-
-def _source(manager: mock.MagicMock, endpoint: str = "contacts"):
- return agilecrm_source(
- domain="acme",
- api_key="key",
- endpoint=endpoint,
- team_id=1,
- job_id="j",
- resumable_source_manager=manager,
- )
+def _page(rows: object) -> ScriptedResponse:
+ return ScriptedResponse(json=rows)
class TestBaseUrl:
@@ -102,167 +57,125 @@ class TestBaseUrl:
class TestPagination:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_paginates_until_short_page(self, MockSession) -> None:
- session = MockSession.return_value
+ def test_paginates_until_short_page(self) -> None:
first_page = [{"id": i} for i in range(PAGE_SIZE - 1)] + [{"id": PAGE_SIZE, "cursor": "CURSOR1"}]
second_page = [{"id": 9001}] # short page -> terminal
- params = _wire(session, [_response(first_page), _response(second_page)])
-
- manager = _make_manager()
- rows = _rows(_source(manager))
+ result = _driver().run("contacts", [_page(first_page), _page(second_page)])
- assert len(rows) == PAGE_SIZE + 1
+ assert result.raised is None
+ assert len(result.rows) == PAGE_SIZE + 1
# First request has no cursor; the second carries the cursor from the last item of page one.
- assert "cursor" not in params[0]
- assert params[0]["page_size"] == PAGE_SIZE
- assert params[1]["cursor"] == "CURSOR1"
+ assert result.params("cursor") == [None, "CURSOR1"]
+ assert result.params("page_size") == [str(PAGE_SIZE), str(PAGE_SIZE)]
# The cursor is navigation metadata and must never leak into the warehouse rows.
- assert all("cursor" not in row for row in rows)
+ assert all("cursor" not in row for row in result.rows)
# Checkpoint saved after the first page (points at the next page); the short page ends it.
- manager.save_state.assert_called_once()
- assert manager.save_state.call_args.args[0] == AgileCRMResumeConfig(cursor="CURSOR1")
+ assert result.saved_states == [AgileCRMResumeConfig(cursor="CURSOR1")]
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_stops_when_full_page_has_no_cursor(self, MockSession) -> None:
+ def test_stops_when_full_page_has_no_cursor(self) -> None:
# A full page whose last item carries no cursor must terminate rather than loop forever.
- session = MockSession.return_value
full_page_no_cursor = [{"id": i} for i in range(PAGE_SIZE)]
- _wire(session, [_response(full_page_no_cursor), _response([{"id": 1}])])
+ result = _driver().run("contacts", [_page(full_page_no_cursor)])
- manager = _make_manager()
- rows = _rows(_source(manager))
+ assert result.raised is None
+ assert len(result.rows) == PAGE_SIZE
+ assert len(result.requests) == 1
+ assert result.saved_states == []
- assert len(rows) == PAGE_SIZE
- assert session.send.call_count == 1
- manager.save_state.assert_not_called()
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_stops_on_short_page_even_with_cursor(self, MockSession) -> None:
+ def test_stops_on_short_page_even_with_cursor(self) -> None:
# A short page is terminal even if its last item still carries a cursor.
- session = MockSession.return_value
short_page = [{"id": 1}, {"id": 2, "cursor": "DANGLING"}]
- _wire(session, [_response(short_page), _response([{"id": 3}])])
-
- manager = _make_manager()
- rows = _rows(_source(manager))
-
- assert [r["id"] for r in rows] == [1, 2]
- assert session.send.call_count == 1
- assert all("cursor" not in row for row in rows)
- manager.save_state.assert_not_called()
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_resume_uses_saved_cursor(self, MockSession) -> None:
- session = MockSession.return_value
- params = _wire(session, [_response([{"id": 1}])])
+ result = _driver().run("contacts", [_page(short_page)])
- manager = _make_manager(AgileCRMResumeConfig(cursor="SAVED"))
- rows = _rows(_source(manager))
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == [1, 2]
+ assert len(result.requests) == 1
+ assert all("cursor" not in row for row in result.rows)
+ assert result.saved_states == []
- assert rows == [{"id": 1}]
- assert params[0]["cursor"] == "SAVED"
+ def test_resume_uses_saved_cursor(self) -> None:
+ result = _driver().run("contacts", [_page([{"id": 1}])], resume_state=AgileCRMResumeConfig(cursor="SAVED"))
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_non_list_body_raises_loudly(self, MockSession) -> None:
- session = MockSession.return_value
- _wire(session, [_response({"error": "something went wrong"})])
+ assert result.raised is None
+ assert result.rows == [{"id": 1}]
+ assert result.params("cursor") == ["SAVED"]
+ def test_non_list_body_raises_loudly(self) -> None:
# A 200 object body means the response shape changed — fail loud, not silently mis-sync.
- with pytest.raises(ValueError, match="Required a list response body"):
- _rows(_source(_make_manager()))
-
-
-def _mock_get_session(responses: list[Response]) -> tuple[mock.MagicMock, list[tuple[str, dict[str, Any]]]]:
- """A mock session whose `.get(url, params=...)` returns the queued responses in order.
-
- Returns the session and a list of (url, params) captured per call.
- """
- session = mock.MagicMock()
- calls: list[tuple[str, dict[str, Any]]] = []
+ result = _driver().run("contacts", [_page({"error": "something went wrong"})])
- def _get(url: str, params: Any = None) -> Response:
- calls.append((url, dict(params) if params else {}))
- return responses[len(calls) - 1]
-
- session.get.side_effect = _get
- return session, calls
+ assert isinstance(result.raised, ValueError)
+ assert "Required a list response body" in str(result.raised)
class TestTickets:
- @mock.patch(AGILECRM_SESSION_PATCH)
- def test_lists_via_all_tickets_filter(self, mock_make_session) -> None:
+ def test_lists_via_all_tickets_filter(self) -> None:
# The default filter list has "All Tickets" second — listing must resolve it, not grab the first.
filters = [
{"id": 1, "name": "New Tickets", "is_default_filter": True},
{"id": 2, "name": "All Tickets", "is_default_filter": True},
]
tickets_page = [{"id": 100, "subject": "x", "cursor": "C"}] # short page -> terminal
- session, calls = _mock_get_session([_response(filters), _response(tickets_page)])
- mock_make_session.return_value = session
-
- rows = _rows(_source(_make_manager(), endpoint="tickets"))
+ result = _driver().run("tickets", [_page(filters), _page(tickets_page)])
- assert [r["id"] for r in rows] == [100]
- assert all("cursor" not in r for r in rows)
- assert calls[1][0].endswith("/tickets/filter")
- assert calls[1][1]["filter_id"] == "2"
- assert calls[1][1]["global_sort_key"] == "-last_updated_time"
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == [100]
+ assert all("cursor" not in row for row in result.rows)
+ assert result.paths[1] == "/dev/api/tickets/filter"
+ assert result.requests[1].param("filter_id") == "2"
+ assert result.requests[1].param("global_sort_key") == "-last_updated_time"
- @mock.patch(AGILECRM_SESSION_PATCH)
- def test_no_filters_yields_nothing(self, mock_make_session) -> None:
+ def test_no_filters_yields_nothing(self) -> None:
# Without a saved filter there is no way to list tickets, so the table stays empty.
- session, calls = _mock_get_session([_response([])])
- mock_make_session.return_value = session
+ result = _driver().run("tickets", [_page([])])
- assert _rows(_source(_make_manager(), endpoint="tickets")) == []
- assert len(calls) == 1
+ assert result.raised is None
+ assert result.rows == []
+ assert len(result.requests) == 1
class TestFanout:
- @mock.patch(AGILECRM_SESSION_PATCH)
- def test_contact_notes_inject_parent_id(self, mock_make_session) -> None:
+ def test_contact_notes_inject_parent_id(self) -> None:
contacts_page = [{"id": 1}, {"id": 2}] # short page -> terminal
notes_1 = [{"id": 10, "subject": "a"}]
notes_2 = [{"id": 11, "subject": "b", "cursor": "X"}]
- session, calls = _mock_get_session([_response(contacts_page), _response(notes_1), _response(notes_2)])
- mock_make_session.return_value = session
-
- rows = _rows(_source(_make_manager(), endpoint="contact_notes"))
+ result = _driver().run("contact_notes", [_page(contacts_page), _page(notes_1), _page(notes_2)])
# Each note carries the id of the contact it was fetched for (part of the composite key), and
# the navigation cursor never leaks into a row.
- assert rows == [
+ assert result.raised is None
+ assert result.rows == [
{"id": 10, "subject": "a", "contact_id": 1},
{"id": 11, "subject": "b", "contact_id": 2},
]
- assert calls[1][0].endswith("/contacts/1/notes")
- assert calls[2][0].endswith("/contacts/2/notes")
+ assert result.paths[1:] == ["/dev/api/contacts/1/notes", "/dev/api/contacts/2/notes"]
- @mock.patch(AGILECRM_SESSION_PATCH)
- def test_ticket_notes_fan_out_over_tickets(self, mock_make_session) -> None:
+ def test_ticket_notes_fan_out_over_tickets(self) -> None:
# Parent enumeration for ticket messages goes through the ticket filter, then per-ticket notes.
filters = [{"id": 2, "name": "All Tickets", "is_default_filter": True}]
tickets_page = [{"id": 5}] # short page -> terminal
messages = [{"id": 50, "ticket_id": 5, "plain_text": "hi"}]
- session, calls = _mock_get_session([_response(filters), _response(tickets_page), _response(messages)])
- mock_make_session.return_value = session
+ result = _driver().run("ticket_notes", [_page(filters), _page(tickets_page), _page(messages)])
- rows = _rows(_source(_make_manager(), endpoint="ticket_notes"))
-
- assert rows == [{"id": 50, "ticket_id": 5, "plain_text": "hi"}]
- assert calls[2][0].endswith("/tickets/notes/5")
+ assert result.raised is None
+ assert result.rows == [{"id": 50, "ticket_id": 5, "plain_text": "hi"}]
+ assert result.paths[2] == "/dev/api/tickets/notes/5"
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:
- with mock.patch(AGILECRM_SESSION_PATCH) as mock_session:
- mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)
+ with scripted_network([ScriptedResponse(status=status_code)]) as network:
assert validate_credentials("acme", "[email protected]", "key") is expected
+ assert len(network.requests_log) == 1
+ assert network.requests_log[0].path == "/dev/api/contacts"
+ assert network.requests_log[0].param("page_size") == "1"
+
def test_invalid_domain_short_circuits_to_false(self) -> None:
# An invalid domain must fail before any request is attempted.
- with mock.patch(AGILECRM_SESSION_PATCH) as mock_session:
+ with scripted_network([]) as network:
assert validate_credentials("evil.com#", "[email protected]", "key") is False
- mock_session.assert_not_called()
+
+ assert network.requests_log == []
+ assert network.session_options == []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm_source.py
index 26f7137f97ff..6b17367571bc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm_source.py
@@ -1,11 +1,13 @@
from typing import Any
-from unittest.mock import MagicMock
-
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm import source as agilecrm_source_module
from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.source import AgileCRMSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.agilecrm import (
AgileCRMSourceConfig,
)
@@ -59,8 +61,9 @@ class TestPipelinePlumbing:
]
)
def test_source_for_pipeline_routes_endpoint(self, _name: str, endpoint: str, expected_keys: list[str]) -> None:
- inputs = MagicMock()
- inputs.schema_name = endpoint
- response = AgileCRMSource().source_for_pipeline(_config(), MagicMock(), inputs)
- assert response.name == endpoint
- assert response.primary_keys == expected_keys
+ result = SourceDriver(AgileCRMSource(), _config()).run(endpoint, [ScriptedResponse(json=[])])
+
+ assert result.raised is None
+ assert result.response is not None
+ assert result.response.name == endpoint
+ assert result.response.primary_keys == expected_keys
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aha/tests/test_aha.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/tests/test_aha.py
index 54825e72854b..fde14b1a0edc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aha/tests/test_aha.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aha/tests/test_aha.py
@@ -1,32 +1,26 @@
-import json
from datetime import UTC, date, datetime
-from typing import Any, cast
+from typing import Any
import pytest
-from unittest import mock
from parameterized import parameterized
-from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.aha.aha import (
AhaResumeConfig,
_build_initial_params,
_format_updated_since,
_incremental_window,
- aha_source,
normalize_subdomain,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.aha.settings import AHA_ENDPOINTS, PER_PAGE
-
-FANOUT_REST_RESOURCES_PATCH = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"
+from products.warehouse_sources.backend.temporal.data_imports.sources.aha.source import AhaSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
)
-
-# RESTClient builds its session via make_tracked_session in the rest_client module.
-CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
-# validate_credentials builds its own tracked session in the aha module.
-AHA_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.aha.aha.make_tracked_session"
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.aha import AhaSourceConfig
class TestNormalizeSubdomain:
@@ -90,110 +84,56 @@ def _response(
*,
current_page: int | None = None,
total_pages: int | None = None,
- drop_key: bool = False,
-) -> Response:
- body: dict[str, Any] = {}
- if not drop_key:
- body[response_key] = items or []
+) -> ScriptedResponse:
+ body: dict[str, Any] = {response_key: items or []}
if total_pages is not None:
body["pagination"] = {"current_page": current_page or 1, "total_pages": total_pages}
- resp = Response()
- resp.status_code = 200
- resp._content = json.dumps(body).encode()
- return resp
-
-
-def _make_manager(resume_state: AhaResumeConfig | None = None) -> mock.MagicMock:
- manager = mock.MagicMock()
- manager.can_resume.return_value = resume_state is not None
- manager.load_state.return_value = resume_state
- return manager
-
-
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
- """Wire a mock session and return a list that captures each request AT SEND TIME.
-
- ``request.params`` is a single dict mutated in place across pages, so inspecting it after the
- run shows only the final state — snapshot a copy when each request is prepared instead.
- """
- session.headers = {}
- snapshots: list[dict[str, Any]] = []
-
- def _prepare(request: Any) -> mock.MagicMock:
- snapshots.append({"url": request.url, "params": dict(request.params or {}), "auth": request.auth})
- return mock.MagicMock()
-
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = responses
- return snapshots
-
-
-def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):
- return aha_source(
- subdomain="acme",
- api_key="key",
- endpoint=endpoint,
- team_id=1,
- job_id="j",
- resumable_source_manager=manager,
- **kwargs,
- )
+ return ScriptedResponse(json=body)
-def _rows(source_response) -> list[dict[str, Any]]:
- return [row for page in source_response.items() for row in page]
+def _driver() -> SourceDriver:
+ return SourceDriver(AhaSource(), AhaSourceConfig(subdomain="acme", api_key="key"))
class TestAhaSource:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_resumes_from_saved_page(self, MockSession) -> None:
- session = MockSession.return_value
- snapshots = _wire(session, [_response("features", [{"id": "2"}], current_page=2, total_pages=2)])
-
- rows = _rows(_source("features", _make_manager(AhaResumeConfig(next_page=2))))
-
- assert [r["id"] for r in rows] == ["2"]
- assert session.send.call_count == 1
- assert snapshots[0]["params"]["page"] == 2
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_incremental_cursor_added_to_request(self, MockSession) -> None:
- session = MockSession.return_value
- snapshots = _wire(session, [_response("features", [{"id": "1"}], total_pages=1)])
-
- _rows(
- _source(
- "features",
- _make_manager(),
- should_use_incremental_field=True,
- db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
- )
+ def test_resumes_from_saved_page(self) -> None:
+ result = _driver().run(
+ "features",
+ [_response("features", [{"id": "2"}], current_page=2, total_pages=2)],
+ resume_state=AhaResumeConfig(next_page=2),
)
- assert snapshots[0]["params"]["updated_since"] == "2026-03-04T02:58:14Z"
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == ["2"]
+ assert result.params("page") == ["2"]
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_uses_response_key_for_todos(self, MockSession) -> None:
- # to-dos live at /tasks with a `tasks` root key.
- session = MockSession.return_value
- snapshots = _wire(session, [_response("tasks", [{"id": "t1"}], total_pages=1)])
+ def test_incremental_cursor_added_to_request(self) -> None:
+ result = _driver().run(
+ "features",
+ [_response("features", [{"id": "1"}], total_pages=1)],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ )
+
+ assert result.raised is None
+ assert result.params("updated_since") == ["2026-03-04T02:58:14Z"]
- rows = _rows(_source("todos", _make_manager()))
+ def test_uses_response_key_for_todos(self) -> None:
+ # to-dos live at /tasks with a `tasks` root key.
+ result = _driver().run("todos", [_response("tasks", [{"id": "t1"}], total_pages=1)])
- assert [r["id"] for r in rows] == ["t1"]
- assert snapshots[0]["url"] == "https://acme.aha.io/api/v1/tasks"
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == ["t1"]
+ assert result.paths == ["/api/v1/tasks"]
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_missing_metadata_full_page_continues(self, MockSession) -> None:
+ def test_missing_metadata_full_page_continues(self) -> None:
# No pagination metadata + a full page -> there may be more pages.
- session = MockSession.return_value
full_page = [{"id": str(i)} for i in range(PER_PAGE)]
- _wire(session, [_response("features", full_page), _response("features", [{"id": "last"}])])
-
- rows = _rows(_source("features", _make_manager()))
+ result = _driver().run("features", [_response("features", full_page), _response("features", [{"id": "last"}])])
- assert len(rows) == PER_PAGE + 1
- assert session.send.call_count == 2
+ assert result.raised is None
+ assert len(result.rows) == PER_PAGE + 1
+ assert result.params("page") == ["1", "2"]
class TestIncrementalWindow:
@@ -207,43 +147,32 @@ class TestIncrementalWindow:
assert convert(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)) == "2026-03-04T02:58:14Z"
-class _FakeDltResource:
- """Stand-in for a DltResource returned by ``rest_api_resources``."""
-
- def __init__(self, name: str, rows: list[dict[str, Any]]) -> None:
- self.name = name
- self._rows = rows
-
- def add_map(self, mapper: Any) -> "_FakeDltResource":
- self._rows = [mapper(dict(row)) for row in self._rows]
- return self
+class TestAhaFanout:
+ def test_releases_injects_product_id_from_parent(self) -> None:
+ result = _driver().run(
+ "releases",
+ [
+ _response("products", [{"id": "1000"}]),
+ _response("releases", [{"id": "R1"}]),
+ ],
+ )
- def __iter__(self) -> Any:
- return iter(self._rows)
+ assert result.raised is None
+ assert result.paths == ["/api/v1/products", "/api/v1/products/1000/releases"]
+ assert result.rows == [{"id": "R1", "product_id": "1000"}]
-class TestAhaFanout:
- @mock.patch(FANOUT_REST_RESOURCES_PATCH)
- def test_releases_injects_product_id_from_parent(self, mock_rest_api_resources) -> None:
- mock_rest_api_resources.return_value = [
- _FakeDltResource("products", [{"id": "1000"}]),
- _FakeDltResource("releases", [{"id": "R1", "_products_id": "1000"}]),
- ]
-
- resp = _source("releases", _make_manager())
+class TestValidateCredentials:
+ def test_ok(self) -> None:
+ with scripted_network([ScriptedResponse(status=200)]) as network:
+ assert validate_credentials("acme", "key") == (True, 200)
- rows = list(cast(Any, resp.items()))
- assert rows == [{"id": "R1", "product_id": "1000"}]
+ assert [request.path for request in network.requests_log] == ["/api/v1/me"]
+ def test_bad_subdomain_raises_before_probe(self) -> None:
+ with scripted_network([]) as network:
+ with pytest.raises(ValueError, match="Invalid Aha! account domain"):
+ validate_credentials("acme/../evil", "key")
-class TestValidateCredentials:
- @mock.patch(AHA_SESSION_PATCH)
- def test_ok(self, mock_session) -> None:
- mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
- assert validate_credentials("acme", "key") == (True, 200)
-
- @mock.patch(AHA_SESSION_PATCH)
- def test_bad_subdomain_raises_before_probe(self, mock_session) -> None:
- with pytest.raises(ValueError, match="Invalid Aha! account domain"):
- validate_credentials("acme/../evil", "key")
- mock_session.assert_not_called()
+ assert network.requests_log == []
+ assert network.session_options == []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aha_ideas/tests/test_aha_ideas.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aha_ideas/tests/test_aha_ideas.py
index c17e3c720e98..e987b333fc7d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aha_ideas/tests/test_aha_ideas.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aha_ideas/tests/test_aha_ideas.py
@@ -1,18 +1,14 @@
-import json
from datetime import UTC, date, datetime
-from typing import Any, cast
+from typing import Any
import pytest
-from unittest import mock
from parameterized import parameterized
-from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.aha_ideas.aha_ideas import (
AhaIdeasResumeConfig,
_build_initial_params,
_format_updated_since,
- aha_ideas_source,
normalize_subdomain,
validate_credentials,
)
@@ -20,26 +16,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.aha_ideas.
AHA_IDEAS_ENDPOINTS,
PER_PAGE,
)
-
-# RESTClient builds its session via make_tracked_session in the rest_client module.
-CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
-# validate_credentials builds its own tracked session in the aha_ideas module.
-AHA_IDEAS_SESSION_PATCH = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.aha_ideas.aha_ideas.make_tracked_session"
+from products.warehouse_sources.backend.temporal.data_imports.sources.aha_ideas.source import AhaIdeasSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.ahaideas import (
+ AhaIdeasSourceConfig,
)
-class _FakeDltResource:
- def __init__(self, name: str, rows: list[dict]) -> None:
- self.name = name
- self._rows = rows
-
- def add_map(self, mapper):
- self._rows = [mapper(dict(row)) for row in self._rows]
- return self
-
- def __iter__(self):
- return iter(self._rows)
+def _driver() -> SourceDriver:
+ return SourceDriver(AhaIdeasSource(), AhaIdeasSourceConfig(subdomain="acme", api_key="key"))
class TestNormalizeSubdomain:
@@ -104,145 +93,86 @@ def _response(
current_page: int | None = None,
total_pages: int | None = None,
drop_key: bool = False,
-) -> Response:
+) -> ScriptedResponse:
body: dict[str, Any] = {}
if not drop_key:
body[response_key] = items or []
if total_pages is not None:
body["pagination"] = {"current_page": current_page or 1, "total_pages": total_pages}
- resp = Response()
- resp.status_code = 200
- resp._content = json.dumps(body).encode()
- return resp
-
-
-def _make_manager(resume_state: AhaIdeasResumeConfig | None = None) -> mock.MagicMock:
- manager = mock.MagicMock()
- manager.can_resume.return_value = resume_state is not None
- manager.load_state.return_value = resume_state
- return manager
-
-
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
- """Wire a mock session and return a list that captures each request AT SEND TIME.
-
- ``request.params`` is a single dict mutated in place across pages, so inspecting it after the
- run shows only the final state — snapshot a copy when each request is prepared instead.
- """
- session.headers = {}
- snapshots: list[dict[str, Any]] = []
-
- def _prepare(request: Any) -> mock.MagicMock:
- snapshots.append({"url": request.url, "params": dict(request.params or {}), "auth": request.auth})
- return mock.MagicMock()
-
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = responses
- return snapshots
-
-
-def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):
- return aha_ideas_source(
- subdomain="acme",
- api_key="key",
- endpoint=endpoint,
- team_id=1,
- job_id="j",
- resumable_source_manager=manager,
- **kwargs,
- )
+ return ScriptedResponse(json=body)
-def _rows(source_response) -> list[dict[str, Any]]:
- return [row for page in source_response.items() for row in page]
+class TestAhaIdeasSourceNonFanout:
+ def test_resumes_from_saved_page(self) -> None:
+ result = _driver().run(
+ "ideas",
+ [_response("ideas", [{"id": "2"}], current_page=2, total_pages=2)],
+ resume_state=AhaIdeasResumeConfig(next_page=2),
+ )
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == ["2"]
+ assert result.params("page") == ["2"]
-class TestAhaIdeasSourceNonFanout:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_resumes_from_saved_page(self, MockSession) -> None:
- session = MockSession.return_value
- snapshots = _wire(session, [_response("ideas", [{"id": "2"}], current_page=2, total_pages=2)])
-
- rows = _rows(_source("ideas", _make_manager(AhaIdeasResumeConfig(next_page=2))))
-
- assert [r["id"] for r in rows] == ["2"]
- assert session.send.call_count == 1
- assert snapshots[0]["params"]["page"] == 2
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_incremental_cursor_added_to_request(self, MockSession) -> None:
- session = MockSession.return_value
- snapshots = _wire(session, [_response("ideas", [{"id": "1"}], total_pages=1)])
-
- _rows(
- _source(
- "ideas",
- _make_manager(),
- should_use_incremental_field=True,
- db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
- )
+ def test_incremental_cursor_added_to_request(self) -> None:
+ result = _driver().run(
+ "ideas",
+ [_response("ideas", [{"id": "1"}], total_pages=1)],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
)
- assert snapshots[0]["params"]["updated_since"] == "2026-03-04T02:58:14Z"
+ assert result.raised is None
+ assert result.params("updated_since") == ["2026-03-04T02:58:14Z"]
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_uses_response_key_for_idea_endorsements(self, MockSession) -> None:
+ def test_uses_response_key_for_idea_endorsements(self) -> None:
# Votes live at /ideas/endorsements with an `idea_endorsements` root key.
- session = MockSession.return_value
- snapshots = _wire(session, [_response("idea_endorsements", [{"id": "v1"}], total_pages=1)])
+ result = _driver().run("idea_endorsements", [_response("idea_endorsements", [{"id": "v1"}], total_pages=1)])
- rows = _rows(_source("idea_endorsements", _make_manager()))
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == ["v1"]
+ assert result.urls[0].split("?", 1)[0] == "https://acme.aha.io/api/v1/ideas/endorsements"
- assert [r["id"] for r in rows] == ["v1"]
- assert snapshots[0]["url"] == "https://acme.aha.io/api/v1/ideas/endorsements"
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_missing_metadata_full_page_continues(self, MockSession) -> None:
+ def test_missing_metadata_full_page_continues(self) -> None:
# No pagination metadata + a full page -> there may be more pages.
- session = MockSession.return_value
full_page = [{"id": str(i)} for i in range(PER_PAGE)]
- _wire(session, [_response("ideas", full_page), _response("ideas", [{"id": "last"}])])
-
- rows = _rows(_source("ideas", _make_manager()))
+ result = _driver().run("ideas", [_response("ideas", full_page), _response("ideas", [{"id": "last"}])])
- assert len(rows) == PER_PAGE + 1
- assert session.send.call_count == 2
+ assert result.raised is None
+ assert len(result.rows) == PER_PAGE + 1
+ assert len(result.requests) == 2
class TestAhaIdeasSourceFanout:
- @mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"
- )
- def test_idea_comments_fanout_row_format(self, mock_rest_api_resources) -> None:
- mock_rest_api_resources.return_value = [
- _FakeDltResource("ideas", [{"id": "idea_1"}]),
- _FakeDltResource("idea_comments", [{"id": "comment_1", "idea_id": "idea_1"}]),
- ]
-
- response = aha_ideas_source(
- subdomain="acme",
- api_key="key",
- endpoint="idea_comments",
- team_id=1,
- job_id="j",
- resumable_source_manager=_make_manager(),
+ def test_idea_comments_fanout_row_format(self) -> None:
+ result = _driver().run(
+ "idea_comments",
+ [
+ _response("ideas", [{"id": "idea_1"}], total_pages=1),
+ _response("idea_comments", [{"id": "comment_1", "idea_id": "idea_1"}], total_pages=1),
+ ],
)
- rows = list(cast(Any, response.items()))
- assert rows == [{"id": "comment_1", "idea_id": "idea_1"}]
- assert response.primary_keys == ["id", "idea_id"]
- assert response.partition_mode == "datetime"
- assert response.partition_keys == ["created_at"]
+ assert result.raised is None
+ assert result.rows == [{"id": "comment_1", "idea_id": "idea_1"}]
+ assert result.paths == ["/api/v1/ideas", "/api/v1/ideas/idea_1/idea_comments"]
+ assert result.response is not None
+ assert result.response.primary_keys == ["id", "idea_id"]
+ assert result.response.partition_mode == "datetime"
+ assert result.response.partition_keys == ["created_at"]
class TestValidateCredentials:
- @mock.patch(AHA_IDEAS_SESSION_PATCH)
- def test_ok(self, mock_session) -> None:
- mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
- assert validate_credentials("acme", "key") == (True, 200)
-
- @mock.patch(AHA_IDEAS_SESSION_PATCH)
- def test_bad_subdomain_raises_before_probe(self, mock_session) -> None:
- with pytest.raises(ValueError, match="Invalid Aha! account domain"):
- validate_credentials("acme/../evil", "key")
- mock_session.assert_not_called()
+ def test_ok(self) -> None:
+ with scripted_network([ScriptedResponse(status=200)]) as network:
+ assert validate_credentials("acme", "key") == (True, 200)
+
+ assert [request.path for request in network.requests_log] == ["/api/v1/me"]
+
+ def test_bad_subdomain_raises_before_probe(self) -> None:
+ with scripted_network([]) as network:
+ with pytest.raises(ValueError, match="Invalid Aha! account domain"):
+ validate_credentials("acme/../evil", "key")
+
+ assert network.requests_log == []
+ assert network.session_options == []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aha_ideas/tests/test_aha_ideas_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aha_ideas/tests/test_aha_ideas_source.py
index 3284bf7ad235..8ce500ab0661 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aha_ideas/tests/test_aha_ideas_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aha_ideas/tests/test_aha_ideas_source.py
@@ -1,50 +1,52 @@
import pytest
-from unittest import mock
from products.warehouse_sources.backend.temporal.data_imports.sources.aha_ideas.source import AhaIdeasSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ scripted_network,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.ahaideas import (
AhaIdeasSourceConfig,
)
class TestAhaIdeasSource:
- def setup_method(self):
+ def setup_method(self) -> None:
self.source = AhaIdeasSource()
self.team_id = 123
self.config = AhaIdeasSourceConfig(subdomain="acme", api_key="key")
- def test_subdomain_listed_as_connection_host_field(self):
+ def test_subdomain_listed_as_connection_host_field(self) -> None:
# The API key is sent to <subdomain>.aha.io, so retargeting the subdomain must re-require it.
assert self.source.connection_host_fields == ["subdomain"]
@pytest.mark.parametrize(
- "mock_return, expected_valid, expected_message",
+ "status_code, expected_valid, expected_message",
[
- ((True, 200), True, None),
- ((False, 401), False, "Invalid Aha! API key"),
- ((False, 403), False, "Could not connect to Aha! with the provided account domain and API key"),
- ((False, None), False, "Could not connect to Aha! with the provided account domain and API key"),
+ (200, True, None),
+ (401, False, "Invalid Aha! API key"),
+ (403, False, "Could not connect to Aha! with the provided account domain and API key"),
+ (None, False, "Could not connect to Aha! with the provided account domain and API key"),
],
)
- @mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.aha_ideas.source.validate_aha_ideas_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)
+ def test_validate_credentials(
+ self, status_code: int | None, expected_valid: bool, expected_message: str | None
+ ) -> None:
+ script = [ConnectionResetError("reset")] if status_code is None else [ScriptedResponse(status=status_code)]
+ with scripted_network(script) as network:
+ 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("acme", "key")
-
- @mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.aha_ideas.source.validate_aha_ideas_credentials"
- )
- def test_validate_credentials_surfaces_bad_subdomain(self, mock_validate):
- mock_validate.side_effect = ValueError("Invalid Aha! account domain: 'a/b'.")
+ assert network.requests_log
+ assert all(request.path == "/api/v1/me" for request in network.requests_log)
+ assert all(request.headers["authorization"] == "Bearer key" for request in network.requests_log)
- is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+ def test_validate_credentials_surfaces_bad_subdomain(self) -> None:
+ self.config = AhaIdeasSourceConfig(subdomain="a/b", api_key="key")
+ with scripted_network([]) as network:
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
assert is_valid is False
assert "Invalid Aha! account domain" in (error_message or "")
+ assert network.requests_log == []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs.py
index 5c7c7e8222aa..f4c54cc13b06 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs.py
@@ -9,15 +9,18 @@ from unittest.mock import MagicMock, patch
from requests import Response, Session
from requests.exceptions import HTTPError
-from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.ahrefs import (
- ahrefs_source,
- validate_credentials,
-)
+from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.ahrefs import validate_credentials
from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.source import AhrefsSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
RESTClientRetryableError,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import UnknownResourceError
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.ahrefs import AhrefsSourceConfig
@@ -105,15 +108,16 @@ def test_snapshot_request_and_terminal_page(
@pytest.mark.parametrize("count", [99, 100, 101])
-def test_page_sample_cap(send: MagicMock, count: int) -> None:
+def test_page_sample_cap(count: int) -> None:
rows = [{"url": f"https://example.com/{i}"} for i in range(count)]
- send.return_value = response({"pages": rows})
with patch(f"{SOURCE_MODULE}.logger") as logger:
- result = ahrefs_source("test-key", "123", "site_audit_pages", 1, "test-job")
- actual = [row for page in cast(Iterable[Any], result.items()) for row in page]
- assert actual == [{**row, "project_id": "123"} for row in rows[:100]]
+ result = SourceDriver(AhrefsSource(), AhrefsSourceConfig(api_key="test-key", project_id="123")).run(
+ "site_audit_pages", [ScriptedResponse(json={"pages": rows})]
+ )
+ assert result.raised is None
+ assert result.rows == [{**row, "project_id": "123"} for row in rows[:100]]
assert logger.info.call_count == int(count >= 100)
- send.assert_called_once()
+ assert len(result.requests) == 1
@pytest.mark.parametrize(
@@ -127,19 +131,22 @@ def test_page_sample_cap(send: MagicMock, count: int) -> None:
(402, {"error": "Payment required"}, "API units are exhausted"),
],
)
-def test_credential_and_sync_error_mapping(send: MagicMock, status: int, body: object, message: str) -> None:
- send.return_value = response(body, status)
- valid, error = validate_credentials("test-key")
+def test_credential_and_sync_error_mapping(status: int, body: object, message: str) -> None:
+ answer = ScriptedResponse(status=status, json=body)
+ with scripted_network([answer]) as network:
+ valid, error = validate_credentials("test-key")
assert valid is False
assert error is not None and message in error
- send.assert_called_once()
- send.reset_mock()
-
- with pytest.raises(ValueError) as raised:
- list(cast(Iterable[Any], ahrefs_source("test-key", "123", "site_audit_issues", 1, "test-job").items()))
- mapped = AhrefsSource().get_non_retryable_errors()[str(raised.value)]
+ assert len(network.requests_log) == 1
+
+ source = AhrefsSource()
+ result = SourceDriver(source, AhrefsSourceConfig(api_key="test-key", project_id="123")).run(
+ "site_audit_issues", [answer]
+ )
+ assert isinstance(result.raised, ValueError)
+ mapped = source.get_non_retryable_errors()[str(result.raised)]
assert mapped is not None and message in mapped
- send.assert_called_once()
+ assert len(result.requests) == 1
def test_free_credential_probe(send: MagicMock) -> None:
@@ -153,30 +160,39 @@ def test_free_credential_probe(send: MagicMock) -> None:
@pytest.mark.parametrize("status", [429, 500, 503])
-def test_transient_probe_failure_is_not_invalid_credentials(send: MagicMock, status: int) -> None:
- send.return_value = response({"error": "Try later"}, status)
- with pytest.raises(RESTClientRetryableError):
- validate_credentials("test-key")
- send.assert_called_once()
-
-
-def test_unrecognized_probe_error_propagates(send: MagicMock) -> None:
- send.return_value = response({"error": "Invalid request"}, 400)
- with pytest.raises(HTTPError):
- validate_credentials("test-key")
+def test_transient_probe_failure_is_not_invalid_credentials(status: int) -> None:
+ with scripted_network(always(ScriptedResponse(status=status, json={"error": "Try later"}))) as network:
+ with pytest.raises(RESTClientRetryableError):
+ validate_credentials("test-key")
+ assert network.requests_log
+ assert all(request.path == "/v3/subscription-info/limits-and-usage" for request in network.requests_log)
[email protected]("probe", [False, True])
-def test_missing_response_envelope_fails(send: MagicMock, probe: bool) -> None:
- send.return_value = response({"unexpected": []})
- with pytest.raises(ValueError, match="matched nothing"):
- if probe:
+def test_unrecognized_probe_error_propagates() -> None:
+ with scripted_network([ScriptedResponse(status=400, json={"error": "Invalid request"})]) as network:
+ with pytest.raises(HTTPError):
validate_credentials("test-key")
- else:
- list(cast(Iterable[Any], ahrefs_source("test-key", "123", "site_audit_issues", 1, "test-job").items()))
+ assert len(network.requests_log) == 1
-def test_unknown_table_fails_before_request(send: MagicMock) -> None:
- with pytest.raises(UnknownResourceError):
- ahrefs_source("test-key", "123", "unknown", 1, "test-job")
- send.assert_not_called()
[email protected]("probe", [False, True])
+def test_missing_response_envelope_fails(probe: bool) -> None:
+ answer = ScriptedResponse(json={"unexpected": []})
+ if probe:
+ with scripted_network([answer]) as network:
+ with pytest.raises(ValueError, match="matched nothing"):
+ validate_credentials("test-key")
+ assert len(network.requests_log) == 1
+ else:
+ result = SourceDriver(AhrefsSource(), AhrefsSourceConfig(api_key="test-key", project_id="123")).run(
+ "site_audit_issues", [answer]
+ )
+ assert isinstance(result.raised, ValueError)
+ assert "matched nothing" in str(result.raised)
+ assert len(result.requests) == 1
+
+
+def test_unknown_table_fails_before_request() -> None:
+ result = SourceDriver(AhrefsSource(), AhrefsSourceConfig(api_key="test-key", project_id="123")).run("unknown", [])
+ assert isinstance(result.raised, UnknownResourceError)
+ assert result.requests == []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs_source.py
index e81e60712027..c818479f40ee 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs_source.py
@@ -1,33 +1,33 @@
import pytest
-from unittest.mock import patch
from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.source import AhrefsSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ scripted_network,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.ahrefs import AhrefsSourceConfig
@pytest.mark.parametrize("project_id", ["", "0", "-1", "1.5", "https://example.com/123", "123", " 123 "])
def test_invalid_project_id_prevents_probe(project_id: str) -> None:
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.source.validate_ahrefs_credentials"
- ) as validate:
+ with scripted_network([]) as network:
valid, message = AhrefsSource().validate_credentials(
AhrefsSourceConfig(api_key="test-key", project_id=project_id), 1
)
assert valid is False
assert message == "Enter a positive Site Audit project ID from your Ahrefs project URL."
- validate.assert_not_called()
+ assert network.requests_log == []
@pytest.mark.parametrize("project_id", ["123", "00123"])
def test_valid_project_id_reaches_probe(project_id: str) -> None:
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.source.validate_ahrefs_credentials",
- return_value=(True, None),
- ) as validate:
+ with scripted_network([ScriptedResponse(json={"limits_and_usage": {"subscription": "Lite"}})]) as network:
assert AhrefsSource().validate_credentials(
AhrefsSourceConfig(api_key="test-key", project_id=project_id), 1
) == (
True,
None,
)
- validate.assert_called_once_with("test-key")
+ assert len(network.requests_log) == 1
+ assert network.requests_log[0].path == "/v3/subscription-info/limits-and-usage"
+ assert network.requests_log[0].headers["authorization"] == "Bearer test-key"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/tests/test_airbrake.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/tests/test_airbrake.py
index 30677ba75c7b..d43e655eeae0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/tests/test_airbrake.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/tests/test_airbrake.py
@@ -1,76 +1,36 @@
from datetime import UTC, date, datetime
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.airbrake import airbrake
from products.warehouse_sources.backend.temporal.data_imports.sources.airbrake.airbrake import (
NOTICES_MAX_PAGES_PER_GROUP,
- PAGE_LIMIT,
AirbrakeResumeConfig,
+ AirbrakeRetryableError,
_build_groups_params,
_format_start_time,
- airbrake_source,
- get_rows,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.airbrake.source import AirbrakeSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.airbrake import (
+ AirbrakeSourceConfig,
+)
-class _FakeResumableManager:
- def __init__(self, state: AirbrakeResumeConfig | None = None) -> None:
- self._state = state
- self.saved: list[AirbrakeResumeConfig] = []
-
- def can_resume(self) -> bool:
- return self._state is not None
-
- def load_state(self) -> AirbrakeResumeConfig | None:
- return self._state
-
- def save_state(self, data: AirbrakeResumeConfig) -> None:
- self.saved.append(data)
-
-
-def _response_with_status(status_code: int) -> requests.Response:
- response = requests.Response()
- response.status_code = status_code
- return response
-
-
-class _FakePages:
- """Fixture keyed by (path, page). Missing keys mean 'empty page' so pagination terminates."""
-
- def __init__(self, pages: dict[tuple[str, int], Any]) -> None:
- self.pages = pages
- self.requests: list[tuple[str, dict[str, Any]]] = []
-
- def __call__(self, session: Any, url: str, params: dict[str, Any], logger: Any) -> dict[str, Any]:
- path = url.removeprefix("https://api.airbrake.io")
- self.requests.append((path, params))
- result = self.pages.get((path, params["page"]), {})
- if isinstance(result, Exception):
- raise result
- return result
+def _driver() -> SourceDriver:
+ return SourceDriver(AirbrakeSource(), AirbrakeSourceConfig(api_key="user-key"))
-def _collect(
- manager: _FakeResumableManager, monkeypatch: Any, pages: _FakePages, endpoint: str, **kwargs: Any
-) -> list[dict]:
- monkeypatch.setattr(airbrake, "_fetch_page", pages)
- rows: list[dict] = []
- for batch in get_rows(
- api_key="user-key",
- endpoint=endpoint,
- logger=MagicMock(),
- resumable_source_manager=manager, # type: ignore[arg-type]
- **kwargs,
- ):
- rows.extend(batch)
- return rows
+def _page(collection: str, rows: list[dict[str, Any]], count: int | None = None) -> ScriptedResponse:
+ return ScriptedResponse(json={"count": len(rows) if count is None else count, collection: rows})
class TestFormatStartTime:
@@ -108,226 +68,225 @@ class TestBuildGroupsParams:
class TestIterPages:
def test_max_pages_cap_truncates_collection(self, monkeypatch: Any) -> None:
- pages = _FakePages({("/p", page): {"count": 999, "notices": [{"id": page}]} for page in range(1, 10)})
- monkeypatch.setattr(airbrake, "_fetch_page", pages)
- result = list(airbrake._iter_pages(MagicMock(), "user-key", "/p", "notices", MagicMock(), max_pages=3))
- assert [page for page, _items in result] == [1, 2, 3]
+ monkeypatch.setattr(airbrake, "NOTICES_MAX_PAGES_PER_GROUP", 3)
+ result = _driver().run(
+ "notices",
+ [
+ _page("projects", [{"id": 1}]),
+ _page("groups", [{"id": "g1"}]),
+ *[_page("notices", [{"id": page}], count=999) for page in range(1, 4)],
+ ],
+ )
+ assert result.raised is None
+ assert result.rows == [{"id": 1}, {"id": 2}, {"id": 3}]
+ assert [request.param("page") for request in result.requests if request.path.endswith("/notices")] == [
+ "1",
+ "2",
+ "3",
+ ]
class TestFetchPageRetries:
@parameterized.expand([("rate_limited", 429), ("server_error", 500)])
def test_retryable_statuses_are_retried(self, _name: str, status_code: int) -> None:
- bad = MagicMock()
- bad.status_code = status_code
- good = MagicMock()
- good.status_code = 200
- good.ok = True
- good.json.return_value = {"projects": []}
-
- session = MagicMock()
- session.get.side_effect = [bad, good]
-
- with pytest.MonkeyPatch.context() as mp:
- mp.setattr(airbrake._fetch_page.retry, "sleep", lambda *_: None) # type: ignore[attr-defined]
- result = airbrake._fetch_page(session, "https://api.airbrake.io/api/v4/projects", {}, MagicMock())
+ result = _driver().run("projects", [ScriptedResponse(status=status_code), _page("projects", [])])
+ assert result.raised is None
+ assert result.rows == []
+ assert result.paths == ["/api/v4/projects", "/api/v4/projects"]
- assert result == {"projects": []}
- assert session.get.call_count == 2
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500)])
+ def test_persistent_retryable_status_raises_a_retryable_error(self, _name: str, status_code: int) -> None:
+ # The adapter absorbs one failed try, so only a status that persists reaches the source's own check.
+ result = _driver().run("projects", always(ScriptedResponse(status=status_code)))
+ assert isinstance(result.raised, AirbrakeRetryableError)
def test_auth_error_raises_immediately_without_leaking_key(self) -> None:
# 401 must surface as HTTPError on the first attempt so get_non_retryable_errors can stop
# the sync — and its message must not carry the ?key= credential, since it is persisted
# into job errors and logs.
- response = MagicMock()
- response.status_code = 401
- response.ok = False
- response.reason = "Unauthorized"
- response.text = '{"code":401,"type":"Unauthorized"}'
- session = MagicMock()
- session.get.return_value = response
-
- with pytest.raises(requests.HTTPError) as exc_info:
- airbrake._fetch_page(
- session,
- "https://api.airbrake.io/api/v4/projects",
- {"key": "SECRET-KEY", "limit": PAGE_LIMIT, "page": 1},
- MagicMock(),
- )
-
- assert session.get.call_count == 1
- assert "401 Client Error: Unauthorized for url: https://api.airbrake.io/api/v4/projects" in str(exc_info.value)
- assert "SECRET-KEY" not in str(exc_info.value)
+ result = _driver().run("projects", [ScriptedResponse(status=401, json={"code": 401, "type": "Unauthorized"})])
+ assert len(result.requests) == 1
+ assert isinstance(result.raised, requests.HTTPError)
+ assert "401 Client Error: Unauthorized for url: https://api.airbrake.io/api/v4/projects" in str(result.raised)
+ assert "user-key" not in str(result.raised)
# `response` must ride along so fan-out callers can distinguish 404s.
- assert exc_info.value.response is response
+ assert result.raised.response is not None
+ assert result.raised.response.status_code == 401
class TestGroupsFanOut:
- def test_incremental_run_passes_start_time_to_every_project(self, monkeypatch: Any) -> None:
- pages = _FakePages(
- {
- ("/api/v4/projects", 1): {"count": 2, "projects": [{"id": 1}, {"id": 2}]},
- ("/api/v4/projects/1/groups", 1): {"count": 1, "groups": [{"id": "g1"}]},
- ("/api/v4/projects/2/groups", 1): {"count": 1, "groups": [{"id": "g2"}]},
- }
- )
- _collect(
- _FakeResumableManager(),
- monkeypatch,
- pages,
+ def test_incremental_run_passes_start_time_to_every_project(self) -> None:
+ result = _driver().run(
"groups",
+ [
+ _page("projects", [{"id": 1}, {"id": 2}]),
+ _page("groups", [{"id": "g1"}]),
+ _page("groups", [{"id": "g2"}]),
+ ],
should_use_incremental_field=True,
db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
)
- groups_requests = [params for path, params in pages.requests if path.endswith("/groups")]
+ assert result.raised is None
+ groups_requests = [request for request in result.requests if request.path.endswith("/groups")]
assert len(groups_requests) == 2
- for params in groups_requests:
- assert params["start_time"] == "2026-03-04T02:58:14.000Z"
- assert params["order"] == "created"
-
- def test_resume_skips_projects_before_bookmark_and_reuses_saved_page(self, monkeypatch: Any) -> None:
- pages = _FakePages(
- {
- ("/api/v4/projects", 1): {"count": 3, "projects": [{"id": 1}, {"id": 2}, {"id": 3}]},
+ for request in groups_requests:
+ assert request.param("start_time") == "2026-03-04T02:58:14.000Z"
+ assert request.param("order") == "created"
+
+ def test_resume_skips_projects_before_bookmark_and_reuses_saved_page(self) -> None:
+ result = _driver().run(
+ "groups",
+ [
+ _page("projects", [{"id": 1}, {"id": 2}, {"id": 3}]),
# Project 1 must not be re-fetched; project 2 resumes at page 3.
- ("/api/v4/projects/2/groups", 3): {"count": 999, "groups": [{"id": "g2-p3"}]},
- ("/api/v4/projects/3/groups", 1): {"count": 1, "groups": [{"id": "g3"}]},
- }
+ _page("groups", [{"id": "g2-p3"}], count=999),
+ _page("groups", []),
+ _page("groups", [{"id": "g3"}]),
+ ],
+ resume_state=AirbrakeResumeConfig(page=3, project_id=2),
)
- manager = _FakeResumableManager(AirbrakeResumeConfig(page=3, project_id=2))
- rows = _collect(manager, monkeypatch, pages, "groups")
- assert rows == [{"id": "g2-p3"}, {"id": "g3"}]
- fetched_group_paths = [path for path, _params in pages.requests if path.endswith("/groups")]
- assert "/api/v4/projects/1/groups" not in fetched_group_paths
-
- def test_resume_from_deleted_project_restarts_from_first(self, monkeypatch: Any) -> None:
- pages = _FakePages(
- {
- ("/api/v4/projects", 1): {"count": 1, "projects": [{"id": 1}]},
- ("/api/v4/projects/1/groups", 1): {"count": 1, "groups": [{"id": "g1"}]},
- }
+ assert result.raised is None
+ assert result.rows == [{"id": "g2-p3"}, {"id": "g3"}]
+ assert result.paths == [
+ "/api/v4/projects",
+ "/api/v4/projects/2/groups",
+ "/api/v4/projects/2/groups",
+ "/api/v4/projects/3/groups",
+ ]
+ assert result.params("page") == ["1", "3", "4", "1"]
+
+ def test_resume_from_deleted_project_restarts_from_first(self) -> None:
+ result = _driver().run(
+ "groups",
+ [_page("projects", [{"id": 1}]), _page("groups", [{"id": "g1"}])],
+ resume_state=AirbrakeResumeConfig(page=5, project_id=999),
)
- manager = _FakeResumableManager(AirbrakeResumeConfig(page=5, project_id=999))
- rows = _collect(manager, monkeypatch, pages, "groups")
- assert rows == [{"id": "g1"}]
-
- def test_state_saved_after_each_page_and_bookmark_advanced_between_projects(self, monkeypatch: Any) -> None:
- pages = _FakePages(
- {
- ("/api/v4/projects", 1): {"count": 2, "projects": [{"id": 1}, {"id": 2}]},
- ("/api/v4/projects/1/groups", 1): {"count": 1, "groups": [{"id": "g1"}]},
- ("/api/v4/projects/2/groups", 1): {"count": 1, "groups": [{"id": "g2"}]},
- }
+ assert result.raised is None
+ assert result.rows == [{"id": "g1"}]
+ assert result.paths == ["/api/v4/projects", "/api/v4/projects/1/groups"]
+ assert result.params("page") == ["1", "1"]
+
+ def test_state_saved_after_each_page_and_bookmark_advanced_between_projects(self) -> None:
+ result = _driver().run(
+ "groups",
+ [
+ _page("projects", [{"id": 1}, {"id": 2}]),
+ _page("groups", [{"id": "g1"}]),
+ _page("groups", [{"id": "g2"}]),
+ ],
)
- manager = _FakeResumableManager()
- _collect(manager, monkeypatch, pages, "groups")
- assert manager.saved == [
+ assert result.raised is None
+ assert result.saved_states == [
AirbrakeResumeConfig(page=2, project_id=1),
AirbrakeResumeConfig(page=1, project_id=2),
AirbrakeResumeConfig(page=2, project_id=2),
]
- def test_project_deleted_mid_fan_out_is_skipped(self, monkeypatch: Any) -> None:
- pages = _FakePages(
- {
- ("/api/v4/projects", 1): {"count": 2, "projects": [{"id": 1}, {"id": 2}]},
- ("/api/v4/projects/1/groups", 1): requests.HTTPError(response=_response_with_status(404)),
- ("/api/v4/projects/2/groups", 1): {"count": 1, "groups": [{"id": "g2"}]},
- }
- )
- rows = _collect(_FakeResumableManager(), monkeypatch, pages, "groups")
- assert rows == [{"id": "g2"}]
-
- def test_non_404_http_error_propagates(self, monkeypatch: Any) -> None:
- pages = _FakePages(
- {
- ("/api/v4/projects", 1): {"count": 1, "projects": [{"id": 1}]},
- ("/api/v4/projects/1/groups", 1): requests.HTTPError(response=_response_with_status(500)),
- }
+ def test_project_deleted_mid_fan_out_is_skipped(self) -> None:
+ result = _driver().run(
+ "groups",
+ [
+ _page("projects", [{"id": 1}, {"id": 2}]),
+ ScriptedResponse(status=404),
+ _page("groups", [{"id": "g2"}]),
+ ],
)
- with pytest.raises(requests.HTTPError):
- _collect(_FakeResumableManager(), monkeypatch, pages, "groups")
+ assert result.raised is None
+ assert result.rows == [{"id": "g2"}]
+ assert result.paths[-1] == "/api/v4/projects/2/groups"
+
+ def test_non_404_http_error_propagates(self) -> None:
+ result = _driver().run("groups", [_page("projects", [{"id": 1}]), ScriptedResponse(status=403)])
+ assert isinstance(result.raised, requests.HTTPError)
+ assert result.raised.response is not None
+ assert result.raised.response.status_code == 403
class TestDeploysFanOut:
- def test_project_id_is_injected_into_deploy_rows(self, monkeypatch: Any) -> None:
+ def test_project_id_is_injected_into_deploy_rows(self) -> None:
# The Airbrake deploy payload carries no project reference; without injection the table
# can't be joined back to projects.
- pages = _FakePages(
- {
- ("/api/v4/projects", 1): {"count": 1, "projects": [{"id": 7}]},
- ("/api/v4/projects/7/deploys", 1): {
- "count": 1,
- "deploys": [{"environment": "production", "revision": "abc123"}],
- },
- }
+ result = _driver().run(
+ "deploys",
+ [
+ _page("projects", [{"id": 7}]),
+ _page("deploys", [{"environment": "production", "revision": "abc123"}]),
+ ],
)
- rows = _collect(_FakeResumableManager(), monkeypatch, pages, "deploys")
- assert rows == [{"environment": "production", "revision": "abc123", "projectId": 7}]
+ assert result.raised is None
+ assert result.rows == [{"environment": "production", "revision": "abc123", "projectId": 7}]
class TestNoticesFanOut:
- def test_resume_skips_groups_before_bookmark(self, monkeypatch: Any) -> None:
- pages = _FakePages(
- {
- ("/api/v4/projects", 1): {"count": 1, "projects": [{"id": 1}]},
- ("/api/v4/projects/1/groups", 1): {"count": 2, "groups": [{"id": "g1"}, {"id": "g2"}]},
- ("/api/v4/projects/1/groups/g2/notices", 2): {"count": 999, "notices": [{"id": "n2-p2"}]},
- }
+ def test_resume_skips_groups_before_bookmark(self) -> None:
+ result = _driver().run(
+ "notices",
+ [
+ _page("projects", [{"id": 1}]),
+ _page("groups", [{"id": "g1"}, {"id": "g2"}]),
+ _page("notices", [{"id": "n2-p2"}], count=999),
+ _page("notices", []),
+ ],
+ resume_state=AirbrakeResumeConfig(page=2, project_id=1, group_id="g2"),
)
- manager = _FakeResumableManager(AirbrakeResumeConfig(page=2, project_id=1, group_id="g2"))
- rows = _collect(manager, monkeypatch, pages, "notices")
- assert rows == [{"id": "n2-p2"}]
- fetched_notice_paths = [path for path, _params in pages.requests if "/notices" in path]
- assert "/api/v4/projects/1/groups/g1/notices" not in fetched_notice_paths
-
- def test_group_deleted_mid_fan_out_is_skipped(self, monkeypatch: Any) -> None:
- pages = _FakePages(
- {
- ("/api/v4/projects", 1): {"count": 1, "projects": [{"id": 1}]},
- ("/api/v4/projects/1/groups", 1): {"count": 2, "groups": [{"id": "gone"}, {"id": "g2"}]},
- ("/api/v4/projects/1/groups/gone/notices", 1): requests.HTTPError(response=_response_with_status(404)),
- ("/api/v4/projects/1/groups/g2/notices", 1): {"count": 1, "notices": [{"id": "n2"}]},
- }
+ assert result.raised is None
+ assert result.rows == [{"id": "n2-p2"}]
+ assert result.paths[2:] == [
+ "/api/v4/projects/1/groups/g2/notices",
+ "/api/v4/projects/1/groups/g2/notices",
+ ]
+ assert result.params("page")[2:] == ["2", "3"]
+
+ def test_group_deleted_mid_fan_out_is_skipped(self) -> None:
+ result = _driver().run(
+ "notices",
+ [
+ _page("projects", [{"id": 1}]),
+ _page("groups", [{"id": "gone"}, {"id": "g2"}]),
+ ScriptedResponse(status=404),
+ _page("notices", [{"id": "n2"}]),
+ ],
)
- rows = _collect(_FakeResumableManager(), monkeypatch, pages, "notices")
- assert rows == [{"id": "n2"}]
+ assert result.raised is None
+ assert result.rows == [{"id": "n2"}]
+ assert result.paths[-1] == "/api/v4/projects/1/groups/g2/notices"
- def test_per_group_history_is_capped(self, monkeypatch: Any) -> None:
+ def test_per_group_history_is_capped(self) -> None:
# One noisy group with unbounded history must not dominate the sync.
- pages = _FakePages(
- {
- ("/api/v4/projects", 1): {"count": 1, "projects": [{"id": 1}]},
- ("/api/v4/projects/1/groups", 1): {"count": 1, "groups": [{"id": "g1"}]},
- **{
- ("/api/v4/projects/1/groups/g1/notices", page): {"count": 99999, "notices": [{"id": f"n{page}"}]}
- for page in range(1, NOTICES_MAX_PAGES_PER_GROUP + 50)
- },
- }
+ result = _driver().run(
+ "notices",
+ [
+ _page("projects", [{"id": 1}]),
+ _page("groups", [{"id": "g1"}]),
+ *[
+ _page("notices", [{"id": f"n{page}"}], count=99999)
+ for page in range(1, NOTICES_MAX_PAGES_PER_GROUP + 1)
+ ],
+ ],
)
- rows = _collect(_FakeResumableManager(), monkeypatch, pages, "notices")
- assert len(rows) == NOTICES_MAX_PAGES_PER_GROUP
+ assert result.raised is None
+ assert len(result.rows) == NOTICES_MAX_PAGES_PER_GROUP
+ assert result.params("page")[2:] == [str(page) for page in range(1, NOTICES_MAX_PAGES_PER_GROUP + 1)]
def test_group_budget_caps_total_fan_out(self, monkeypatch: Any) -> None:
# The per-group page cap bounds each group, but only this budget bounds the two-level
# fan-out as a whole; an account with many groups must stop once it is exhausted.
monkeypatch.setattr(airbrake, "NOTICES_MAX_GROUPS_PER_SYNC", 2)
- pages = _FakePages(
- {
- ("/api/v4/projects", 1): {"count": 1, "projects": [{"id": 1}]},
- ("/api/v4/projects/1/groups", 1): {
- "count": 4,
- "groups": [{"id": "g1"}, {"id": "g2"}, {"id": "g3"}, {"id": "g4"}],
- },
- **{
- (f"/api/v4/projects/1/groups/{g}/notices", 1): {"count": 1, "notices": [{"id": f"n-{g}"}]}
- for g in ("g1", "g2", "g3", "g4")
- },
- }
+ result = _driver().run(
+ "notices",
+ [
+ _page("projects", [{"id": 1}]),
+ _page("groups", [{"id": "g1"}, {"id": "g2"}, {"id": "g3"}, {"id": "g4"}]),
+ _page("notices", [{"id": "n-g1"}]),
+ _page("notices", [{"id": "n-g2"}]),
+ ],
)
- rows = _collect(_FakeResumableManager(), monkeypatch, pages, "notices")
- assert rows == [{"id": "n-g1"}, {"id": "n-g2"}]
- fetched_notice_paths = [path for path, _params in pages.requests if "/notices" in path]
- assert "/api/v4/projects/1/groups/g3/notices" not in fetched_notice_paths
+ assert result.raised is None
+ assert result.rows == [{"id": "n-g1"}, {"id": "n-g2"}]
+ assert result.paths[2:] == [
+ "/api/v4/projects/1/groups/g1/notices",
+ "/api/v4/projects/1/groups/g2/notices",
+ ]
class TestSourceResponse:
@@ -344,26 +303,28 @@ class TestSourceResponse:
) -> None:
# Dropping groupId from the notices key multi-matches merges if notice ids repeat across
# groups; partitioning on a mutable field rewrites partitions every sync.
- response = airbrake_source(
- api_key="user-key", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()
- )
- assert response.primary_keys == expected_pks
- assert response.partition_keys == expected_partition_keys
+ result = _driver().run(endpoint, [_page("projects", [])])
+ assert result.raised is None
+ assert result.response is not None
+ assert result.response.primary_keys == expected_pks
+ assert result.response.partition_keys == expected_partition_keys
# Watermark persistence must stay deferred to job end: fan-out batches arrive per project,
# so per-batch asc checkpointing could advance the cursor past projects a crashed run never reached.
- assert response.sort_mode == "desc"
+ assert result.response.sort_mode == "desc"
class TestValidateCredentials:
@parameterized.expand([("valid", 200, True), ("invalid_key", 401, False), ("forbidden", 403, False)])
def test_status_mapping(self, _name: str, status_code: int, expected: bool) -> None:
- session = MagicMock()
- session.get.return_value = MagicMock(status_code=status_code)
- with patch.object(airbrake, "make_tracked_session", return_value=session):
+ with scripted_network([ScriptedResponse(status=status_code)]) as network:
assert validate_credentials("user-key") is expected
+ assert len(network.requests_log) == 1
+ assert network.requests_log[0].path == "/api/v4/projects"
+ assert network.requests_log[0].param("key") == "user-key"
+ assert network.requests_log[0].param("limit") == "1"
def test_network_error_maps_to_invalid(self) -> None:
- session = MagicMock()
- session.get.side_effect = requests.ConnectionError("boom")
- with patch.object(airbrake, "make_tracked_session", return_value=session):
+ with scripted_network(always(requests.ConnectionError("boom"))) as network:
assert validate_credentials("user-key") is False
+ # The real stack retries a dropped connection.
+ assert {request.path for request in network.requests_log} == {"/api/v4/projects"}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/tests/test_airbrake_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/tests/test_airbrake_source.py
index 92295702b6a8..78eb00c7dd5c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/tests/test_airbrake_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/tests/test_airbrake_source.py
@@ -1,11 +1,17 @@
from datetime import UTC, datetime
-from unittest.mock import MagicMock, patch
-
from parameterized import parameterized
from products.warehouse_sources.backend.facade.source_config import SourceFieldInputConfig, SourceFieldInputConfigType
from products.warehouse_sources.backend.temporal.data_imports.sources.airbrake.source import AirbrakeSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.airbrake import (
+ AirbrakeSourceConfig,
+)
class TestAirbrakeSource:
@@ -23,19 +29,16 @@ class TestAirbrakeSource:
assert api_key.required is True
def test_get_schemas_filters_by_names(self) -> None:
- schemas = AirbrakeSource().get_schemas(MagicMock(), team_id=1, names=["groups"])
+ schemas = AirbrakeSource().get_schemas(AirbrakeSourceConfig(api_key="user-key"), team_id=1, names=["groups"])
assert [s.name for s in schemas] == ["groups"]
@parameterized.expand([("valid", True, (True, None)), ("invalid", False, (False, "Invalid Airbrake user API key"))])
- def test_validate_credentials(self, _name: str, transport_result: bool, expected: tuple) -> None:
- config = MagicMock()
- config.api_key = "user-key"
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.airbrake.source.validate_airbrake_credentials",
- return_value=transport_result,
- ) as validate:
- assert AirbrakeSource().validate_credentials(config, team_id=1) == expected
- validate.assert_called_once_with("user-key")
+ def test_validate_credentials(self, _name: str, transport_result: bool, expected: tuple[bool, str | None]) -> None:
+ with scripted_network([ScriptedResponse(status=200 if transport_result else 401)]) as network:
+ result = AirbrakeSource().validate_credentials(AirbrakeSourceConfig(api_key="user-key"), team_id=1)
+ assert result == expected
+ assert len(network.requests_log) == 1
+ assert network.requests_log[0].param("key") == "user-key"
@parameterized.expand(
[
@@ -48,26 +51,21 @@ class TestAirbrakeSource:
def test_source_for_pipeline_plumbs_incremental_inputs(
self, _name: str, should_use_incremental_field: bool, last_value: datetime, expected_last_value: datetime | None
) -> None:
- config = MagicMock()
- config.api_key = "user-key"
- inputs = MagicMock()
- inputs.schema_name = "groups"
- inputs.should_use_incremental_field = should_use_incremental_field
- inputs.db_incremental_field_last_value = last_value
- manager = MagicMock()
-
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.airbrake.source.airbrake_source"
- ) as airbrake_source_mock:
- AirbrakeSource().source_for_pipeline(config, manager, inputs)
-
- airbrake_source_mock.assert_called_once_with(
- api_key="user-key",
- endpoint="groups",
- logger=inputs.logger,
- resumable_source_manager=manager,
+ result = SourceDriver(AirbrakeSource(), AirbrakeSourceConfig(api_key="user-key")).run(
+ "groups",
+ [
+ ScriptedResponse(json={"count": 1, "projects": [{"id": 1}]}),
+ ScriptedResponse(json={"count": 1, "groups": [{"id": "g1"}]}),
+ ],
should_use_incremental_field=should_use_incremental_field,
- db_incremental_field_last_value=expected_last_value,
+ db_incremental_field_last_value=last_value,
+ )
+ assert result.raised is None
+ assert result.rows == [{"id": "g1"}]
+ assert result.paths == ["/api/v4/projects", "/api/v4/projects/1/groups"]
+ assert result.requests[1].param("key") == "user-key"
+ assert result.requests[1].param("start_time") == (
+ "2026-03-04T00:00:00.000Z" if expected_last_value is not None else None
)
@parameterized.expand(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/tests/test_aircall.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/tests/test_aircall.py
index 089f5ccac770..2a006870efcc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/tests/test_aircall.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aircall/tests/test_aircall.py
@@ -20,13 +20,18 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.aircall.se
AIRCALL_ENDPOINTS,
ENDPOINTS,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aircall.source import AircallSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.aircall import (
+ AircallSourceConfig,
+)
# RESTClient builds its session via make_tracked_session in the rest_client module.
CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
-# validate_credentials builds its own tracked session in the aircall module.
-AIRCALL_SESSION_PATCH = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.aircall.aircall.make_tracked_session"
-)
def _response(items_key: str, items: list[dict[str, Any]], next_link: str | None) -> Response:
@@ -37,13 +42,6 @@ def _response(items_key: str, items: list[dict[str, Any]], next_link: str | None
return resp
-def _plain_response(status_code: int, body: dict[str, Any]) -> Response:
- resp = Response()
- resp.status_code = status_code
- resp._content = json.dumps(body).encode()
- return resp
-
-
def _make_manager(resume_state: AircallResumeConfig | None = None) -> mock.MagicMock:
manager = mock.MagicMock()
manager.can_resume.return_value = resume_state is not None
@@ -77,6 +75,14 @@ def _rows(source_response) -> list[dict[str, Any]]:
return [row for page in source_response.items() for row in page]
+def _driver() -> SourceDriver:
+ return SourceDriver(AircallSource(), AircallSourceConfig(api_id="id", api_token="token"))
+
+
+def _page(items_key: str, items: list[dict[str, Any]], next_link: str | None) -> ScriptedResponse:
+ return ScriptedResponse(json={"meta": {"next_page_link": next_link}, items_key: items})
+
+
class TestToEpoch:
@pytest.mark.parametrize(
"value, expected",
@@ -109,83 +115,66 @@ class TestBuildUrl:
class TestValidateCredentials:
- @mock.patch(AIRCALL_SESSION_PATCH)
- def test_validate_credentials_probes_ping_with_basic_auth(self, mock_session):
- mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
-
- validate_credentials("id", "token")
+ def test_validate_credentials_probes_ping_with_basic_auth(self) -> None:
+ with scripted_network([ScriptedResponse(status=200)]) as network:
+ assert validate_credentials("id", "token") is True
- call = mock_session.return_value.get.call_args
- assert call.args[0] == "https://api.aircall.io/v1/ping"
- assert call.kwargs["auth"].username == "id"
- assert call.kwargs["auth"].password == "token"
+ assert [request.url for request in network.requests_log] == ["https://api.aircall.io/v1/ping"]
+ assert network.requests_log[0].headers["authorization"] == "Basic aWQ6dG9rZW4="
+ assert network.session_options[0]["redact_values"] == ("token",)
class TestPagination:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_paginates_via_next_page_link(self, MockSession):
- session = MockSession.return_value
- requests_seen = _wire(
- session,
+ def test_paginates_via_next_page_link(self) -> None:
+ result = _driver().run(
+ "users",
[
- _response("users", [{"id": 1}, {"id": 2}], "https://api.aircall.io/v1/users?page=2"),
- _response("users", [{"id": 3}], None),
+ _page("users", [{"id": 1}, {"id": 2}], "https://api.aircall.io/v1/users?page=2"),
+ _page("users", [{"id": 3}], None),
],
)
- manager = _make_manager()
- rows = _rows(_source("users", manager))
-
- assert [row["id"] for row in rows] == [1, 2, 3]
- assert requests_seen[0]["url"] == "https://api.aircall.io/v1/users"
- assert requests_seen[0]["params"] == {"per_page": 50}
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == [1, 2, 3]
+ assert result.urls[0] == "https://api.aircall.io/v1/users?per_page=50"
+ assert result.queries[0] == {"per_page": ("50",)}
# The next-page URL is self-contained; original params are dropped.
- assert requests_seen[1]["url"] == "https://api.aircall.io/v1/users?page=2"
- assert requests_seen[1]["params"] == {}
+ assert result.urls[1] == "https://api.aircall.io/v1/users?page=2"
+ assert result.queries[1] == {"page": ("2",)}
# State is saved only while a next page exists.
- manager.save_state.assert_called_once()
- assert manager.save_state.call_args.args[0] == AircallResumeConfig(
- next_url="https://api.aircall.io/v1/users?page=2"
- )
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_resumes_from_saved_state(self, MockSession):
- session = MockSession.return_value
- requests_seen = _wire(session, [_response("users", [{"id": 9}], None)])
+ assert result.saved_states == [AircallResumeConfig(next_url="https://api.aircall.io/v1/users?page=2")]
+ def test_resumes_from_saved_state(self) -> None:
resume_url = "https://api.aircall.io/v1/users?page=5"
- manager = _make_manager(AircallResumeConfig(next_url=resume_url))
-
- rows = _rows(_source("users", manager))
+ result = _driver().run(
+ "users", [_page("users", [{"id": 9}], None)], resume_state=AircallResumeConfig(next_url=resume_url)
+ )
- assert [row["id"] for row in rows] == [9]
- assert requests_seen[0]["url"] == resume_url
- assert requests_seen[0]["params"] == {}
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == [9]
+ assert result.urls == [resume_url]
+ assert result.queries == [{"page": ("5",)}]
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_reanchors_from_cursor_when_page_chain_ends(self, MockSession):
+ def test_reanchors_from_cursor_when_page_chain_ends(self) -> None:
# First window ends without a next link; the latest started_at is used to issue a
# fresh `from`-anchored request, then that window ends with no new advancement.
- session = MockSession.return_value
- requests_seen = _wire(
- session,
+ result = _driver().run(
+ "calls",
[
- _response("calls", [{"id": 1, "started_at": 100}, {"id": 2, "started_at": 200}], None),
- _response("calls", [{"id": 2, "started_at": 200}], None),
+ _page("calls", [{"id": 1, "started_at": 100}, {"id": 2, "started_at": 200}], None),
+ _page("calls", [{"id": 2, "started_at": 200}], None),
],
)
- manager = _make_manager()
- rows = _rows(_source("calls", manager))
-
# Two requests: original window + one re-anchored window.
- assert len(requests_seen) == 2
- assert "from=200" in requests_seen[1]["url"]
+ assert result.raised is None
+ assert len(result.requests) == 2
+ assert result.requests[1].param("from") == "200"
# The re-anchored window URL is checkpointed like a next-page link.
- manager.save_state.assert_called_once()
- assert "from=200" in manager.save_state.call_args.args[0].next_url
+ assert len(result.saved_states) == 1
+ assert "from=200" in result.saved_states[0].next_url
# Boundary row re-emitted; merge on primary key dedupes downstream.
- assert [row["id"] for row in rows] == [1, 2, 2]
+ assert [row["id"] for row in result.rows] == [1, 2, 2]
@mock.patch(CLIENT_SESSION_PATCH)
def test_reanchors_after_cap_records_when_next_link_has_no_page(self, MockSession):
@@ -207,102 +196,86 @@ class TestPagination:
assert len(requests_seen) == 201
assert "from=10000" in requests_seen[200]["url"]
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_raises_when_a_capped_window_cursor_cannot_advance(self, MockSession):
+ def test_raises_when_a_capped_window_cursor_cannot_advance(self) -> None:
# Every record in the capped window shares the boundary timestamp, so a re-anchored
# window would repeat the same query forever and the rest of the window is unreachable.
# Raise so the run fails visibly instead of finalizing as complete with missing data.
- session = MockSession.return_value
over_cap_link = "https://api.aircall.io/v1/contacts?order=asc&per_page=50&page=201"
- _wire(session, [_response("contacts", [{"id": 1, "created_at": 200}], over_cap_link)])
-
- manager = _make_manager()
- with pytest.raises(AircallTruncationError):
- _rows(
- _source(
- "contacts",
- manager,
- should_use_incremental_field=True,
- db_incremental_field_last_value=200,
- incremental_field="created_at",
- )
- )
+ result = _driver().run(
+ "contacts",
+ [_page("contacts", [{"id": 1, "created_at": 200}], over_cap_link)],
+ incremental_field="created_at",
+ db_incremental_field_last_value=200,
+ )
- manager.save_state.assert_not_called()
+ assert isinstance(result.raised, AircallTruncationError)
+ assert result.requests[0].param("from") == "200"
+ assert result.saved_states == []
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_incremental_run_anchors_from_on_watermark(self, MockSession):
- session = MockSession.return_value
- requests_seen = _wire(session, [_response("calls", [{"id": 1, "started_at": 1700000000}], None)])
-
- _rows(
- _source(
- "calls",
- _make_manager(),
- should_use_incremental_field=True,
- db_incremental_field_last_value=1700000000,
- incremental_field="started_at",
- )
+ def test_incremental_run_anchors_from_on_watermark(self) -> None:
+ result = _driver().run(
+ "calls",
+ [_page("calls", [{"id": 1, "started_at": 1700000000}], None)],
+ incremental_field="started_at",
+ db_incremental_field_last_value=1700000000,
)
- assert requests_seen[0]["params"] == {"per_page": 50, "order": "asc", "from": 1700000000}
+ assert result.raised is None
+ assert result.queries[0] == {"per_page": ("50",), "order": ("asc",), "from": ("1700000000",)}
# started_at did not advance past the watermark, so no re-anchored window is issued.
- assert len(requests_seen) == 1
+ assert len(result.requests) == 1
class TestConversationIntelligenceFanout:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_child_rows_carry_call_id_from_parent(self, MockSession):
+ def test_child_rows_carry_call_id_from_parent(self) -> None:
# The per-call sub-resource is fanned out over the calls list. Each child row must carry
# the parent call id as `call_id` (the primary key), overriding whatever the body itself
# holds, so one CI object per call stays uniquely keyed.
- session = MockSession.return_value
- requests_seen = _wire(
- session,
+ result = _driver().run(
+ "call_transcriptions",
[
- _response("calls", [{"id": 1, "started_at": 100}, {"id": 2, "started_at": 200}], None),
- _plain_response(200, {"id": 55, "content": "hi", "call_id": 999}),
- _plain_response(200, {"id": 66, "content": "yo"}),
+ _page("calls", [{"id": 1, "started_at": 100}, {"id": 2, "started_at": 200}], None),
+ ScriptedResponse(json={"id": 55, "content": "hi", "call_id": 999}),
+ ScriptedResponse(json={"id": 66, "content": "yo"}),
# The calls paginator re-anchors once the first window ends; an empty window stops it.
- _response("calls", [], None),
+ _page("calls", [], None),
],
)
- rows = _rows(_source("call_transcriptions", _make_manager()))
-
- assert [(row["call_id"], row["id"], row["content"]) for row in rows] == [(1, 55, "hi"), (2, 66, "yo")]
- child_urls = [req["url"] for req in requests_seen if "transcription" in (req["url"] or "")]
- assert child_urls == [
- "https://api.aircall.io/v1/calls/1/transcription",
- "https://api.aircall.io/v1/calls/2/transcription",
+ assert result.raised is None
+ assert [(row["call_id"], row["id"], row["content"]) for row in result.rows] == [
+ (1, 55, "hi"),
+ (2, 66, "yo"),
]
+ child_paths = [path for path in result.paths if "transcription" in path]
+ assert child_paths == ["/v1/calls/1/transcription", "/v1/calls/2/transcription"]
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_calls_without_ci_data_are_skipped(self, MockSession):
+ def test_calls_without_ci_data_are_skipped(self) -> None:
# A call with no AI data answers 404; that call is skipped rather than sinking the table.
- session = MockSession.return_value
- _wire(
- session,
+ result = _driver().run(
+ "call_evaluations",
[
- _response("calls", [{"id": 1, "started_at": 100}, {"id": 2, "started_at": 200}], None),
- _plain_response(404, {"error": "not found"}),
- _plain_response(200, {"id": 66, "content": "yo"}),
- _response("calls", [], None),
+ _page("calls", [{"id": 1, "started_at": 100}, {"id": 2, "started_at": 200}], None),
+ ScriptedResponse(status=404, json={"error": "not found"}),
+ ScriptedResponse(json={"id": 66, "content": "yo"}),
+ _page("calls", [], None),
],
)
- rows = _rows(_source("call_evaluations", _make_manager()))
-
- assert [row["call_id"] for row in rows] == [2]
+ assert result.raised is None
+ assert [row["call_id"] for row in result.rows] == [2]
class TestAircallSourceResponse:
@pytest.mark.parametrize("endpoint", list(ENDPOINTS))
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_response_metadata_per_endpoint(self, MockSession, endpoint):
+ def test_response_metadata_per_endpoint(self, endpoint: str) -> None:
config = AIRCALL_ENDPOINTS[endpoint]
- response = _source(endpoint, _make_manager())
+ schema_name = "calls" if config.fanout else endpoint
+ result = _driver().run(endpoint, [_page(schema_name, [], None)])
+ response = result.response
+ assert result.raised is None
+ assert response is not None
assert response.name == endpoint
assert response.primary_keys == [config.primary_key]
assert response.sort_mode == "asc"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airops/tests/test_airops.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airops/tests/test_airops.py
index 38b2282df012..c9aba2cfde28 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/airops/tests/test_airops.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airops/tests/test_airops.py
@@ -1,12 +1,6 @@
-import json
-from collections.abc import Iterable
-from typing import Any, cast
-
import pytest
-from unittest import mock
import requests
-from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.airops.airops import (
AIROPS_BASE_URL,
@@ -16,219 +10,180 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.airops.air
airops_source,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.airops.source import AirOpsSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
- RESTClient,
RESTClientRetryableError,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
-
-# All AirOps traffic (sync + credential probe) flows through _make_session, which builds its
-# tracked session in the airops module — so one patch point covers every request.
-SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.airops.airops.make_tracked_session"
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.airops import AirOpsSourceConfig
APPS_URL = f"{AIROPS_BASE_URL}/public_api/airops_apps"
BRAND_KITS_URL = f"{AIROPS_BASE_URL}/{BRAND_KIT_LIST_PATH}"
-def _response(body: Any, status: int = 200, reason: str | None = None, url: str = APPS_URL) -> Response:
- resp = Response()
- resp.status_code = status
- resp._content = json.dumps(body).encode()
- resp.reason = cast("str", reason)
- resp.url = url
- resp.headers["Content-Type"] = "application/json"
- return resp
-
-
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
- """Wire a mock session and snapshot each request's URL, params, and auth headers AT PREPARE
- TIME — the paginator mutates the params dict in place between pages, so a later look at the
- same dict would show the final page's params for every request."""
- session.headers = {}
- seen: list[dict[str, Any]] = []
-
- def _prepare(request: Any) -> mock.MagicMock:
- prepared = mock.MagicMock()
- prepared.headers = {}
- if request.auth is not None:
- request.auth(prepared)
- seen.append(
- {
- "url": request.url,
- "params": dict(request.params or {}),
- # Brand-kit endpoints carry pagination in the POST body; snapshot it here for the
- # same in-place-mutation reason as params.
- "json": dict(request.json or {}),
- "auth_headers": dict(prepared.headers),
- }
- )
- return prepared
-
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = responses
- return seen
+def _driver() -> SourceDriver:
+ return SourceDriver(AirOpsSource(), AirOpsSourceConfig(api_key="k"))
def _source(endpoint: str) -> SourceResponse:
return airops_source(api_key="k", endpoint=endpoint, team_id=1, job_id="j")
-def _batches(source_response: SourceResponse) -> list[list[dict[str, Any]]]:
- return [list(page) for page in cast("Iterable[Any]", source_response.items())]
-
-
class TestMakeSession:
def test_disables_sample_capture_and_redirects(self) -> None:
# Executions carry free-form inputs/output that can hold user secrets the name-based
# scrubbers can't recognise, so response capture must stay off; redirects stay pinned off
# so a credentialed request can't be replayed against another host.
- with mock.patch(SESSION_PATCH) as make_session:
+ with scripted_network([]) as network:
_make_session("secret-key")
- assert make_session.call_args.kwargs["capture"] is False
- assert make_session.call_args.kwargs["allow_redirects"] is False
- assert make_session.call_args.kwargs["redact_values"] == ("secret-key",)
- assert make_session.call_args.kwargs["headers"] == {"Accept": "application/json"}
+
+ assert network.session_options == [
+ {
+ "capture": False,
+ "allow_redirects": False,
+ "redact_values": ("secret-key",),
+ "headers": {"Accept": "application/json"},
+ }
+ ]
class TestApps:
- @mock.patch(SESSION_PATCH)
- def test_non_list_body_fails_loud(self, MockSession: mock.MagicMock) -> None:
+ def test_non_list_body_fails_loud(self) -> None:
# The documented shape is a bare array; a 200 with anything else means the response shape
# changed — fail loud rather than silently syncing 0 (or garbage) rows.
- _wire(MockSession.return_value, [_response({"data": [{"id": 1}]})])
- with pytest.raises(ValueError, match="list response body"):
- _batches(_source("apps"))
+ result = _driver().run("apps", [ScriptedResponse(json={"data": [{"id": 1}]})])
+
+ assert isinstance(result.raised, ValueError)
+ assert "list response body" in str(result.raised)
class TestExecutions:
- @mock.patch(SESSION_PATCH)
- def test_fans_out_over_apps_and_paginates(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- seen = _wire(
- session,
+ def test_fans_out_over_apps_and_paginates(self) -> None:
+ result = _driver().run(
+ "executions",
[
- _response([{"id": 10}, {"id": 20}]), # apps
- _response({"data": [{"id": "e1"}], "meta": {"has_more": True, "cursor": "c1"}}), # app 10 page 1
- _response({"data": [{"id": "e2"}], "meta": {"has_more": False, "cursor": None}}), # app 10 page 2
- _response({"data": [{"id": "e3"}], "meta": {"has_more": False}}), # app 20 page 1
+ ScriptedResponse(json=[{"id": 10}, {"id": 20}]), # apps
+ ScriptedResponse(
+ json={"data": [{"id": "e1"}], "meta": {"has_more": True, "cursor": "c1"}}
+ ), # app 10 page 1
+ ScriptedResponse(
+ json={"data": [{"id": "e2"}], "meta": {"has_more": False, "cursor": None}}
+ ), # app 10 page 2
+ ScriptedResponse(json={"data": [{"id": "e3"}], "meta": {"has_more": False}}), # app 20 page 1
],
)
- batches = _batches(_source("executions"))
-
- rows = [row for batch in batches for row in batch]
# Every execution row is stamped with its parent app id so the flattened table can be joined
# back and the primary key stays meaningful table-wide.
- assert rows == [
+ assert result.raised is None
+ assert result.rows == [
{"id": "e1", "airops_app_id": 10},
{"id": "e2", "airops_app_id": 10},
{"id": "e3", "airops_app_id": 20},
]
# 1 apps call + 2 pages for app 10 + 1 page for app 20.
- assert session.send.call_count == 4
- assert [s["url"] for s in seen] == [
+ assert len(result.requests) == 4
+ assert result.urls == [
APPS_URL,
- f"{APPS_URL}/10/executions",
- f"{APPS_URL}/10/executions",
- f"{APPS_URL}/20/executions",
+ f"{APPS_URL}/10/executions?items=100",
+ f"{APPS_URL}/10/executions?items=100&cursor=c1",
+ f"{APPS_URL}/20/executions?items=100",
]
# Page size is pinned to the endpoint's cap; the second page carries the cursor returned by
# the first, and a fresh parent starts without one.
- assert seen[1]["params"] == {"items": 100}
- assert seen[2]["params"] == {"items": 100, "cursor": "c1"}
- assert seen[3]["params"] == {"items": 100}
+ assert result.queries[1:] == [
+ {"items": ("100",)},
+ {"items": ("100",), "cursor": ("c1",)},
+ {"items": ("100",)},
+ ]
- @mock.patch(SESSION_PATCH)
- def test_stops_when_has_more_false_even_if_cursor_present(self, MockSession: mock.MagicMock) -> None:
+ def test_stops_when_has_more_false_even_if_cursor_present(self) -> None:
# An explicit has_more=false ends the app's pagination even when a cursor is echoed back,
# so the last page isn't paid for twice.
- session = MockSession.return_value
- _wire(
- session,
+ result = _driver().run(
+ "executions",
[
- _response([{"id": 10}]),
- _response({"data": [{"id": "e1"}], "meta": {"has_more": False, "cursor": "c1"}}),
+ ScriptedResponse(json=[{"id": 10}]),
+ ScriptedResponse(json={"data": [{"id": "e1"}], "meta": {"has_more": False, "cursor": "c1"}}),
],
)
- batches = _batches(_source("executions"))
-
- assert [row for batch in batches for row in batch] == [{"id": "e1", "airops_app_id": 10}]
- assert session.send.call_count == 2
+ assert result.raised is None
+ assert result.rows == [{"id": "e1", "airops_app_id": 10}]
+ assert len(result.requests) == 2
- @mock.patch(SESSION_PATCH)
- def test_fails_when_app_missing_id(self, MockSession: mock.MagicMock) -> None:
+ def test_fails_when_app_missing_id(self) -> None:
# A missing app id must fail loudly rather than silently dropping that app's executions.
- _wire(MockSession.return_value, [_response([{"name": "no id"}])])
- with pytest.raises(ValueError, match="field 'id'"):
- _batches(_source("executions"))
+ result = _driver().run("executions", [ScriptedResponse(json=[{"name": "no id"}])])
+
+ assert isinstance(result.raised, ValueError)
+ assert "field 'id'" in str(result.raised)
class TestBrandKits:
- @mock.patch(SESSION_PATCH)
- def test_missing_data_key_fails_loud(self, MockSession: mock.MagicMock) -> None:
+ def test_missing_data_key_fails_loud(self) -> None:
# A 200 whose body drops the `data` array means the response shape changed — fail loud
# instead of silently syncing 0 rows.
- _wire(MockSession.return_value, [_response({"meta": {"total_pages": 1}}, url=BRAND_KITS_URL)])
- with pytest.raises(Exception, match="data"):
- _batches(_source("brand_kits"))
+ result = _driver().run("brand_kits", [ScriptedResponse(json={"meta": {"total_pages": 1}})])
+
+ assert isinstance(result.raised, Exception)
+ assert "data" in str(result.raised)
class TestBrandKitFanout:
@pytest.mark.parametrize("endpoint", ["prompts", "citations"])
- @mock.patch(SESSION_PATCH)
- def test_fans_out_over_brand_kits_and_stamps_parent_id(self, MockSession: mock.MagicMock, endpoint: str) -> None:
- session = MockSession.return_value
- seen = _wire(
- session,
+ def test_fans_out_over_brand_kits_and_stamps_parent_id(self, endpoint: str) -> None:
+ result = _driver().run(
+ endpoint,
[
- _response({"data": [{"id": 10}, {"id": 20}], "meta": {"total_pages": 1}}, url=BRAND_KITS_URL),
- _response({"data": [{"url": "a"}], "meta": {"total_pages": 1}}), # kit 10
- _response({"data": [{"url": "b"}], "meta": {"total_pages": 1}}), # kit 20
+ ScriptedResponse(json={"data": [{"id": 10}, {"id": 20}], "meta": {"total_pages": 1}}),
+ ScriptedResponse(json={"data": [{"url": "a"}], "meta": {"total_pages": 1}}), # kit 10
+ ScriptedResponse(json={"data": [{"url": "b"}], "meta": {"total_pages": 1}}), # kit 20
],
)
- rows = [row for batch in _batches(_source(endpoint)) for row in batch]
-
# Every child row is stamped with its parent brand kit id so the flattened table's composite
# key stays unique across brand kits.
- assert rows == [{"url": "a", "brand_kit_id": 10}, {"url": "b", "brand_kit_id": 20}]
- assert [s["url"] for s in seen] == [
+ assert result.raised is None
+ assert result.rows == [{"url": "a", "brand_kit_id": 10}, {"url": "b", "brand_kit_id": 20}]
+ assert result.urls == [
BRAND_KITS_URL,
f"{AIROPS_BASE_URL}/{BRAND_KITS_PATH}/10/{endpoint}/list",
f"{AIROPS_BASE_URL}/{BRAND_KITS_PATH}/20/{endpoint}/list",
]
@pytest.mark.parametrize("endpoint", ["prompts", "citations"])
- @mock.patch(SESSION_PATCH)
- def test_skips_brand_kit_without_aeo_configured(self, MockSession: mock.MagicMock, endpoint: str) -> None:
+ def test_skips_brand_kit_without_aeo_configured(self, endpoint: str) -> None:
# A brand kit that hasn't configured AEO answers the child endpoint with 412; that brand kit
# is skipped rather than failing the whole table, and its siblings still sync.
- session = MockSession.return_value
- _wire(
- session,
+ result = _driver().run(
+ endpoint,
[
- _response({"data": [{"id": 10}, {"id": 20}], "meta": {"total_pages": 1}}, url=BRAND_KITS_URL),
- _response({"error": "AEO not configured"}, status=412, reason="Precondition Failed"), # kit 10
- _response({"data": [{"url": "b"}], "meta": {"total_pages": 1}}), # kit 20
+ ScriptedResponse(json={"data": [{"id": 10}, {"id": 20}], "meta": {"total_pages": 1}}),
+ ScriptedResponse(status=412, json={"error": "AEO not configured"}), # kit 10
+ ScriptedResponse(json={"data": [{"url": "b"}], "meta": {"total_pages": 1}}), # kit 20
],
)
- rows = [row for batch in _batches(_source(endpoint)) for row in batch]
-
- assert rows == [{"url": "b", "brand_kit_id": 20}]
- assert session.send.call_count == 3
+ assert result.raised is None
+ assert result.rows == [{"url": "b", "brand_kit_id": 20}]
+ assert len(result.requests) == 3
@pytest.mark.parametrize("endpoint", ["prompts", "citations"])
- @mock.patch(SESSION_PATCH)
- def test_fails_when_brand_kit_missing_id(self, MockSession: mock.MagicMock, endpoint: str) -> None:
+ def test_fails_when_brand_kit_missing_id(self, endpoint: str) -> None:
# A brand kit without an `id` can't be fanned out — fail loud rather than dropping its rows.
- _wire(
- MockSession.return_value,
- [_response({"data": [{"name": "no id"}], "meta": {"total_pages": 1}}, url=BRAND_KITS_URL)],
+ result = _driver().run(
+ endpoint,
+ [ScriptedResponse(json={"data": [{"name": "no id"}], "meta": {"total_pages": 1}})],
)
- with pytest.raises(ValueError, match="missing its 'id'"):
- _batches(_source(endpoint))
+
+ assert isinstance(result.raised, ValueError)
+ assert "missing its 'id'" in str(result.raised)
class TestUnknownEndpoint:
@@ -239,39 +194,36 @@ class TestUnknownEndpoint:
class TestErrorHandling:
@pytest.mark.parametrize("status", [429, 500, 503])
- @mock.patch(SESSION_PATCH)
- def test_retryable_statuses_retry_then_raise(self, MockSession: mock.MagicMock, status: int) -> None:
+ def test_retryable_statuses_retry_then_raise(self, status: int) -> None:
# 429/5xx are retried by the framework client; once attempts are exhausted the last
- # retryable error is reraised. Patch tenacity's sleep so the retries don't actually wait.
- session = MockSession.return_value
- _wire(session, [_response({}, status=status) for _ in range(5)])
+ # retryable error is reraised.
+ result = _driver().run("apps", [ScriptedResponse(status=status, json={}) for _ in range(5)])
- with (
- mock.patch.object(RESTClient._send_request.retry, "sleep"), # type: ignore[attr-defined]
- pytest.raises(RESTClientRetryableError),
- ):
- _batches(_source("apps"))
- assert session.send.call_count == 5
+ assert isinstance(result.raised, RESTClientRetryableError)
+ assert len(result.requests) == 5
@pytest.mark.parametrize(
"status, reason",
[(400, "Bad Request"), (401, "Unauthorized"), (403, "Forbidden"), (404, "Not Found")],
)
- @mock.patch(SESSION_PATCH)
- def test_client_errors_propagate_as_httperror(self, MockSession: mock.MagicMock, status: int, reason: str) -> None:
+ def test_client_errors_propagate_as_httperror(self, status: int, reason: str) -> None:
# 4xx (bad/expired credentials, missing app) must surface as HTTPError so
# get_non_retryable_errors can match and permanently fail the sync.
- _wire(MockSession.return_value, [_response({"error": "nope"}, status=status, reason=reason)])
- with pytest.raises(requests.HTTPError, match=f"{status} Client Error"):
- _batches(_source("apps"))
+ result = _driver().run("apps", [ScriptedResponse(status=status, json={"error": "nope"})])
+
+ assert isinstance(result.raised, requests.HTTPError)
+ assert f"{status} Client Error: {reason}" in str(result.raised)
class TestValidateCredentials:
@pytest.mark.parametrize(("status", "expected"), [(200, True), (401, False), (403, False)])
- @mock.patch(SESSION_PATCH)
- def test_maps_status_to_bool(self, MockSession: mock.MagicMock, status: int, expected: bool) -> None:
- MockSession.return_value.get.return_value = mock.MagicMock(status_code=status)
- assert validate_credentials("key") is expected
+ def test_maps_status_to_bool(self, status: int, expected: bool) -> None:
+ with scripted_network([ScriptedResponse(status=status)]) as network:
+ assert validate_credentials("key") is expected
+
+ assert len(network.requests_log) == 1
+ assert network.requests_log[0].url == APPS_URL
+ assert network.requests_log[0].headers["authorization"] == "Bearer key"
class TestAirOpsSourceResponse:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airops/tests/test_airops_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airops/tests/test_airops_source.py
index 204e2eceaef1..037e89ff30b6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/airops/tests/test_airops_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airops/tests/test_airops_source.py
@@ -1,8 +1,10 @@
-from unittest.mock import patch
-
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.airops.source import AirOpsSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ scripted_network,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.airops import AirOpsSourceConfig
@@ -13,11 +15,10 @@ def _config(api_key: str = "test-key") -> AirOpsSourceConfig:
class TestAirOpsSource:
@parameterized.expand([("valid", True, (True, None)), ("invalid", False, (False, "Invalid AirOps API key"))])
def test_validate_credentials(self, _name: str, probe_result: bool, expected: tuple[bool, str | None]) -> None:
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.airops.source.validate_airops_credentials",
- return_value=probe_result,
- ):
+ with scripted_network([ScriptedResponse(status=200 if probe_result else 401)]) as network:
assert AirOpsSource().validate_credentials(_config(), team_id=1) == expected
+ assert len(network.requests_log) == 1
+ assert network.requests_log[0].headers["authorization"] == "Bearer test-key"
@parameterized.expand(
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airtable/tests/test_airtable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airtable/tests/test_airtable.py
index 8efc0cc47d54..a655ba8ea61b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/airtable/tests/test_airtable.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airtable/tests/test_airtable.py
@@ -1,58 +1,26 @@
-import json
from datetime import UTC, date, datetime
from typing import Any
-from urllib.parse import urlparse
import pytest
-from unittest import mock
-
-from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.airtable.airtable import (
_format_created_time,
- airtable_source,
validate_credentials,
)
-
-# RESTClient builds its session via make_tracked_session in the rest_client module.
-CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
-# validate_credentials builds its own tracked session in the airtable module.
-AIRTABLE_SESSION_PATCH = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.airtable.airtable.make_tracked_session"
+from products.warehouse_sources.backend.temporal.data_imports.sources.airtable.source import AirtableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.airtable import (
+ AirtableSourceConfig,
)
-def _response(body: dict[str, Any]) -> Response:
- resp = Response()
- resp.status_code = 200
- resp._content = json.dumps(body).encode()
- return resp
-
-
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
- """Wire a mock session and capture each request's url + params AT PREPARE time.
-
- ``request.params`` is mutated in place across pages, so snapshot a copy when each request is
- prepared instead of inspecting the shared dict after the run.
- """
- session.headers = {}
- snapshots: list[dict[str, Any]] = []
-
- def _prepare(request: Any) -> mock.MagicMock:
- snapshots.append({"url": request.url, "params": dict(request.params or {})})
- return mock.MagicMock()
-
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = responses
- return snapshots
-
-
-def _rows(source_response) -> list[dict[str, Any]]:
- return [row for page in source_response.items() for row in page]
-
-
-def _source(endpoint: str, **kwargs: Any):
- return airtable_source("pat", endpoint, team_id=1, job_id="j", **kwargs)
+def _driver() -> SourceDriver:
+ return SourceDriver(AirtableSource(), AirtableSourceConfig(personal_access_token="pat"))
class TestFormatCreatedTime:
@@ -65,7 +33,7 @@ class TestFormatCreatedTime:
("2024-01-02T03:04:05.000Z", "2024-01-02T03:04:05.000Z"),
],
)
- def test_format_values(self, value, expected):
+ def test_format_values(self, value: Any, expected: str) -> None:
assert _format_created_time(value) == expected
@@ -79,112 +47,94 @@ class TestValidateCredentials:
(500, False),
],
)
- @mock.patch(AIRTABLE_SESSION_PATCH)
- 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
+ def test_validate_credentials_status_mapping(self, status_code: int, expected: bool) -> None:
+ with scripted_network(always(ScriptedResponse(status=status_code))) as network:
+ assert validate_credentials("pat") is expected
- assert validate_credentials("pat") is expected
+ assert network.requests_log[0].path == "/v0/meta/bases"
+ assert network.requests_log[0].headers["authorization"] == "Bearer pat"
class TestTables:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_fans_out_over_bases_and_injects_base_id(self, MockSession):
- session = MockSession.return_value
- snapshots = _wire(
- session,
+ def test_fans_out_over_bases_and_injects_base_id(self) -> None:
+ result = _driver().run(
+ "tables",
[
- _response({"bases": [{"id": "app1"}, {"id": "app2"}]}),
- _response({"tables": [{"id": "tbl1", "name": "Tasks"}]}),
- _response({"tables": [{"id": "tbl2", "name": "Leads"}]}),
+ ScriptedResponse(json={"bases": [{"id": "app1"}, {"id": "app2"}]}),
+ ScriptedResponse(json={"tables": [{"id": "tbl1", "name": "Tasks"}]}),
+ ScriptedResponse(json={"tables": [{"id": "tbl2", "name": "Leads"}]}),
],
)
- rows = _rows(_source("tables"))
-
- assert [(t["id"], t["_base_id"]) for t in rows] == [("tbl1", "app1"), ("tbl2", "app2")]
+ assert result.raised is None
+ assert [(t["id"], t["_base_id"]) for t in result.rows] == [("tbl1", "app1"), ("tbl2", "app2")]
# No leaked include_from_parent scaffolding key.
- assert all("_bases_id" not in t for t in rows)
- assert urlparse(snapshots[1]["url"]).path == "/v0/meta/bases/app1/tables"
- assert urlparse(snapshots[2]["url"]).path == "/v0/meta/bases/app2/tables"
+ assert all("_bases_id" not in t for t in result.rows)
+ assert result.paths[1:] == ["/v0/meta/bases/app1/tables", "/v0/meta/bases/app2/tables"]
class TestRecords:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_fans_out_over_tables_and_paginates_records(self, MockSession):
- session = MockSession.return_value
- snapshots = _wire(
- session,
+ def test_fans_out_over_tables_and_paginates_records(self) -> None:
+ result = _driver().run(
+ "records",
[
- _response({"bases": [{"id": "app1"}]}),
- _response({"tables": [{"id": "tbl1"}]}),
- _response({"records": [{"id": "rec1", "createdTime": "2024-01-01T00:00:00.000Z"}], "offset": "off1"}),
- _response({"records": [{"id": "rec2", "createdTime": "2024-01-02T00:00:00.000Z"}]}),
+ ScriptedResponse(json={"bases": [{"id": "app1"}]}),
+ ScriptedResponse(json={"tables": [{"id": "tbl1"}]}),
+ ScriptedResponse(
+ json={"records": [{"id": "rec1", "createdTime": "2024-01-01T00:00:00.000Z"}], "offset": "off1"}
+ ),
+ ScriptedResponse(json={"records": [{"id": "rec2", "createdTime": "2024-01-02T00:00:00.000Z"}]}),
],
)
- rows = _rows(_source("records"))
-
- assert [(r["id"], r["_base_id"], r["_table_id"]) for r in rows] == [
+ assert result.raised is None
+ assert [(r["id"], r["_base_id"], r["_table_id"]) for r in result.rows] == [
("rec1", "app1", "tbl1"),
("rec2", "app1", "tbl1"),
]
# No leaked include_from_parent scaffolding keys.
- assert all("_tables__base_id" not in r and "_tables_id" not in r for r in rows)
- assert urlparse(snapshots[2]["url"]).path == "/v0/app1/tbl1"
- assert snapshots[2]["params"]["pageSize"] == 100
- assert snapshots[3]["params"]["offset"] == "off1"
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_incremental_records_filter_on_created_time(self, MockSession):
- session = MockSession.return_value
- snapshots = _wire(
- session,
+ assert all("_tables__base_id" not in r and "_tables_id" not in r for r in result.rows)
+ assert result.paths[2] == "/v0/app1/tbl1"
+ assert result.requests[2].param("pageSize") == "100"
+ assert result.requests[3].param("offset") == "off1"
+
+ def test_incremental_records_filter_on_created_time(self) -> None:
+ result = _driver().run(
+ "records",
[
- _response({"bases": [{"id": "app1"}]}),
- _response({"tables": [{"id": "tbl1"}]}),
- _response({"records": []}),
+ ScriptedResponse(json={"bases": [{"id": "app1"}]}),
+ ScriptedResponse(json={"tables": [{"id": "tbl1"}]}),
+ ScriptedResponse(json={"records": []}),
],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),
)
- _rows(
- _source(
- "records",
- should_use_incremental_field=True,
- db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),
- )
- )
-
- assert snapshots[2]["params"]["filterByFormula"] == 'IS_AFTER(CREATED_TIME(), "2024-01-02T00:00:00.000Z")'
+ assert result.raised is None
+ assert result.requests[2].param("filterByFormula") == 'IS_AFTER(CREATED_TIME(), "2024-01-02T00:00:00.000Z")'
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_full_refresh_sends_no_filter(self, MockSession):
- session = MockSession.return_value
- snapshots = _wire(
- session,
+ def test_full_refresh_sends_no_filter(self) -> None:
+ result = _driver().run(
+ "records",
[
- _response({"bases": [{"id": "app1"}]}),
- _response({"tables": [{"id": "tbl1"}]}),
- _response({"records": []}),
+ ScriptedResponse(json={"bases": [{"id": "app1"}]}),
+ ScriptedResponse(json={"tables": [{"id": "tbl1"}]}),
+ ScriptedResponse(json={"records": []}),
],
)
- _rows(_source("records"))
-
- assert "filterByFormula" not in snapshots[2]["params"]
+ assert result.raised is None
+ assert result.requests[2].param("filterByFormula") is None
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_table_without_id_fails_loudly(self, MockSession):
- session = MockSession.return_value
- _wire(
- session,
+ def test_table_without_id_fails_loudly(self) -> None:
+ result = _driver().run(
+ "records",
[
- _response({"bases": [{"id": "app1"}]}),
- _response({"tables": [{"name": "broken"}]}),
+ ScriptedResponse(json={"bases": [{"id": "app1"}]}),
+ ScriptedResponse(json={"tables": [{"name": "broken"}]}),
],
)
# A table row missing its id can't bind the {table_id} path param — fail loud, don't skip it.
- with pytest.raises(ValueError, match="table_id"):
- _rows(_source("records"))
+ assert isinstance(result.raised, ValueError)
+ assert "table_id" in str(result.raised)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/tests/test_airwallex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/tests/test_airwallex.py
index 8aeddb8120fc..c912e62e7d7a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/tests/test_airwallex.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/tests/test_airwallex.py
@@ -2,8 +2,6 @@ import json
from datetime import UTC, datetime, timedelta
from typing import Any
-from unittest import mock
-
from parameterized import parameterized
from requests import PreparedRequest, Response
from requests.structures import CaseInsensitiveDict
@@ -19,14 +17,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.airwallex.
AirwallexResumeConfig,
_to_iso8601,
_token_lifetime_seconds,
- airwallex_source,
base_url_for,
validate_credentials,
)
-
-CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
-AIRWALLEX_SESSION_PATCH = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.airwallex.airwallex.make_tracked_session"
+from products.warehouse_sources.backend.temporal.data_imports.sources.airwallex.source import AirwallexSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.airwallex import (
+ AirwallexSourceConfig,
)
@@ -50,116 +51,84 @@ def _response(
return resp
-def _login_response(token: str = "tok", expires_at: str | None = None) -> Response:
- resp = Response()
- resp.status_code = 201
+def _login_response(token: str = "tok", expires_at: str | None = None) -> ScriptedResponse:
body: dict[str, Any] = {"token": token}
if expires_at is not None:
body["expires_at"] = expires_at
- resp._content = json.dumps(body).encode()
- return resp
-
-
-def _make_manager(resume_state: AirwallexResumeConfig | None = None) -> mock.MagicMock:
- manager = mock.MagicMock()
- manager.can_resume.return_value = resume_state is not None
- manager.load_state.return_value = resume_state
- return manager
+ return ScriptedResponse(status=201, json=body)
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
- session.headers = {}
- snapshots: list[dict[str, Any]] = []
-
- def _prepare(request: Any) -> mock.MagicMock:
- snapshots.append(dict(request.params or {}))
- prepared = mock.MagicMock()
- prepared.url = request.url
- return prepared
-
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = responses
- return snapshots
-
+def _page(
+ items: list[dict[str, Any]], *, has_more: bool | None = None, page_after: str | None = None
+) -> ScriptedResponse:
+ body: dict[str, Any] = {"items": items}
+ if has_more is not None:
+ body["has_more"] = has_more
+ if page_after is not None:
+ body["page_after"] = page_after
+ return ScriptedResponse(json=body)
-def _rows(source_response: Any) -> list[dict[str, Any]]:
- return [row for page in source_response.items() for row in page]
-
-def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any) -> Any:
- return airwallex_source(
- client_id="cid",
- api_key="key",
- environment="live",
- api_version="2026-07-17",
- endpoint=endpoint,
- team_id=1,
- job_id="j",
- resumable_source_manager=manager,
- **kwargs,
- )
+def _driver() -> SourceDriver:
+ return SourceDriver(AirwallexSource(), AirwallexSourceConfig(client_id="cid", api_key="key", environment="live"))
class TestAirwallexAuth:
- @mock.patch(AIRWALLEX_SESSION_PATCH)
- def test_login_sends_the_credential_headers_and_sets_a_bearer(self, MockSession) -> None:
- session = MockSession.return_value
- session.post.return_value = _login_response("minted")
+ def test_login_sends_the_credential_headers_and_sets_a_bearer(self) -> None:
auth = AirwallexAuth("cid", "key", AIRWALLEX_LIVE_BASE_URL)
request = PreparedRequest()
request.headers = CaseInsensitiveDict()
- auth(request)
+ with scripted_network([_login_response("minted")]) as network:
+ auth(request)
- headers = session.post.call_args.kwargs["headers"]
+ headers = network.requests_log[0].headers
assert headers["x-client-id"] == "cid"
assert headers["x-api-key"] == "key"
+ assert network.requests_log[0].method == "POST"
assert request.headers["Authorization"] == "Bearer minted"
- @mock.patch(AIRWALLEX_SESSION_PATCH)
- def test_login_never_follows_a_redirect(self, MockSession) -> None:
+ def test_login_never_follows_a_redirect(self) -> None:
# The login call carries the API key in a custom header, which requests would replay to a
# redirect target.
- session = MockSession.return_value
- session.post.return_value = _login_response()
-
- AirwallexAuth("cid", "key", AIRWALLEX_LIVE_BASE_URL)._get_token()
+ with scripted_network(
+ [ScriptedResponse(status=302, headers={"Location": "https://example.com/redirect"})]
+ ) as network:
+ try:
+ AirwallexAuth("cid", "key", AIRWALLEX_LIVE_BASE_URL)._get_token()
+ except (AirwallexAuthError, ValueError):
+ pass
- assert session.post.call_args.kwargs["allow_redirects"] is False
+ assert len(network.requests_log) == 1
- @mock.patch(AIRWALLEX_SESSION_PATCH)
- def test_token_is_reused_until_it_nears_expiry(self, MockSession) -> None:
- session = MockSession.return_value
+ def test_token_is_reused_until_it_nears_expiry(self) -> None:
far_future = (datetime.now(UTC) + timedelta(hours=1)).isoformat()
- session.post.return_value = _login_response("minted", far_future)
auth = AirwallexAuth("cid", "key", AIRWALLEX_LIVE_BASE_URL)
- auth._get_token()
- auth._get_token()
+ with scripted_network([_login_response("minted", far_future)]) as network:
+ auth._get_token()
+ auth._get_token()
- assert session.post.call_count == 1
+ assert len(network.requests_log) == 1
- @mock.patch(AIRWALLEX_SESSION_PATCH)
- def test_missing_token_in_a_successful_login_raises(self, MockSession) -> None:
- session = MockSession.return_value
- session.post.return_value = _login_response(token="")
+ def test_missing_token_in_a_successful_login_raises(self) -> None:
+ with scripted_network([_login_response(token="")]):
+ try:
+ AirwallexAuth("cid", "key", AIRWALLEX_LIVE_BASE_URL)._get_token()
+ except AirwallexAuthError:
+ return
+ raise AssertionError("expected AirwallexAuthError")
- try:
- AirwallexAuth("cid", "key", AIRWALLEX_LIVE_BASE_URL)._get_token()
- except AirwallexAuthError:
- return
- raise AssertionError("expected AirwallexAuthError")
-
- @mock.patch(AIRWALLEX_SESSION_PATCH)
- def test_secret_values_cover_the_key_and_the_minted_token(self, MockSession) -> None:
+ def test_secret_values_cover_the_key_and_the_minted_token(self) -> None:
# Both must be redacted from logged URLs, headers, sampled bodies, and raised errors.
- session = MockSession.return_value
- session.post.return_value = _login_response("minted")
auth = AirwallexAuth("cid", "key", AIRWALLEX_LIVE_BASE_URL)
assert auth.secret_values() == ("key",)
- auth._get_token()
+ with scripted_network([_login_response("minted")]) as network:
+ auth._get_token()
assert set(auth.secret_values()) == {"key", "minted"}
+ assert network.session_options[0]["redact_values"] == ("key",)
+ assert network.session_options[0]["capture"] is False
@parameterized.expand(
[
@@ -208,52 +177,43 @@ class TestAirwallexTransport:
("Invoices", "from_created_at"),
]
)
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_incremental_uses_the_endpoints_own_filter_name(self, endpoint: str, param: str, MockSession) -> None:
+ def test_incremental_uses_the_endpoints_own_filter_name(self, endpoint: str, param: str) -> None:
# Airwallex names this filter differently per endpoint, and sends 200 while ignoring a name
# it does not know, so a wrong name silently full-scans every run.
- session = MockSession.return_value
- params = _wire(session, [_response([{"id": "1"}], has_more=False)])
-
- _rows(
- _source(
- endpoint,
- _make_manager(),
- should_use_incremental_field=True,
- db_incremental_field_last_value=datetime(2021, 1, 1, tzinfo=UTC),
- )
+ result = _driver().run(
+ endpoint,
+ [_login_response(), _page([{"id": "1"}], has_more=False)],
+ incremental_field="settled_at" if endpoint == "Settlements" else "created_at",
+ db_incremental_field_last_value=datetime(2021, 1, 1, tzinfo=UTC),
)
- assert params[0][param] == "2021-01-01T00:00:00Z"
+ assert result.raised is None
+ assert result.requests[1].param(param) == "2021-01-01T00:00:00Z"
@parameterized.expand([("PaymentIntents",), ("Customers",)])
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_drops_client_secret(self, endpoint: str, MockSession) -> None:
+ def test_drops_client_secret(self, endpoint: str) -> None:
# A still-valid client_secret authorizes a browser/app against Airwallex; it must never be
# persisted to the warehouse.
- session = MockSession.return_value
- _wire(session, [_response([{"id": "1", "client_secret": "live_secret"}], has_more=False)])
-
- rows = _rows(_source(endpoint, _make_manager()))
+ result = _driver().run(
+ endpoint, [_login_response(), _page([{"id": "1", "client_secret": "live_secret"}], has_more=False)]
+ )
- assert rows == [{"id": "1"}]
+ assert result.raised is None
+ assert result.rows == [{"id": "1"}]
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_cursor_walk_sends_page_after_as_page(self, MockSession) -> None:
- session = MockSession.return_value
- params = _wire(
- session,
+ def test_cursor_walk_sends_page_after_as_page(self) -> None:
+ result = _driver().run(
+ "Transfers",
[
- _response([{"id": "1"}], page_after="cur1"),
- _response([{"id": "2"}]),
+ _login_response(),
+ _page([{"id": "1"}], page_after="cur1"),
+ _page([{"id": "2"}]),
],
)
- rows = _rows(_source("Transfers", _make_manager()))
-
- assert [row["id"] for row in rows] == ["1", "2"]
- assert "page" not in params[0]
- assert params[1]["page"] == "cur1"
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == ["1", "2"]
+ assert result.params("page") == [None, None, "cur1"]
def test_page_number_paginator_stops_at_the_api_cap(self) -> None:
# page_num is capped at 2000; walking past it would request pages the API rejects.
@@ -270,41 +230,36 @@ class TestAirwallexTransport:
assert paginator.has_next_page is False
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_page_number_resume_seeds_the_page(self, MockSession) -> None:
- session = MockSession.return_value
- params = _wire(session, [_response([{"id": "1"}], has_more=False)])
-
- _rows(_source("FinancialTransactions", _make_manager(AirwallexResumeConfig(page_num=7))))
-
- assert params[0]["page_num"] == 7
+ def test_page_number_resume_seeds_the_page(self) -> None:
+ result = _driver().run(
+ "FinancialTransactions",
+ [_login_response(), _page([{"id": "1"}], has_more=False)],
+ resume_state=AirwallexResumeConfig(page_num=7),
+ )
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_cursor_resume_seeds_the_cursor(self, MockSession) -> None:
- session = MockSession.return_value
- params = _wire(session, [_response([{"id": "1"}])])
+ assert result.raised is None
+ assert result.params("page_num") == [None, "7"]
- _rows(_source("Transfers", _make_manager(AirwallexResumeConfig(cursor="saved"))))
+ def test_cursor_resume_seeds_the_cursor(self) -> None:
+ result = _driver().run(
+ "Transfers", [_login_response(), _page([{"id": "1"}])], resume_state=AirwallexResumeConfig(cursor="saved")
+ )
- assert params[0]["page"] == "saved"
+ assert result.raised is None
+ assert result.params("page") == [None, "saved"]
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_checkpoints_save_the_field_matching_the_pagination_style(self, MockSession) -> None:
- session = MockSession.return_value
- _wire(
- session,
+ def test_checkpoints_save_the_field_matching_the_pagination_style(self) -> None:
+ result = _driver().run(
+ "FinancialTransactions",
[
- _response([{"id": "1"}], has_more=True),
- _response([{"id": "2"}], has_more=False),
+ _login_response(),
+ _page([{"id": "1"}], has_more=True),
+ _page([{"id": "2"}], has_more=False),
],
)
- manager = _make_manager()
- _rows(_source("FinancialTransactions", manager))
-
- saved = [c.args[0] for c in manager.save_state.call_args_list]
- assert [s.page_num for s in saved] == [1]
- assert all(s.cursor is None for s in saved)
+ assert result.raised is None
+ assert result.saved_states == [AirwallexResumeConfig(page_num=1)]
@parameterized.expand(
[
@@ -313,33 +268,26 @@ class TestAirwallexTransport:
("Invoices", ["id"], "created_at"),
]
)
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_primary_key_and_partition_key(self, endpoint: str, keys: list[str], partition: str, MockSession) -> None:
+ def test_primary_key_and_partition_key(self, endpoint: str, keys: list[str], partition: str) -> None:
# Settlements is the one endpoint with no `id` field. A wrong key seeds duplicate rows that
# every later merge multi-matches.
- session = MockSession.return_value
- _wire(session, [_response([], has_more=False)])
-
- result = _source(endpoint, _make_manager())
+ result = _driver().run(endpoint, [_login_response(), _page([], has_more=False)])
- assert result.primary_keys == keys
- assert result.partition_keys == [partition]
+ assert result.raised is None
+ assert result.response is not None
+ assert result.response.primary_keys == keys
+ assert result.response.partition_keys == [partition]
class TestValidateCredentials:
- @mock.patch(AIRWALLEX_SESSION_PATCH)
- def test_valid_credentials_mint_a_token(self, MockSession) -> None:
- MockSession.return_value.post.return_value = _login_response("minted")
-
- assert validate_credentials("cid", "key", "live") == (True, None)
-
- @mock.patch(AIRWALLEX_SESSION_PATCH)
- def test_a_rejected_login_returns_a_message_rather_than_raising(self, MockSession) -> None:
- resp = Response()
- resp.status_code = 401
- MockSession.return_value.post.return_value = resp
-
- ok, message = validate_credentials("cid", "key", "live")
+ def test_valid_credentials_mint_a_token(self) -> None:
+ with scripted_network([_login_response("minted")]) as network:
+ assert validate_credentials("cid", "key", "live") == (True, None)
+ assert network.requests_log[0].path == "/api/v1/authentication/login"
+
+ def test_a_rejected_login_returns_a_message_rather_than_raising(self) -> None:
+ with scripted_network([ScriptedResponse(status=401)]):
+ ok, message = validate_credentials("cid", "key", "live")
assert ok is False
assert message is not None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/tests/test_airwallex_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/tests/test_airwallex_source.py
index 0979cee2266f..97d2651cde07 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/tests/test_airwallex_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airwallex/tests/test_airwallex_source.py
@@ -1,39 +1,18 @@
-from typing import Any
-
-from unittest import mock
-
from parameterized import parameterized
from products.warehouse_sources.backend.facade.source_config import SourceFieldInputConfig, SourceFieldInputConfigType
from products.warehouse_sources.backend.temporal.data_imports.sources.airwallex.source import AirwallexSource
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
-
-SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.airwallex.source"
-
-
-class _Config:
- client_id = "cid"
- api_key = "key"
- environment = "live"
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.airwallex import (
+ AirwallexSourceConfig,
+)
-def _inputs(**overrides: Any) -> SourceInputs:
- defaults: dict[str, Any] = {
- "schema_name": "FinancialTransactions",
- "schema_id": "schema-1",
- "source_id": "source-1",
- "team_id": 1,
- "should_use_incremental_field": False,
- "db_incremental_field_last_value": None,
- "db_incremental_field_earliest_value": None,
- "incremental_field": None,
- "incremental_field_type": None,
- "job_id": "job-1",
- "logger": mock.MagicMock(),
- "reset_pipeline": False,
- }
- defaults.update(overrides)
- return SourceInputs(**defaults)
+def _driver() -> SourceDriver:
+ return SourceDriver(AirwallexSource(), AirwallexSourceConfig(client_id="cid", api_key="key", environment="live"))
class TestAirwallexSource:
@@ -54,28 +33,30 @@ class TestAirwallexSource:
assert schemas[endpoint].supports_incremental is True
assert [f["field"] for f in schemas[endpoint].incremental_fields] == [expected]
- @mock.patch(f"{SOURCE_MODULE}.airwallex_source")
- def test_source_for_pipeline_passes_the_watermark_when_incremental(self, mock_source) -> None:
- inputs = _inputs(should_use_incremental_field=True, db_incremental_field_last_value=123)
+ def test_source_for_pipeline_passes_the_watermark_when_incremental(self) -> None:
+ result = _driver().run(
+ "FinancialTransactions",
+ [ScriptedResponse(status=201, json={"token": "tok"}), ScriptedResponse(json={"items": []})],
+ incremental_field="created_at",
+ db_incremental_field_last_value=123,
+ )
- AirwallexSource().source_for_pipeline(_Config(), mock.MagicMock(), inputs) # type: ignore[arg-type]
-
- kwargs = mock_source.call_args.kwargs
- assert kwargs["endpoint"] == "FinancialTransactions"
- assert kwargs["db_incremental_field_last_value"] == 123
- assert kwargs["environment"] == "live"
+ assert result.raised is None
+ assert result.paths == ["/api/v1/authentication/login", "/api/v1/financial_transactions"]
+ assert result.requests[1].param("from_created_at") == "1970-01-01T00:02:03Z"
+ assert result.requests[1].origin == "https://api.airwallex.com"
@parameterized.expand([("stored_pin_wins", "2025-06-30", "2025-06-30"), ("no_pin_defaults", None, "2026-07-17")])
- @mock.patch(f"{SOURCE_MODULE}.airwallex_source")
- def test_source_for_pipeline_resolves_the_api_version(
- self, _name: str, pinned: str | None, expected: str, mock_source
- ) -> None:
+ def test_source_for_pipeline_resolves_the_api_version(self, _name: str, pinned: str | None, expected: str) -> None:
# A source created against an older version must keep calling that version.
- inputs = _inputs(api_version=pinned)
-
- AirwallexSource().source_for_pipeline(_Config(), mock.MagicMock(), inputs) # type: ignore[arg-type]
-
- assert mock_source.call_args.kwargs["api_version"] == expected
+ result = _driver().run(
+ "FinancialTransactions",
+ [ScriptedResponse(status=201, json={"token": "tok"}), ScriptedResponse(json={"items": []})],
+ api_version=pinned,
+ )
+
+ assert result.raised is None
+ assert result.requests[1].headers["x-api-version"] == expected
def test_the_api_key_field_is_marked_secret(self) -> None:
# A non-secret credential field is stored and returned in the clear by the serializer.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/tests/test_aiven.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/tests/test_aiven.py
index a5a606df8476..8b1b1d66be00 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/tests/test_aiven.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/tests/test_aiven.py
@@ -1,62 +1,23 @@
-import json
-from collections.abc import Iterable
-from typing import Any, cast
-
-import pytest
-from unittest.mock import MagicMock, patch
+from typing import Any
import requests
from parameterized import parameterized
-from products.warehouse_sources.backend.temporal.data_imports.sources.aiven.aiven import (
- AIVEN_BASE_URL,
- aiven_source,
- validate_credentials,
-)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aiven.aiven import validate_credentials
from products.warehouse_sources.backend.temporal.data_imports.sources.aiven.settings import AIVEN_ENDPOINTS
-
-# RESTClient builds its session via make_tracked_session in the rest_client module.
-CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
-# validate_credentials builds its own tracked session in the aiven module.
-AIVEN_SESSION_PATCH = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.aiven.aiven.make_tracked_session"
+from products.warehouse_sources.backend.temporal.data_imports.sources.aiven.source import AivenSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ route,
+ scripted_network,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.aiven import AivenSourceConfig
-def _response(status_code: int, body: Any) -> requests.Response:
- resp = requests.Response()
- resp.status_code = status_code
- resp._content = json.dumps(body).encode()
- return resp
-
-
-def _wire(session: MagicMock, responses_by_path: dict[str, requests.Response]) -> list[str]:
- """Wire a mock session that dispatches each request to a response by its (formatted) path.
-
- Fan-out issues one request per parent row in a deterministic order, but keying by path keeps the
- test robust to ordering. Returns the list of paths requested, in call order.
- """
- session.headers = {}
- requested_paths: list[str] = []
-
- def _prepare(request: Any) -> MagicMock:
- prepared = MagicMock()
- prepared.url = request.url
- return prepared
-
- def _send(prepared: Any, **kwargs: Any) -> requests.Response:
- path = prepared.url.replace(AIVEN_BASE_URL, "")
- requested_paths.append(path)
- return responses_by_path[path]
-
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = _send
- return requested_paths
-
-
-def _rows(endpoint: str) -> list[dict[str, Any]]:
- response = aiven_source("tok", endpoint, team_id=1, job_id="j")
- return [row for page in cast("Iterable[Any]", response.items()) for row in page]
+def _driver() -> SourceDriver:
+ return SourceDriver(AivenSource(), AivenSourceConfig.from_dict({"api_token": "tok"}))
class TestListExtraction:
@@ -68,132 +29,155 @@ class TestListExtraction:
("empty_list", {"projects": []}, []),
]
)
- @patch(CLIENT_SESSION_PATCH)
def test_extracts_rows_under_data_key(
- self, _name: str, body: dict[str, Any], expected: list, MockSession: MagicMock
+ self, _name: str, body: dict[str, Any], expected: list[dict[str, Any]]
) -> None:
- session = MockSession.return_value
- _wire(session, {"/project": _response(200, body)})
- assert _rows("projects") == expected
+ result = _driver().run("projects", [ScriptedResponse(json=body)])
+
+ assert result.raised is None
+ assert result.paths == ["/v1/project"]
+ assert result.rows == expected
class TestFanOut:
- @patch(CLIENT_SESSION_PATCH)
- def test_fan_out_project_injects_parent_project_name(self, MockSession: MagicMock) -> None:
+ def test_fan_out_project_injects_parent_project_name(self) -> None:
# `services` items carry no project field, so the parent's `project_name` must be injected
# to keep the composite primary key unique across projects.
- session = MockSession.return_value
- _wire(
- session,
- {
- "/project": _response(200, {"projects": [{"project_name": "p1"}, {"project_name": "p2"}]}),
- "/project/p1/service": _response(200, {"services": [{"service_name": "s1"}]}),
- "/project/p2/service": _response(200, {"services": [{"service_name": "s2"}]}),
- },
+ result = _driver().run(
+ "services",
+ route(
+ {
+ "/project": [ScriptedResponse(json={"projects": [{"project_name": "p1"}, {"project_name": "p2"}]})],
+ "/project/p1/service": [ScriptedResponse(json={"services": [{"service_name": "s1"}]})],
+ "/project/p2/service": [ScriptedResponse(json={"services": [{"service_name": "s2"}]})],
+ }
+ ),
)
- assert _rows("services") == [
+
+ assert result.raised is None
+ assert result.rows == [
{"service_name": "s1", "project_name": "p1"},
{"service_name": "s2", "project_name": "p2"},
]
- @patch(CLIENT_SESSION_PATCH)
- def test_fan_out_organization_injects_org(self, MockSession: MagicMock) -> None:
- session = MockSession.return_value
- _wire(
- session,
- {
- "/organizations": _response(200, {"organizations": [{"organization_id": "org1"}]}),
- "/organization/org1/user": _response(200, {"users": [{"user_id": "u1"}]}),
- },
+ def test_fan_out_organization_injects_org(self) -> None:
+ result = _driver().run(
+ "organization_users",
+ route(
+ {
+ "/organizations": [ScriptedResponse(json={"organizations": [{"organization_id": "org1"}]})],
+ "/organization/org1/user": [ScriptedResponse(json={"users": [{"user_id": "u1"}]})],
+ }
+ ),
)
- assert _rows("organization_users") == [{"user_id": "u1", "organization_id": "org1"}]
- @patch(CLIENT_SESSION_PATCH)
- def test_fan_out_organization_setdefault_keeps_existing_org_id(self, MockSession: MagicMock) -> None:
+ assert result.raised is None
+ assert result.rows == [{"user_id": "u1", "organization_id": "org1"}]
+
+ def test_fan_out_organization_setdefault_keeps_existing_org_id(self) -> None:
# billing_groups already carry organization_id; injection must not clobber it.
- session = MockSession.return_value
- _wire(
- session,
- {
- "/organizations": _response(200, {"organizations": [{"organization_id": "org1"}]}),
- "/organization/org1/billing-groups": _response(
- 200, {"billing_groups": [{"billing_group_id": "bg1", "organization_id": "org-real"}]}
- ),
- },
+ result = _driver().run(
+ "billing_groups",
+ route(
+ {
+ "/organizations": [ScriptedResponse(json={"organizations": [{"organization_id": "org1"}]})],
+ "/organization/org1/billing-groups": [
+ ScriptedResponse(
+ json={"billing_groups": [{"billing_group_id": "bg1", "organization_id": "org-real"}]}
+ )
+ ],
+ }
+ ),
)
- rows = _rows("billing_groups")
- assert rows == [{"billing_group_id": "bg1", "organization_id": "org-real"}]
-
- @patch(CLIENT_SESSION_PATCH)
- def test_fan_out_invoice_two_levels_injects_org_and_invoice(self, MockSession: MagicMock) -> None:
- session = MockSession.return_value
- _wire(
- session,
- {
- "/organizations": _response(200, {"organizations": [{"organization_id": "org1"}]}),
- "/organization/org1/invoices": _response(
- 200, {"invoices": [{"invoice_number": "inv1"}, {"invoice_number": "inv2"}]}
- ),
- "/organization/org1/invoice/inv1/lines": _response(200, {"lines": [{"line_type": "usage"}]}),
- "/organization/org1/invoice/inv2/lines": _response(200, {"lines": [{"line_type": "credit"}]}),
- },
+
+ assert result.raised is None
+ assert result.rows == [{"billing_group_id": "bg1", "organization_id": "org-real"}]
+
+ def test_fan_out_invoice_two_levels_injects_org_and_invoice(self) -> None:
+ result = _driver().run(
+ "invoice_lines",
+ route(
+ {
+ "/organizations": [ScriptedResponse(json={"organizations": [{"organization_id": "org1"}]})],
+ "/organization/org1/invoices": [
+ ScriptedResponse(json={"invoices": [{"invoice_number": "inv1"}, {"invoice_number": "inv2"}]})
+ ],
+ "/organization/org1/invoice/inv1/lines": [
+ ScriptedResponse(json={"lines": [{"line_type": "usage"}]})
+ ],
+ "/organization/org1/invoice/inv2/lines": [
+ ScriptedResponse(json={"lines": [{"line_type": "credit"}]})
+ ],
+ }
+ ),
)
- assert _rows("invoice_lines") == [
+
+ assert result.raised is None
+ assert result.rows == [
{"line_type": "usage", "organization_id": "org1", "invoice_number": "inv1"},
{"line_type": "credit", "organization_id": "org1", "invoice_number": "inv2"},
]
- @patch(CLIENT_SESSION_PATCH)
- def test_two_level_injects_both_org_and_group(self, MockSession: MagicMock) -> None:
+ def test_two_level_injects_both_org_and_group(self) -> None:
# user_group_members fans out organization -> user-groups -> members; the child rows carry
# neither id, so both must be injected to keep the composite key unique table-wide.
- session = MockSession.return_value
- _wire(
- session,
- {
- "/organizations": _response(200, {"organizations": [{"organization_id": "org1"}]}),
- "/organization/org1/user-groups": _response(200, {"user_groups": [{"user_group_id": "g1"}]}),
- "/organization/org1/user-groups/g1/members": _response(200, {"members": [{"user_id": "u1"}]}),
- },
+ result = _driver().run(
+ "user_group_members",
+ route(
+ {
+ "/organizations": [ScriptedResponse(json={"organizations": [{"organization_id": "org1"}]})],
+ "/organization/org1/user-groups": [
+ ScriptedResponse(json={"user_groups": [{"user_group_id": "g1"}]})
+ ],
+ "/organization/org1/user-groups/g1/members": [
+ ScriptedResponse(json={"members": [{"user_id": "u1"}]})
+ ],
+ }
+ ),
)
- assert _rows("user_group_members") == [
- {"user_id": "u1", "organization_id": "org1", "user_group_id": "g1"},
- ]
- @patch(CLIENT_SESSION_PATCH)
- def test_two_level_single_placeholder_injects_only_declared_param(self, MockSession: MagicMock) -> None:
+ assert result.raised is None
+ assert result.rows == [{"user_id": "u1", "organization_id": "org1", "user_group_id": "g1"}]
+
+ def test_two_level_single_placeholder_injects_only_declared_param(self) -> None:
# billing_group_projects binds only {billing_group_id}, so only that id is injected — the
# grandparent organization_id must not leak onto the row.
- session = MockSession.return_value
- _wire(
- session,
- {
- "/organizations": _response(200, {"organizations": [{"organization_id": "org1"}]}),
- "/organization/org1/billing-groups": _response(200, {"billing_groups": [{"billing_group_id": "bg1"}]}),
- "/billing-group/bg1/projects": _response(200, {"projects": [{"project_name": "p1"}]}),
- },
+ result = _driver().run(
+ "billing_group_projects",
+ route(
+ {
+ "/organizations": [ScriptedResponse(json={"organizations": [{"organization_id": "org1"}]})],
+ "/organization/org1/billing-groups": [
+ ScriptedResponse(json={"billing_groups": [{"billing_group_id": "bg1"}]})
+ ],
+ "/billing-group/bg1/projects": [ScriptedResponse(json={"projects": [{"project_name": "p1"}]})],
+ }
+ ),
)
- assert _rows("billing_group_projects") == [{"project_name": "p1", "billing_group_id": "bg1"}]
+
+ assert result.raised is None
+ assert result.rows == [{"project_name": "p1", "billing_group_id": "bg1"}]
class TestFailLoud:
@parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
- @patch(CLIENT_SESSION_PATCH)
- def test_client_errors_surface(self, _name: str, status: int, MockSession: MagicMock) -> None:
+ def test_client_errors_surface(self, _name: str, status: int) -> None:
# A 4xx is non-retryable and must fail the sync loudly rather than syncing 0 rows silently.
- session = MockSession.return_value
- _wire(session, {"/project": _response(status, {"message": "nope"})})
- with pytest.raises(requests.HTTPError):
- _rows("projects")
+ result = _driver().run("projects", [ScriptedResponse(status=status, json={"message": "nope"})])
+
+ assert isinstance(result.raised, requests.HTTPError)
+ assert result.rows == []
class TestSourceResponse:
@parameterized.expand(list(AIVEN_ENDPOINTS.keys()))
- @patch(CLIENT_SESSION_PATCH)
- def test_source_response_matches_endpoint_settings(self, endpoint: str, MockSession: MagicMock) -> None:
+ def test_source_response_matches_endpoint_settings(self, endpoint: str) -> None:
config = AIVEN_ENDPOINTS[endpoint]
- response = aiven_source("tok", endpoint, team_id=1, job_id="j")
+ result = _driver().run(endpoint, always(ScriptedResponse(json={})))
+ response = result.response
+ assert result.raised is None
+ assert response is not None
assert response.name == endpoint
assert response.primary_keys == config.primary_keys
if config.partition_key:
@@ -207,7 +191,10 @@ class TestSourceResponse:
class TestValidateCredentials:
@parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("server_error", 500, False)])
- @patch(AIVEN_SESSION_PATCH)
- def test_maps_status_to_bool(self, _name: str, status: int, expected: bool, mock_session: MagicMock) -> None:
- mock_session.return_value.get.return_value = MagicMock(status_code=status)
- assert validate_credentials("tok") is expected
+ def test_maps_status_to_bool(self, _name: str, status: int, expected: bool) -> None:
+ with scripted_network(always(ScriptedResponse(status=status))) as network:
+ assert validate_credentials("tok") is expected
+
+ # The real stack retries a 5xx, so the count of requests is not fixed.
+ assert {request.path for request in network.requests_log} == {"/v1/me"}
+ assert network.requests_log[0].headers["authorization"] == "aivenv1 tok"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/tests/test_aiven_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/tests/test_aiven_source.py
index f593a03c1140..1331e3dbf5e9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/tests/test_aiven_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/tests/test_aiven_source.py
@@ -1,9 +1,10 @@
-from unittest.mock import patch
-
from parameterized import parameterized
-from products.warehouse_sources.backend.temporal.data_imports.sources.aiven import source as source_module
from products.warehouse_sources.backend.temporal.data_imports.sources.aiven.source import AivenSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ scripted_network,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.aiven import AivenSourceConfig
@@ -12,9 +13,11 @@ def _config() -> AivenSourceConfig:
class TestValidateCredentials:
- @parameterized.expand([("valid", True, True), ("invalid", False, False)])
- def test_maps_validation_result(self, _name: str, valid: bool, expected: bool) -> None:
- with patch.object(source_module, "validate_aiven_credentials", return_value=valid):
+ @parameterized.expand([("valid", 200, True), ("invalid", 401, False)])
+ def test_maps_validation_result(self, _name: str, status: int, expected: bool) -> None:
+ with scripted_network([ScriptedResponse(status=status)]) as network:
ok, error = AivenSource().validate_credentials(_config(), team_id=1)
+
assert ok is expected
assert (error is None) is expected
+ assert [request.path for request in network.requests_log] == ["/v1/me"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia.py b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia.py
index 0eb1e0d226ac..f81e584e5b4e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia.py
@@ -1,13 +1,10 @@
-import json
import dataclasses
from datetime import UTC, date, datetime
from typing import Any
import pytest
-from unittest import mock
import requests
-from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.algolia.algolia import (
AlgoliaResumeConfig,
@@ -15,86 +12,23 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.algolia.al
_base_url,
_endpoint_url,
_to_start_date,
- algolia_source,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.algolia.settings import ALGOLIA_ENDPOINTS
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
-
-# RESTClient builds its session via make_tracked_session in the rest_client module.
-CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
-# validate_credentials builds its own tracked session in the algolia module.
-ALGOLIA_SESSION_PATCH = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.algolia.algolia.make_tracked_session"
+from products.warehouse_sources.backend.temporal.data_imports.sources.algolia.source import AlgoliaSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.algolia import (
+ AlgoliaSourceConfig,
)
-def _response(body: dict[str, Any], status_code: int = 200) -> Response:
- resp = Response()
- resp.status_code = status_code
- resp._content = json.dumps(body).encode()
- return resp
-
-
-def _make_manager(resume_state: AlgoliaResumeConfig | None = None) -> mock.MagicMock:
- manager = mock.MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = resume_state is not None
- manager.load_state.return_value = resume_state
- return manager
-
-
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
- """Wire a mock session and return a list that captures each request AT PREPARE TIME.
-
- ``request.params`` / ``request.json`` are single dicts mutated in place across pages, so
- inspecting them after the run shows only the final state — snapshot copies when each request
- is prepared instead.
- """
- session.headers = {}
- snapshots: list[dict[str, Any]] = []
-
- def _prepare(request: Any) -> mock.MagicMock:
- snapshots.append(
- {
- "method": request.method,
- "url": request.url,
- "params": dict(request.params or {}),
- "json": dict(request.json) if request.json is not None else None,
- }
- )
- return mock.MagicMock()
-
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = responses
- return snapshots
-
-
-def _build(
- endpoint: str,
- manager: mock.MagicMock,
- index_name: str | None = "idx",
- region: str = "us",
- should_use_incremental_field: bool = False,
- db_incremental_field_last_value: Any = None,
- incremental_field: str | None = None,
-) -> Any:
- return algolia_source(
- endpoint=endpoint,
- application_id="APP",
- api_key="key",
- index_name=index_name,
- team_id=1,
- job_id="job",
- manager=manager,
- region=region,
- should_use_incremental_field=should_use_incremental_field,
- db_incremental_field_last_value=db_incremental_field_last_value,
- incremental_field=incremental_field,
- )
-
-
-def _rows(source_response: Any) -> list[dict[str, Any]]:
- return [row for page in source_response.items() for row in page]
+def _driver() -> SourceDriver:
+ return SourceDriver(AlgoliaSource(), AlgoliaSourceConfig(application_id="APP", api_key="key", index_name="idx"))
class TestBaseUrl:
@@ -117,141 +51,123 @@ class TestEndpointUrl:
class TestCursorPagination:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_pages_until_cursor_absent(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- manager = _make_manager()
- calls = _wire(
- session,
+ def test_pages_until_cursor_absent(self) -> None:
+ result = _driver().run(
+ "records",
[
- _response({"hits": [{"objectID": "1"}], "cursor": "c1"}),
- _response({"hits": [{"objectID": "2"}]}),
+ ScriptedResponse(json={"hits": [{"objectID": "1"}], "cursor": "c1"}),
+ ScriptedResponse(json={"hits": [{"objectID": "2"}]}),
],
)
- rows = _rows(_build("records", manager))
-
- assert [r["objectID"] for r in rows] == ["1", "2"]
- assert [c["method"] for c in calls] == ["POST", "POST"]
- assert calls[0]["url"] == "https://APP.algolia.net/1/indexes/idx/browse"
+ assert result.raised is None
+ assert [row["objectID"] for row in result.rows] == ["1", "2"]
+ assert [request.method for request in result.requests] == ["POST", "POST"]
+ assert result.urls[0].lower() == "https://app.algolia.net/1/indexes/idx/browse"
# First browse request carries no cursor; the second carries the cursor returned first.
- assert calls[0]["json"] == {"hitsPerPage": 1000}
- assert calls[1]["json"] == {"hitsPerPage": 1000, "cursor": "c1"}
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_resume_seeds_cursor(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- manager = _make_manager(AlgoliaResumeConfig(cursor="resumed"))
- calls = _wire(session, [_response({"hits": [{"objectID": "x"}]})])
-
- _rows(_build("records", manager))
+ assert result.requests[0].json() == {"hitsPerPage": 1000}
+ assert result.requests[1].json() == {"hitsPerPage": 1000, "cursor": "c1"}
+
+ def test_resume_seeds_cursor(self) -> None:
+ result = _driver().run(
+ "records",
+ [ScriptedResponse(json={"hits": [{"objectID": "x"}]})],
+ resume_state=AlgoliaResumeConfig(cursor="resumed"),
+ )
- assert calls[0]["json"] == {"hitsPerPage": 1000, "cursor": "resumed"}
+ assert result.raised is None
+ assert result.requests[0].json() == {"hitsPerPage": 1000, "cursor": "resumed"}
class TestPagePagination:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_search_endpoint_stops_on_short_page(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- manager = _make_manager()
+ def test_search_endpoint_stops_on_short_page(self) -> None:
# Fewer rows than the requested page size signals the last page for search endpoints.
- calls = _wire(session, [_response({"hits": [{"objectID": "s1"}], "nbHits": 1})])
+ result = _driver().run("synonyms", [ScriptedResponse(json={"hits": [{"objectID": "s1"}], "nbHits": 1})])
- rows = _rows(_build("synonyms", manager))
+ assert result.raised is None
+ assert [row["objectID"] for row in result.rows] == ["s1"]
+ assert len(result.requests) == 1
+ assert result.saved_states == []
- assert [r["objectID"] for r in rows] == ["s1"]
- assert len(calls) == 1
- manager.save_state.assert_not_called()
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_indices_uses_nb_pages_to_terminate(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- manager = _make_manager()
- calls = _wire(
- session,
+ def test_indices_uses_nb_pages_to_terminate(self) -> None:
+ result = _driver().run(
+ "indices",
[
- _response({"items": [{"name": "i1"}], "nbPages": 2}),
- _response({"items": [{"name": "i2"}], "nbPages": 2}),
+ ScriptedResponse(json={"items": [{"name": "i1"}], "nbPages": 2}),
+ ScriptedResponse(json={"items": [{"name": "i2"}], "nbPages": 2}),
],
)
- rows = _rows(_build("indices", manager, index_name=None))
-
- assert [r["name"] for r in rows] == ["i1", "i2"]
- assert len(calls) == 2
+ assert result.raised is None
+ assert [row["name"] for row in result.rows] == ["i1", "i2"]
+ assert len(result.requests) == 2
# GET endpoints page via query params, and must request the configured page size so the
# listing doesn't fall back to Algolia's small server-side default.
- assert [c["method"] for c in calls] == ["GET", "GET"]
- assert [c["params"]["page"] for c in calls] == [0, 1]
- assert all(c["params"]["hitsPerPage"] == ALGOLIA_ENDPOINTS["indices"].page_size for c in calls)
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_resume_seeds_page(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- manager = _make_manager(AlgoliaResumeConfig(page=3))
- calls = _wire(session, [_response({"items": [{"name": "i"}], "nbPages": 4})])
-
- _rows(_build("indices", manager, index_name=None))
+ assert [request.method for request in result.requests] == ["GET", "GET"]
+ assert result.params("page") == ["0", "1"]
+ assert result.params("hitsPerPage") == ["1000", "1000"]
+
+ def test_resume_seeds_page(self) -> None:
+ result = _driver().run(
+ "indices",
+ [ScriptedResponse(json={"items": [{"name": "i"}], "nbPages": 4})],
+ resume_state=AlgoliaResumeConfig(page=3),
+ )
- assert calls[0]["params"]["page"] == 3
+ assert result.raised is None
+ assert result.params("page") == ["3"]
class TestOffsetPagination:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_abtests_terminates_on_total_and_omits_index(
- self, MockSession: mock.MagicMock, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- session = MockSession.return_value
- manager = _make_manager()
+ def test_abtests_terminates_on_total_and_omits_index(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setitem(
ALGOLIA_ENDPOINTS, "ab_tests", dataclasses.replace(ALGOLIA_ENDPOINTS["ab_tests"], page_size=1)
)
- calls = _wire(
- session,
+ result = _driver().run(
+ "ab_tests",
[
- _response({"abtests": [{"abTestID": 1}], "total": 2}),
- _response({"abtests": [{"abTestID": 2}], "total": 2}),
+ ScriptedResponse(json={"abtests": [{"abTestID": 1}], "total": 2}),
+ ScriptedResponse(json={"abtests": [{"abTestID": 2}], "total": 2}),
],
)
- rows = _rows(_build("ab_tests", manager, index_name=None))
-
- assert [r["abTestID"] for r in rows] == [1, 2]
+ assert result.raised is None
+ assert [row["abTestID"] for row in result.rows] == [1, 2]
# A/B tests are application-level, so no index param is sent; the `total` field stops paging.
- assert "index" not in calls[0]["params"]
- assert [c["params"]["offset"] for c in calls] == [0, 1]
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_resume_seeds_offset(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- manager = _make_manager(AlgoliaResumeConfig(offset=5))
- calls = _wire(session, [_response({"searches": []})])
-
- _rows(_build("top_searches", manager))
+ assert result.requests[0].param("index") is None
+ assert result.params("offset") == ["0", "1"]
+
+ def test_resume_seeds_offset(self) -> None:
+ result = _driver().run(
+ "top_searches",
+ [ScriptedResponse(json={"searches": []})],
+ resume_state=AlgoliaResumeConfig(offset=5),
+ )
- assert calls[0]["params"]["offset"] == 5
+ assert result.raised is None
+ assert result.params("offset") == ["5"]
class TestAlgoliaSourceResponse:
@pytest.mark.parametrize("endpoint", list(ALGOLIA_ENDPOINTS.keys()))
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_primary_keys_match_settings(self, MockSession: mock.MagicMock, endpoint: str) -> None:
- MockSession.return_value.headers = {}
- response = _build(endpoint, _make_manager())
- assert response.name == endpoint
- assert response.primary_keys == ALGOLIA_ENDPOINTS[endpoint].primary_keys
+ def test_primary_keys_match_settings(self, endpoint: str) -> None:
+ selector = "attributes" if endpoint == "top_filter_values" else ALGOLIA_ENDPOINTS[endpoint].data_selector
+ result = _driver().run(endpoint, [ScriptedResponse(json={selector: []})])
+
+ assert result.raised is None
+ assert result.response is not None
+ assert result.response.name == endpoint
+ assert result.response.primary_keys == ALGOLIA_ENDPOINTS[endpoint].primary_keys
class TestValidateCredentials:
- def _run(self, response: Any, **kwargs: Any) -> tuple[bool, str | None]:
- with mock.patch(ALGOLIA_SESSION_PATCH) as factory:
- session = factory.return_value
- session.get.return_value = response
- session.post.return_value = response
+ def _run(self, response: ScriptedResponse | BaseException, **kwargs: Any) -> tuple[bool, str | None]:
+ # The real stack retries a dropped connection, so an error repeats on every try.
+ with scripted_network(always(response) if isinstance(response, BaseException) else [response]):
return validate_credentials(application_id="APP", api_key="key", **kwargs)
def test_invalid_credentials(self) -> None:
- resp = _response({"message": "Invalid Application-ID or API key", "status": 403}, status_code=403)
+ resp = ScriptedResponse(status=403, json={"message": "Invalid Application-ID or API key", "status": 403})
valid, error = self._run(resp, index_name="idx")
assert valid is False
assert error is not None and "Invalid Algolia Application ID or API key" in error
@@ -259,21 +175,19 @@ class TestValidateCredentials:
def test_missing_acl_accepted_at_source_create(self) -> None:
# A genuine key lacking the ACL for the probe returns a different 403; at source
# create (no schema_name) we accept it.
- resp = _response({"message": "Method not allowed with this API key", "status": 403}, status_code=403)
+ resp = ScriptedResponse(status=403, json={"message": "Method not allowed with this API key", "status": 403})
valid, error = self._run(resp, index_name="idx")
assert valid is True
assert error is None
def test_missing_acl_rejected_for_specific_schema(self) -> None:
- resp = _response({"message": "Method not allowed with this API key", "status": 403}, status_code=403)
+ resp = ScriptedResponse(status=403, json={"message": "Method not allowed with this API key", "status": 403})
valid, error = self._run(resp, index_name="idx", schema_name="synonyms")
assert valid is False
assert error is not None
def test_fanout_schema_probe_targets_the_parent_listing(self) -> None:
- with mock.patch(ALGOLIA_SESSION_PATCH) as factory:
- session = factory.return_value
- session.get.return_value = _response({}, status_code=200)
+ with scripted_network([ScriptedResponse(json={})]) as network:
valid, error = validate_credentials(
application_id="APP",
api_key="key",
@@ -281,29 +195,27 @@ class TestValidateCredentials:
schema_name="top_filter_values",
)
assert valid is True and error is None
- args, kwargs = session.get.call_args
- assert args[0] == "https://analytics.algolia.com/2/filters"
- assert kwargs["params"]["limit"] == 1
+ assert network.requests_log[0].method == "GET"
+ assert network.requests_log[0].origin == "https://analytics.algolia.com"
+ assert network.requests_log[0].path == "/2/filters"
+ assert network.requests_log[0].param("limit") == "1"
def test_invalid_application_id_rejected_before_request(self) -> None:
- with mock.patch(ALGOLIA_SESSION_PATCH) as factory:
+ with scripted_network([]) as network:
valid, error = validate_credentials(application_id="evil.com/", api_key="key", index_name="idx")
assert valid is False
assert error is not None
- factory.return_value.get.assert_not_called()
- factory.return_value.post.assert_not_called()
+ assert network.requests_log == []
def test_network_error_returns_message(self) -> None:
- with mock.patch(ALGOLIA_SESSION_PATCH) as factory:
- factory.return_value.get.side_effect = requests.ConnectionError("boom")
- valid, error = validate_credentials(application_id="APP", api_key="key")
+ valid, error = self._run(requests.ConnectionError("boom"))
assert valid is False
assert error is not None and "boom" in error
def test_not_found_returns_actionable_message(self) -> None:
# A 404 means the probed index (or application ID) doesn't exist. Give the user something to
# act on instead of a bare "returned status 404".
- resp = _response({"message": "Index does not exist"}, status_code=404)
+ resp = ScriptedResponse(status=404, json={"message": "Index does not exist"})
valid, error = self._run(resp, index_name="idx")
assert valid is False
assert error is not None
@@ -312,7 +224,7 @@ class TestValidateCredentials:
def test_unexpected_status_surfaces_algolia_message(self) -> None:
# A non-404 error carrying an Algolia message should surface it so the user isn't left with
# only a status code.
- resp = _response({"message": "Request rejected"}, status_code=400)
+ resp = ScriptedResponse(status=400, json={"message": "Request rejected"})
valid, error = self._run(resp, index_name="idx")
assert valid is False
assert error is not None and "Request rejected" in error
@@ -320,10 +232,7 @@ class TestValidateCredentials:
def test_non_json_error_body_does_not_crash(self) -> None:
# A non-JSON error body (e.g. an HTML 502 page) must not blow up validation; fall back to a
# status-based message.
- resp = mock.MagicMock()
- resp.status_code = 502
- resp.ok = False
- resp.json.side_effect = ValueError("no json")
+ resp = ScriptedResponse(status=502, body=b"<html>bad gateway</html>")
valid, error = self._run(resp, index_name="idx")
assert valid is False
assert error is not None and "502" in error
@@ -349,39 +258,30 @@ class TestStartDate:
class TestTimeSeriesEndpoints:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_incremental_sync_sends_start_date_from_the_watermark(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- calls = _wire(session, [_response({"dates": [{"date": "2026-03-19", "count": 4}]})])
-
- _rows(
- _build(
- "users_count",
- _make_manager(),
- should_use_incremental_field=True,
- db_incremental_field_last_value="2026-03-19",
- incremental_field="date",
- )
+ def test_incremental_sync_sends_start_date_from_the_watermark(self) -> None:
+ result = _driver().run(
+ "users_count",
+ [ScriptedResponse(json={"dates": [{"date": "2026-03-19", "count": 4}]})],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-03-19",
+ incremental_field="date",
)
- assert calls[0]["params"]["startDate"] == "2026-03-16"
+ assert result.raised is None
+ assert result.params("startDate") == ["2026-03-16"]
class TestTopFilterValuesFanout:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_checkpoints_completed_attributes_and_resumes_from_them(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- manager = _make_manager()
- _wire(
- session,
+ def test_checkpoints_completed_attributes_and_resumes_from_them(self) -> None:
+ result = _driver().run(
+ "top_filter_values",
[
- _response({"attributes": [{"attribute": "brand"}, {"attribute": "color"}]}),
- _response({"values": [{"attribute": "brand", "operator": ":", "value": "acme"}]}),
- _response({"values": [{"attribute": "color", "operator": ":", "value": "red"}]}),
+ ScriptedResponse(json={"attributes": [{"attribute": "brand"}, {"attribute": "color"}]}),
+ ScriptedResponse(json={"values": [{"attribute": "brand", "operator": ":", "value": "acme"}]}),
+ ScriptedResponse(json={"values": [{"attribute": "color", "operator": ":", "value": "red"}]}),
],
)
- _rows(_build("top_filter_values", manager))
-
- completed = [call.args[0].fanout["completed"] for call in manager.save_state.call_args_list]
+ assert result.raised is None
+ completed = [state.fanout["completed"] for state in result.saved_states if state.fanout is not None]
assert completed[-1] == ["/2/filters/brand", "/2/filters/color"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna.py
index ed9df4bd13a7..1e966c4cc20a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna.py
@@ -1,124 +1,60 @@
-import json
from typing import Any
-import pytest
-from unittest import mock
-
-from requests import Response
-
from products.warehouse_sources.backend.temporal.data_imports.sources.alguna.alguna import (
AlgunaResumeConfig,
- alguna_source,
validate_credentials,
)
-
-# RESTClient builds its session via make_tracked_session in the rest_client module.
-CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
-# validate_credentials builds its own tracked session in the alguna module.
-ALGUNA_SESSION_PATCH = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.alguna.alguna.make_tracked_session"
+from products.warehouse_sources.backend.temporal.data_imports.sources.alguna.source import AlgunaSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.alguna import AlgunaSourceConfig
+
+def _driver() -> SourceDriver:
+ return SourceDriver(AlgunaSource(), AlgunaSourceConfig(api_key="key"))
-def _response(items: list[dict[str, Any]] | None, *, drop_data: bool = False) -> Response:
+
+def _response(items: list[dict[str, Any]] | None, *, drop_data: bool = False) -> ScriptedResponse:
body: dict[str, Any] = {"pagination": {"per_page": 100}}
if not drop_data:
body["data"] = items or []
- resp = Response()
- resp.status_code = 200
- resp._content = json.dumps(body).encode()
- return resp
-
-
-def _make_manager(resume_state: AlgunaResumeConfig | None = None) -> mock.MagicMock:
- manager = mock.MagicMock()
- manager.can_resume.return_value = resume_state is not None
- manager.load_state.return_value = resume_state
- return manager
-
-
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
- """Wire a mock session and return a list that captures each request's params AT SEND TIME.
-
- ``request.params`` is a single dict mutated in place across pages, so inspecting it after the run
- shows only the final state — snapshot a copy when each request is prepared instead.
- """
- session.headers = {}
- param_snapshots: list[dict[str, Any]] = []
-
- def _prepare(request: Any) -> mock.MagicMock:
- param_snapshots.append(dict(request.params or {}))
- return mock.MagicMock()
-
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = responses
- return param_snapshots
-
-
-def _wire_urls(session: mock.MagicMock, responses: list[Response]) -> list[tuple[str, dict[str, Any]]]:
- """Like `_wire`, but capture each request's URL alongside its params so fan-out tests can tell
- a parent request from a per-parent child request."""
- session.headers = {}
- captured: list[tuple[str, dict[str, Any]]] = []
-
- def _prepare(request: Any) -> mock.MagicMock:
- captured.append((request.url or "", dict(request.params or {})))
- return mock.MagicMock()
-
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = responses
- return captured
-
-
-def _rows(source_response) -> list[dict[str, Any]]:
- return [row for page in source_response.items() for row in page]
+ return ScriptedResponse(json=body)
class TestPagination:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_paginates_and_progresses_offset(self, MockSession) -> None:
- session = MockSession.return_value
+ def test_paginates_and_progresses_offset(self) -> None:
full_page = [{"id": f"c_{i}"} for i in range(100)]
- params = _wire(session, [_response(full_page), _response([{"id": "c_last"}])])
-
- manager = _make_manager()
- rows = _rows(alguna_source("key", "customers", team_id=1, job_id="j", resumable_source_manager=manager))
+ result = _driver().run("customers", [_response(full_page), _response([{"id": "c_last"}])])
- assert [r["id"] for r in rows] == [*(f"c_{i}" for i in range(100)), "c_last"]
- assert params[0]["offset"] == 0
- assert params[0]["limit"] == 100
- assert params[1]["offset"] == 100
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == [*(f"c_{i}" for i in range(100)), "c_last"]
+ assert result.params("offset") == ["0", "100"]
+ assert result.params("limit") == ["100", "100"]
# Checkpoint saved after the first full page (points at the next page); short page ends it.
- manager.save_state.assert_called_once()
- assert manager.save_state.call_args.args[0] == AlgunaResumeConfig(offset=100)
+ assert result.saved_states == [AlgunaResumeConfig(offset=100)]
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_resumes_from_saved_offset(self, MockSession) -> None:
- session = MockSession.return_value
- params = _wire(session, [_response([{"id": "c_201"}])])
+ def test_resumes_from_saved_offset(self) -> None:
+ result = _driver().run("customers", [_response([{"id": "c_201"}])], resume_state=AlgunaResumeConfig(offset=200))
- manager = _make_manager(AlgunaResumeConfig(offset=200))
- _rows(alguna_source("key", "customers", team_id=1, job_id="j", resumable_source_manager=manager))
-
- assert params[0]["offset"] == 200
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_missing_data_key_raises_loudly(self, MockSession) -> None:
- session = MockSession.return_value
- _wire(session, [_response(None, drop_data=True)])
+ assert result.raised is None
+ assert result.params("offset") == ["200"]
+ def test_missing_data_key_raises_loudly(self) -> None:
# A 200 body without "data" means the response shape changed — fail loud, not silently 0 rows.
- with pytest.raises(ValueError, match="matched nothing"):
- _rows(alguna_source("key", "customers", team_id=1, job_id="j", resumable_source_manager=_make_manager()))
+ result = _driver().run("customers", [_response(None, drop_data=True)])
+
+ assert isinstance(result.raised, ValueError)
+ assert "matched nothing" in str(result.raised)
class TestFanout:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_credit_notes_fan_out_over_customers_and_paginate_child(self, MockSession) -> None:
- session = MockSession.return_value
+ def test_credit_notes_fan_out_over_customers_and_paginate_child(self) -> None:
cust1_full = [{"id": f"cn1_{i}", "customer_id": "cust_1"} for i in range(100)]
- reqs = _wire_urls(
- session,
+ result = _driver().run(
+ "credit_notes",
[
_response([{"id": "cust_1"}, {"id": "cust_2"}]), # parent: short page ends parent walk
_response(cust1_full), # cust_1 credit-notes page 1 (full → another page)
@@ -127,41 +63,33 @@ class TestFanout:
],
)
- rows = _rows(
- alguna_source("key", "credit_notes", team_id=1, job_id="j", resumable_source_manager=_make_manager())
- )
-
- assert [r["id"] for r in rows] == [*(f"cn1_{i}" for i in range(100)), "cn1_last", "cn2_1"]
- assert reqs[0][0].endswith("/customers")
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == [*(f"cn1_{i}" for i in range(100)), "cn1_last", "cn2_1"]
+ assert result.paths[0] == "/customers"
# Each customer's credit-notes are fetched with its id, and a full page advances the offset.
- child = [(url, params) for url, params in reqs if url.endswith("/credit-notes")]
- assert [params["customer_id"] for _url, params in child] == ["cust_1", "cust_1", "cust_2"]
- assert [params["offset"] for _url, params in child] == [0, 100, 0]
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_credit_notes_skips_parent_without_id(self, MockSession) -> None:
- session = MockSession.return_value
- reqs = _wire_urls(
- session,
+ child = [request for request in result.requests if request.path == "/credit-notes"]
+ assert [request.param("customer_id") for request in child] == ["cust_1", "cust_1", "cust_2"]
+ assert [request.param("offset") for request in child] == ["0", "100", "0"]
+
+ def test_credit_notes_skips_parent_without_id(self) -> None:
+ result = _driver().run(
+ "credit_notes",
[
_response([{"name": "no-id"}, {"id": "cust_2"}]),
_response([{"id": "cn2_1", "customer_id": "cust_2"}]),
],
)
- rows = _rows(
- alguna_source("key", "credit_notes", team_id=1, job_id="j", resumable_source_manager=_make_manager())
- )
-
- assert [r["id"] for r in rows] == ["cn2_1"]
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == ["cn2_1"]
# The id-less parent yields no child request.
- assert [params["customer_id"] for url, params in reqs if url.endswith("/credit-notes")] == ["cust_2"]
+ assert [request.param("customer_id") for request in result.requests if request.path == "/credit-notes"] == [
+ "cust_2"
+ ]
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_subscription_versions_fan_out_omits_child_page_size(self, MockSession) -> None:
- session = MockSession.return_value
- reqs = _wire_urls(
- session,
+ def test_subscription_versions_fan_out_omits_child_page_size(self) -> None:
+ result = _driver().run(
+ "subscription_versions",
[
_response([{"id": "sub_1"}, {"id": "sub_2"}]), # parent subscriptions
_response([{"id": "v_1", "subscription_id": "sub_1"}]),
@@ -169,23 +97,20 @@ class TestFanout:
],
)
- rows = _rows(
- alguna_source(
- "key", "subscription_versions", team_id=1, job_id="j", resumable_source_manager=_make_manager()
- )
- )
-
- assert {r["id"] for r in rows} == {"v_1", "v_2"}
- parent = next(params for url, params in reqs if url.endswith("/subscriptions"))
- assert parent["limit"] == 100 # parent paginates with an explicit page size
- child = [(url, params) for url, params in reqs if url.endswith("/versions")]
- assert {url.split("/subscriptions/")[1].split("/")[0] for url, _params in child} == {"sub_1", "sub_2"}
+ assert result.raised is None
+ assert {row["id"] for row in result.rows} == {"v_1", "v_2"}
+ parent = next(request for request in result.requests if request.path == "/subscriptions")
+ assert parent.param("limit") == "100" # parent paginates with an explicit page size
+ child = [request for request in result.requests if request.path.endswith("/versions")]
+ assert {request.path.split("/subscriptions/")[1].split("/")[0] for request in child} == {"sub_1", "sub_2"}
# The versions endpoint takes no page-size param; a leaked `limit` would be an undocumented param.
- assert all("limit" not in params for _url, params in child)
+ assert all(request.param("limit") is None for request in child)
class TestValidateCredentials:
- @mock.patch(ALGUNA_SESSION_PATCH)
- def test_ok(self, mock_session) -> None:
- mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
- assert validate_credentials("key") is True
+ def test_ok(self) -> None:
+ with scripted_network([ScriptedResponse(status=200)]) as network:
+ assert validate_credentials("key") is True
+
+ assert len(network.requests_log) == 1
+ assert network.requests_log[0].path == "/customers"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/tests/test_amplemarket.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/tests/test_amplemarket.py
index 9fe18a8a09c1..c51e1ae677db 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/tests/test_amplemarket.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/tests/test_amplemarket.py
@@ -1,161 +1,99 @@
-import json
from typing import Any
-from unittest import mock
-
-from requests import Response
-
from products.warehouse_sources.backend.temporal.data_imports.sources.amplemarket.amplemarket import (
AmplemarketResumeConfig,
- amplemarket_source,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.amplemarket.settings import BASE_URL
-
-# RESTClient builds its session via make_tracked_session in the rest_client module.
-CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
-# validate_credentials builds its own tracked session in the amplemarket module.
-AMPLEMARKET_SESSION_PATCH = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.amplemarket.amplemarket.make_tracked_session"
+from products.warehouse_sources.backend.temporal.data_imports.sources.amplemarket.source import AmplemarketSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.amplemarket import (
+ AmplemarketSourceConfig,
+)
+
+
+def _driver() -> SourceDriver:
+ return SourceDriver(AmplemarketSource(), AmplemarketSourceConfig(api_key="api-key"))
-def _response(data_key: str, items: list[dict[str, Any]], next_href: str | None, url: str) -> Response:
+def _page(data_key: str, items: list[dict[str, Any]], next_href: str | None = None) -> ScriptedResponse:
body: dict[str, Any] = {data_key: items}
if next_href is not None:
body["_links"] = {"next": {"href": next_href}}
- resp = Response()
- resp.status_code = 200
- resp._content = json.dumps(body).encode()
- # The paginator resolves relative next hrefs against the response URL.
- resp.url = url
- return resp
-
-
-def _make_manager(resume_state: AmplemarketResumeConfig | None = None) -> mock.MagicMock:
- manager = mock.MagicMock()
- manager.can_resume.return_value = resume_state is not None
- manager.load_state.return_value = resume_state
- return manager
-
-
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
- """Wire a mock session and return a list capturing each request AT PREPARE TIME.
-
- ``request.params``/``request.url`` are mutated in place across pages, so inspecting them
- after the run shows only the final state — snapshot a copy when each request is prepared.
- """
- session.headers = {}
- snapshots: list[dict[str, Any]] = []
-
- def _prepare(request: Any) -> mock.MagicMock:
- snapshots.append({"url": request.url, "params": dict(request.params or {}), "auth": request.auth})
- return mock.MagicMock()
-
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = responses
- return snapshots
-
-
-def _source(endpoint: str, manager: mock.MagicMock):
- return amplemarket_source("api-key", endpoint, team_id=1, job_id="j", resumable_source_manager=manager)
-
-
-def _rows(source_response) -> list[dict[str, Any]]:
- return [row for page in source_response.items() for row in page]
+ return ScriptedResponse(json=body)
class TestValidateCredentials:
- @mock.patch(AMPLEMARKET_SESSION_PATCH)
- def test_probes_account_info_with_bearer_token(self, mock_session):
- mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
-
- validate_credentials("api-key")
+ def test_probes_account_info_with_bearer_token(self) -> None:
+ with scripted_network([ScriptedResponse(status=200)]) as network:
+ assert validate_credentials("api-key") is True
- call = mock_session.return_value.get.call_args
- assert call.args[0] == "https://api.amplemarket.com/account-info"
- assert call.kwargs["headers"]["Authorization"] == "Bearer api-key"
+ request = network.requests_log[0]
+ assert request.url == f"{BASE_URL}/account-info"
+ assert request.headers["authorization"] == "Bearer api-key"
class TestPagination:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_follows_relative_next_link(self, MockSession):
+ def test_follows_relative_next_link(self) -> None:
# Amplemarket returns HAL-style relative next hrefs with bracketed cursor params; the
# paginator must resolve them against the base URL and drop the original params.
- session = MockSession.return_value
- requests_seen = _wire(
- session,
+ next_href = "/sequences?page[after]=b&page[size]=20"
+ result = _driver().run(
+ "sequences",
[
- _response(
- "sequences",
- [{"id": "a"}, {"id": "b"}],
- "/sequences?page[after]=b&page[size]=20",
- f"{BASE_URL}/sequences",
- ),
- _response("sequences", [{"id": "c"}], None, f"{BASE_URL}/sequences?page[after]=b&page[size]=20"),
+ _page("sequences", [{"id": "a"}, {"id": "b"}], next_href),
+ _page("sequences", [{"id": "c"}]),
],
)
- manager = _make_manager()
- rows = _rows(_source("sequences", manager))
-
- assert [row["id"] for row in rows] == ["a", "b", "c"]
- assert requests_seen[0]["url"] == f"{BASE_URL}/sequences"
- assert requests_seen[0]["params"] == {}
- assert requests_seen[1]["url"] == f"{BASE_URL}/sequences?page[after]=b&page[size]=20"
- assert requests_seen[1]["params"] == {}
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == ["a", "b", "c"]
+ assert {request.origin for request in result.requests} == {BASE_URL}
+ assert result.paths == ["/sequences", "/sequences"]
+ assert result.queries == [{}, {"page[after]": ("b",), "page[size]": ("20",)}]
# State is saved only while a next page exists, with the resolved absolute URL.
- manager.save_state.assert_called_once()
- assert manager.save_state.call_args.args[0] == AmplemarketResumeConfig(
- next_url=f"{BASE_URL}/sequences?page[after]=b&page[size]=20"
- )
+ assert result.saved_states == [AmplemarketResumeConfig(next_url=f"{BASE_URL}{next_href}")]
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_resumes_from_saved_state(self, MockSession):
- session = MockSession.return_value
+ def test_resumes_from_saved_state(self) -> None:
resume_url = f"{BASE_URL}/sequences?page[after]=x&page[size]=20"
- requests_seen = _wire(session, [_response("sequences", [{"id": "y"}], None, resume_url)])
-
- manager = _make_manager(AmplemarketResumeConfig(next_url=resume_url))
- rows = _rows(_source("sequences", manager))
+ result = _driver().run(
+ "sequences",
+ [_page("sequences", [{"id": "y"}])],
+ resume_state=AmplemarketResumeConfig(next_url=resume_url),
+ )
- assert [row["id"] for row in rows] == ["y"]
- assert requests_seen[0]["url"] == resume_url
- assert requests_seen[0]["params"] == {}
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == ["y"]
+ assert {request.origin for request in result.requests} == {BASE_URL}
+ assert result.paths == ["/sequences"]
+ assert result.queries == [{"page[after]": ("x",), "page[size]": ("20",)}]
class TestTasksFanout:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_tasks_are_fetched_per_user(self, MockSession):
+ def test_tasks_are_fetched_per_user(self) -> None:
# /tasks requires a user_id filter, so the fan-out binds each parent user's id into the
# child path and pages each user's tasks through their own next-link chain.
- session = MockSession.return_value
- requests_seen = _wire(
- session,
+ result = _driver().run(
+ "tasks",
[
- _response("users", [{"id": "u1"}, {"id": "u2"}], None, f"{BASE_URL}/users"),
- _response(
- "tasks",
- [{"id": "t1", "user_id": "u1"}],
- "/tasks?user_id=u1&page[after]=t1",
- f"{BASE_URL}/tasks?user_id=u1",
- ),
- _response(
- "tasks",
- [{"id": "t2", "user_id": "u1"}],
- None,
- f"{BASE_URL}/tasks?user_id=u1&page[after]=t1",
- ),
- _response("tasks", [{"id": "t3", "user_id": "u2"}], None, f"{BASE_URL}/tasks?user_id=u2"),
+ _page("users", [{"id": "u1"}, {"id": "u2"}]),
+ _page("tasks", [{"id": "t1", "user_id": "u1"}], "/tasks?user_id=u1&page[after]=t1"),
+ _page("tasks", [{"id": "t2", "user_id": "u1"}]),
+ _page("tasks", [{"id": "t3", "user_id": "u2"}]),
],
)
- rows = _rows(_source("tasks", _make_manager()))
-
- assert [row["id"] for row in rows] == ["t1", "t2", "t3"]
- task_urls = [req["url"] for req in requests_seen if "/tasks" in (req["url"] or "")]
- assert task_urls == [
- f"{BASE_URL}/tasks?user_id=u1",
- f"{BASE_URL}/tasks?user_id=u1&page[after]=t1",
- f"{BASE_URL}/tasks?user_id=u2",
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == ["t1", "t2", "t3"]
+ assert {request.origin for request in result.requests} == {BASE_URL}
+ assert result.paths == ["/users", "/tasks", "/tasks", "/tasks"]
+ assert result.queries == [
+ {},
+ {"user_id": ("u1",)},
+ {"user_id": ("u1",), "page[after]": ("t1",)},
+ {"user_id": ("u2",)},
]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude.py
index 71758553b098..bcdb4c4ea193 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude.py
@@ -16,24 +16,27 @@ from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.amplitude.amplitude import (
AmplitudeResumeConfig,
_auth_headers,
- _get_events_rows,
- _get_fanout_rows,
- _get_list_rows,
_iter_export_window,
_normalize_event,
_parse_amplitude_ts,
- amplitude_source,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.amplitude.settings import (
- AMPLITUDE_ENDPOINTS,
ANNOTATIONS_ENDPOINT,
COHORTS_ENDPOINT,
EVENT_PROPERTIES_ENDPOINT,
+ EVENTS_ENDPOINT,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.amplitude.source import AmplitudeSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.amplitude import (
+ AmplitudeSourceConfig,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
-
-MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.amplitude.amplitude"
def _make_export_zip(files: list[list[dict[str, Any]]]) -> bytes:
@@ -65,6 +68,10 @@ def _response(status: int = 200, content: bytes = b"", json_body: Any = None, te
return response
+def _driver() -> SourceDriver:
+ return SourceDriver(AmplitudeSource(), AmplitudeSourceConfig(api_key="key", secret_key="secret", region="us"))
+
+
class TestParseAmplitudeTimestamp:
@parameterized.expand(
[
@@ -118,10 +125,11 @@ class TestValidateCredentials:
]
)
def test_status_mapping(self, _name: str, status: int, expected_valid: bool) -> None:
- with mock.patch(f"{MODULE}.make_tracked_session") as make_session:
- make_session.return_value.get.return_value = _response(status=status)
+ # The adapter retries a 500, so every try gets the same answer.
+ with scripted_network(always(ScriptedResponse(status=status))) as network:
is_valid, message = validate_credentials("key", "secret", "us")
+ assert {request.path for request in network.requests_log} == {"/api/2/annotations"}
assert is_valid is expected_valid
if expected_valid:
assert message is None
@@ -129,20 +137,19 @@ class TestValidateCredentials:
assert message is not None
def test_network_error_is_not_valid(self) -> None:
- with mock.patch(f"{MODULE}.make_tracked_session") as make_session:
- make_session.return_value.get.side_effect = requests.ConnectionError("boom")
+ with scripted_network(always(requests.ConnectionError("boom"))) as network:
is_valid, message = validate_credentials("key", "secret", "us")
+ # The real stack retries a dropped connection.
+ assert {request.path for request in network.requests_log} == {"/api/2/annotations"}
assert is_valid is False
assert message is not None
def test_uses_eu_host_when_region_is_eu(self) -> None:
- with mock.patch(f"{MODULE}.make_tracked_session") as make_session:
- make_session.return_value.get.return_value = _response(status=200)
+ with scripted_network([ScriptedResponse()]) as network:
validate_credentials("key", "secret", "eu")
- called_url = make_session.return_value.get.call_args.args[0]
- assert called_url.startswith("https://analytics.eu.amplitude.com")
+ assert network.requests_log[0].url.startswith("https://analytics.eu.amplitude.com")
class TestIterExportWindow:
@@ -207,97 +214,49 @@ class TestIterExportWindow:
class TestEventsWindowing:
@time_machine.travel("2026-06-04 12:00:00", tick=False)
def test_windows_advance_and_state_is_saved_per_window(self) -> None:
- manager = mock.MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = False
-
- windows: list[tuple[str, str]] = []
-
- def fake_iter(session, host, headers, start_param, end_param, logger):
- windows.append((start_param, end_param))
- yield {"uuid": f"{start_param}"}
-
- with mock.patch(f"{MODULE}.make_tracked_session"), mock.patch(f"{MODULE}._iter_export_window", fake_iter):
- rows = list(
- _get_events_rows(
- api_key="key",
- secret_key="secret",
- region="us",
- logger=mock.MagicMock(),
- resumable_source_manager=manager,
- should_use_incremental_field=True,
- db_incremental_field_last_value=datetime(2026, 6, 2, 9, 30, tzinfo=UTC),
- )
- )
+ result = _driver().run(
+ EVENTS_ENDPOINT,
+ [
+ ScriptedResponse(body=_make_export_zip([[{"uuid": "first"}]])),
+ ScriptedResponse(body=_make_export_zip([[{"uuid": "second"}]])),
+ ScriptedResponse(body=_make_export_zip([[{"uuid": "third"}]])),
+ ],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 6, 2, 9, 30, tzinfo=UTC),
+ )
# now=12:00, latency 2h => end boundary floored to 10:00. Cursor floored from last value to 09:00.
- assert windows == [
- ("20260602T09", "20260603T08"),
- ("20260603T09", "20260604T08"),
- ("20260604T09", "20260604T10"),
- ]
- assert len(rows) == 3
-
- saved = [call.args[0].window_start for call in manager.save_state.call_args_list]
- assert saved == [
- datetime(2026, 6, 3, 9, tzinfo=UTC).isoformat(),
- datetime(2026, 6, 4, 9, tzinfo=UTC).isoformat(),
- datetime(2026, 6, 4, 11, tzinfo=UTC).isoformat(),
+ assert result.params("start") == ["20260602T09", "20260603T09", "20260604T09"]
+ assert result.params("end") == ["20260603T08", "20260604T08", "20260604T10"]
+ assert [row["uuid"] for row in result.rows] == ["first", "second", "third"]
+ assert result.saved_states == [
+ AmplitudeResumeConfig(window_start=datetime(2026, 6, 3, 9, tzinfo=UTC).isoformat()),
+ AmplitudeResumeConfig(window_start=datetime(2026, 6, 4, 9, tzinfo=UTC).isoformat()),
+ AmplitudeResumeConfig(window_start=datetime(2026, 6, 4, 11, tzinfo=UTC).isoformat()),
]
+ assert result.raised is None
@time_machine.travel("2026-06-04 12:00:00", tick=False)
def test_resume_state_takes_precedence_over_incremental_value(self) -> None:
- manager = mock.MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = True
- manager.load_state.return_value = AmplitudeResumeConfig(window_start="2026-06-04T09:00:00+00:00")
-
- windows: list[tuple[str, str]] = []
-
- def fake_iter(session, host, headers, start_param, end_param, logger):
- windows.append((start_param, end_param))
- return iter(())
-
- with mock.patch(f"{MODULE}.make_tracked_session"), mock.patch(f"{MODULE}._iter_export_window", fake_iter):
- list(
- _get_events_rows(
- api_key="key",
- secret_key="secret",
- region="us",
- logger=mock.MagicMock(),
- resumable_source_manager=manager,
- should_use_incremental_field=True,
- db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
- )
- )
+ result = _driver().run(
+ EVENTS_ENDPOINT,
+ [ScriptedResponse(status=404)],
+ resume_state=AmplitudeResumeConfig(window_start="2026-06-04T09:00:00+00:00"),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
- manager.load_state.assert_called_once()
- assert windows == [("20260604T09", "20260604T10")]
+ assert result.params("start") == ["20260604T09"]
+ assert result.params("end") == ["20260604T10"]
+ assert result.raised is None
@time_machine.travel("2026-06-04 12:00:00", tick=False)
def test_full_refresh_starts_from_lookback_window(self) -> None:
- manager = mock.MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = False
-
- windows: list[tuple[str, str]] = []
-
- def fake_iter(session, host, headers, start_param, end_param, logger):
- windows.append((start_param, end_param))
- return iter(())
-
- with mock.patch(f"{MODULE}.make_tracked_session"), mock.patch(f"{MODULE}._iter_export_window", fake_iter):
- list(
- _get_events_rows(
- api_key="key",
- secret_key="secret",
- region="us",
- logger=mock.MagicMock(),
- resumable_source_manager=manager,
- should_use_incremental_field=False,
- db_incremental_field_last_value=None,
- )
- )
+ result = _driver().run(EVENTS_ENDPOINT, always(ScriptedResponse(status=404)))
# 30-day lookback from the 10:00 boundary => first window starts 30 days earlier at 10:00.
- assert windows[0][0] == "20260505T10"
+ assert result.requests[0].param("start") == "20260505T10"
+ assert result.raised is None
class TestListRows:
@@ -310,42 +269,22 @@ class TestListRows:
]
)
def test_data_selector_extraction(self, endpoint: str, body: Any, expected_ids: list[Any]) -> None:
- config = AMPLITUDE_ENDPOINTS[endpoint]
- with mock.patch(f"{MODULE}.make_tracked_session") as make_session:
- make_session.return_value.get.return_value = _response(status=200, json_body=body)
- rows = list(_get_list_rows("key", "secret", "us", config, mock.MagicMock()))
+ result = _driver().run(endpoint, [ScriptedResponse(json=body)])
- assert [row["id"] for row in rows] == expected_ids
+ assert [row["id"] for row in result.rows] == expected_ids
+ assert result.raised is None
def test_bare_list_response_is_yielded(self) -> None:
- config = AMPLITUDE_ENDPOINTS[ANNOTATIONS_ENDPOINT]
- with mock.patch(f"{MODULE}.make_tracked_session") as make_session:
- make_session.return_value.get.return_value = _response(status=200, json_body=[{"id": 7}])
- rows = list(_get_list_rows("key", "secret", "us", config, mock.MagicMock()))
+ result = _driver().run(ANNOTATIONS_ENDPOINT, [ScriptedResponse(json=[{"id": 7}])])
- assert [row["id"] for row in rows] == [7]
+ assert [row["id"] for row in result.rows] == [7]
+ assert result.raised is None
class TestFanoutRows:
- config = AMPLITUDE_ENDPOINTS[EVENT_PROPERTIES_ENDPOINT]
-
- def _run(self, responses: list[mock.MagicMock]) -> tuple[list[dict[str, Any]], list[str]]:
- urls: list[str] = []
-
- def get(url: str, **kwargs: Any) -> mock.MagicMock:
- urls.append(url)
- return responses[len(urls) - 1]
-
- with mock.patch(f"{MODULE}.make_tracked_session") as make_session:
- make_session.return_value.get.side_effect = get
- rows = list(_get_fanout_rows("key", "secret", "us", self.config, mock.MagicMock()))
-
- return rows, urls
-
def test_queries_each_event_type_and_stamps_it_onto_child_rows(self) -> None:
- parents = _response(
- status=200,
- json_body={
+ parents = ScriptedResponse(
+ json={
"success": True,
"data": [
{"event_type": "Play Song"},
@@ -356,54 +295,53 @@ class TestFanoutRows:
},
)
# Amplitude omits `event_type` on shared properties, so the fan-out has to supply it.
- song_props = _response(status=200, json_body={"success": True, "data": [{"event_property": "genre"}]})
- onboard_props = _response(status=200, json_body={"success": True, "data": [{"event_property": "step"}]})
+ song_props = ScriptedResponse(json={"success": True, "data": [{"event_property": "genre"}]})
+ onboard_props = ScriptedResponse(json={"success": True, "data": [{"event_property": "step"}]})
- rows, urls = self._run([parents, song_props, onboard_props])
+ result = _driver().run(EVENT_PROPERTIES_ENDPOINT, [parents, song_props, onboard_props])
- assert [(row["event_type"], row["event_property"]) for row in rows] == [
+ assert [(row["event_type"], row["event_property"]) for row in result.rows] == [
("Play Song", "genre"),
("Onboard Start", "step"),
]
- assert len(urls) == 3
- assert urls[0].endswith("/api/2/taxonomy/event")
- assert "/api/2/taxonomy/event-property?event_type=Play+Song" in urls[1]
- assert "/api/2/taxonomy/event-property?event_type=Onboard+Start" in urls[2]
+ assert len(result.requests) == 3
+ assert result.paths == [
+ "/api/2/taxonomy/event",
+ "/api/2/taxonomy/event-property",
+ "/api/2/taxonomy/event-property",
+ ]
+ assert result.params("event_type") == [None, "Play Song", "Onboard Start"]
+ assert result.urls[1].endswith("/api/2/taxonomy/event-property?event_type=Play+Song")
+ assert result.urls[2].endswith("/api/2/taxonomy/event-property?event_type=Onboard+Start")
+ assert result.raised is None
def test_400_on_one_event_type_skips_it_and_keeps_going(self) -> None:
- parents = _response(
- status=200, json_body={"data": [{"event_type": "Deleted Event"}, {"event_type": "Play Song"}]}
- )
- not_found = _response(status=400, text='{"success": false, "errors": [{"message": "Not found"}]}')
- not_found.raise_for_status.side_effect = requests.HTTPError(response=not_found)
- song_props = _response(status=200, json_body={"data": [{"event_property": "genre"}]})
+ parents = ScriptedResponse(json={"data": [{"event_type": "Deleted Event"}, {"event_type": "Play Song"}]})
+ not_found = ScriptedResponse(status=400, json={"success": False, "errors": [{"message": "Not found"}]})
+ song_props = ScriptedResponse(json={"data": [{"event_property": "genre"}]})
- rows, _urls = self._run([parents, not_found, song_props])
+ result = _driver().run(EVENT_PROPERTIES_ENDPOINT, [parents, not_found, song_props])
- assert [row["event_type"] for row in rows] == ["Play Song"]
+ assert [row["event_type"] for row in result.rows] == ["Play Song"]
+ assert result.params("event_type") == [None, "Deleted Event", "Play Song"]
+ assert result.raised is None
def test_other_http_errors_propagate(self) -> None:
- parents = _response(status=200, json_body={"data": [{"event_type": "Play Song"}]})
- forbidden = _response(status=403, text="Forbidden")
- forbidden.raise_for_status.side_effect = requests.HTTPError(response=forbidden)
+ parents = ScriptedResponse(json={"data": [{"event_type": "Play Song"}]})
+ forbidden = ScriptedResponse(status=403, body=b"Forbidden")
- with pytest.raises(requests.HTTPError):
- self._run([parents, forbidden])
+ result = _driver().run(EVENT_PROPERTIES_ENDPOINT, [parents, forbidden])
+
+ assert isinstance(result.raised, requests.HTTPError)
class TestAmplitudeSourceResponse:
@parameterized.expand([(COHORTS_ENDPOINT,), (ANNOTATIONS_ENDPOINT,)])
def test_list_response_metadata(self, endpoint: str) -> None:
- manager = mock.MagicMock(spec=ResumableSourceManager)
- response = amplitude_source(
- api_key="key",
- secret_key="secret",
- region="us",
- endpoint=endpoint,
- logger=mock.MagicMock(),
- resumable_source_manager=manager,
- )
+ result = _driver().run(endpoint, [ScriptedResponse(json={})])
+ response = result.response
+ assert response is not None
assert response.name == endpoint
assert response.primary_keys == ["id"]
assert response.partition_mode is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude_source.py
index 53908daf9c14..8bf3697dcae5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amplitude/tests/test_amplitude_source.py
@@ -1,46 +1,37 @@
-from types import SimpleNamespace
-from typing import cast
+import time_machine
-from unittest import mock
-
-from products.warehouse_sources.backend.temporal.data_imports.sources.amplitude.settings import (
- COHORTS_ENDPOINT,
- EVENTS_ENDPOINT,
-)
+from products.warehouse_sources.backend.temporal.data_imports.sources.amplitude.settings import EVENTS_ENDPOINT
from products.warehouse_sources.backend.temporal.data_imports.sources.amplitude.source import AmplitudeSource
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.amplitude import (
AmplitudeSourceConfig,
)
class TestAmplitudeSource:
- def setup_method(self):
+ def setup_method(self) -> None:
self.source = AmplitudeSource()
self.team_id = 123
self.config = AmplitudeSourceConfig(api_key="key", secret_key="secret", region="us")
- def test_get_schemas_filtered_by_names(self):
+ def test_get_schemas_filtered_by_names(self) -> None:
schemas = self.source.get_schemas(self.config, self.team_id, names=[EVENTS_ENDPOINT])
assert len(schemas) == 1
assert schemas[0].name == EVENTS_ENDPOINT
- @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.amplitude.source.amplitude_source")
- def test_source_for_pipeline_drops_last_value_on_full_refresh(self, mock_amplitude_source):
- mock_amplitude_source.return_value = SimpleNamespace(name=COHORTS_ENDPOINT)
- manager = mock.MagicMock(spec=ResumableSourceManager)
- inputs = SimpleNamespace(
- schema_name=COHORTS_ENDPOINT,
- team_id=self.team_id,
- job_id="job-2",
- logger=mock.MagicMock(),
+ @time_machine.travel("2026-06-04 12:00:00", tick=False)
+ def test_source_for_pipeline_drops_last_value_on_full_refresh(self) -> None:
+ result = SourceDriver(self.source, self.config).run(
+ EVENTS_ENDPOINT,
+ always(ScriptedResponse(status=404)),
should_use_incremental_field=False,
- incremental_field=None,
db_incremental_field_last_value="2026-01-01T00:00:00Z",
)
- self.source.source_for_pipeline(self.config, manager, cast(SourceInputs, inputs))
-
# When the user isn't running incrementally, no watermark should leak through.
- assert mock_amplitude_source.call_args.kwargs["db_incremental_field_last_value"] is None
+ assert result.requests[0].param("start") == "20260505T10"
+ assert result.raised is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/tests/test_anvil.py b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/tests/test_anvil.py
index bb35d3b67390..5bc9f886ad6f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/tests/test_anvil.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/anvil/tests/test_anvil.py
@@ -11,20 +11,20 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.anvil.anvi
_build_organization_page_query,
_build_weld_datas_query,
_execute,
- anvil_source,
- get_rows,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.anvil.settings import ANVIL_ENDPOINTS, ENDPOINTS
-
-_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.anvil.anvil"
+from products.warehouse_sources.backend.temporal.data_imports.sources.anvil.source import AnvilSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.anvil import AnvilSourceConfig
-def _make_manager(resume_state: AnvilResumeConfig | None = None) -> mock.MagicMock:
- manager = mock.MagicMock()
- manager.can_resume.return_value = resume_state is not None
- manager.load_state.return_value = resume_state
- return manager
+def _driver() -> SourceDriver:
+ return SourceDriver(AnvilSource(), AnvilSourceConfig(api_key="key"))
def _response(payload: dict[str, Any], status_code: int = 200) -> mock.MagicMock:
@@ -40,23 +40,20 @@ def _response(payload: dict[str, Any], status_code: int = 200) -> mock.MagicMock
return resp
-def _org_eids(*eids: str) -> mock.MagicMock:
- return _response({"data": {"currentUser": {"organizations": [{"eid": eid} for eid in eids]}}})
-
+def _org_eids(*eids: str) -> ScriptedResponse:
+ return ScriptedResponse(json={"data": {"currentUser": {"organizations": [{"eid": eid} for eid in eids]}}})
-def _org_page(page_field: str, items: list[dict[str, Any]], page: int = 1, page_count: int = 1) -> mock.MagicMock:
- return _response({"data": {"organization": {page_field: {"page": page, "pageCount": page_count, "items": items}}}})
-
-def _weld_datas_page(items: list[dict[str, Any]], page: int = 1, page_count: int = 1) -> mock.MagicMock:
- return _response({"data": {"weld": {"weldDatas": {"page": page, "pageCount": page_count, "items": items}}}})
+def _org_page(page_field: str, items: list[dict[str, Any]], page: int = 1, page_count: int = 1) -> ScriptedResponse:
+ return ScriptedResponse(
+ json={"data": {"organization": {page_field: {"page": page, "pageCount": page_count, "items": items}}}}
+ )
-def _mock_session(mock_make_session: mock.MagicMock, responses: list[mock.MagicMock]) -> mock.MagicMock:
- session = mock.MagicMock()
- session.post.side_effect = responses
- mock_make_session.return_value = session
- return session
+def _weld_datas_page(items: list[dict[str, Any]], page: int = 1, page_count: int = 1) -> ScriptedResponse:
+ return ScriptedResponse(
+ json={"data": {"weld": {"weldDatas": {"page": page, "pageCount": page_count, "items": items}}}}
+ )
class TestExecute:
@@ -83,92 +80,73 @@ class TestExecute:
class TestValidateCredentials:
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_valid_key_authenticates_with_basic_auth(self, mock_make_session):
- session = _mock_session(mock_make_session, [_response({"data": {"currentUser": {"eid": "u1"}}})])
+ def test_valid_key_authenticates_with_basic_auth(self) -> None:
+ with scripted_network([ScriptedResponse(json={"data": {"currentUser": {"eid": "u1"}}})]) as network:
+ assert validate_credentials("key-1") == (True, None)
- assert validate_credentials("key-1") == (True, None)
- assert session.auth == ("key-1", "")
+ assert len(network.requests_log) == 1
+ assert network.requests_log[0].headers["authorization"] == "Basic a2V5LTE6"
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_rejected_key_returns_message(self, mock_make_session):
- _mock_session(mock_make_session, [_response({}, status_code=401)])
+ def test_rejected_key_returns_message(self) -> None:
+ with scripted_network([ScriptedResponse(status=401, json={})]):
+ is_valid, error = validate_credentials("bad-key")
- is_valid, error = validate_credentials("bad-key")
assert is_valid is False
assert error == "Anvil rejected the API key"
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_graphql_error_returns_its_message(self, mock_make_session):
+ def test_graphql_error_returns_its_message(self) -> None:
# Anvil responds HTTP 200 with an errors body when no auth header is readable.
- _mock_session(mock_make_session, [_response({"errors": [{"message": "Must be authenticated"}]})])
+ with scripted_network([ScriptedResponse(json={"errors": [{"message": "Must be authenticated"}]})]):
+ is_valid, error = validate_credentials("key-1")
- is_valid, error = validate_credentials("key-1")
assert is_valid is False
assert error is not None and "Must be authenticated" in error
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_network_failure_returns_unreachable(self, mock_make_session):
- mock_make_session.return_value.post.side_effect = requests.ConnectionError("boom")
-
- assert validate_credentials("key-1") == (False, "Could not reach the Anvil API")
+ def test_network_failure_returns_unreachable(self) -> None:
+ with scripted_network([ConnectionResetError("boom")]):
+ assert validate_credentials("key-1") == (False, "Could not reach the Anvil API")
class TestOrganizations:
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_single_query_yields_every_organization(self, mock_make_session):
- session = _mock_session(
- mock_make_session,
- [_response({"data": {"currentUser": {"organizations": [{"eid": "o1"}, {"eid": "o2"}]}}})],
- )
-
- manager = _make_manager()
- batches = list(get_rows("key", "organizations", mock.MagicMock(), manager))
+ def test_single_query_yields_every_organization(self) -> None:
+ result = _driver().run("organizations", [_org_eids("o1", "o2")])
- assert [row["eid"] for batch in batches for row in batch] == ["o1", "o2"]
- assert session.post.call_count == 1
- manager.save_state.assert_not_called()
+ assert result.raised is None
+ assert [row["eid"] for row in result.rows] == ["o1", "o2"]
+ assert len(result.requests) == 1
+ assert result.saved_states == []
class TestOrganizationPagedEndpoints:
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_resumes_from_bookmarked_organization_and_offset(self, mock_make_session):
- session = _mock_session(
- mock_make_session,
- [
- _org_eids("o1", "o2"),
- _org_page("casts", [{"eid": "c9"}], page=3, page_count=3),
- ],
+ def test_resumes_from_bookmarked_organization_and_offset(self) -> None:
+ result = _driver().run(
+ "casts",
+ [_org_eids("o1", "o2"), _org_page("casts", [{"eid": "c9"}], page=3, page_count=3)],
+ resume_state=AnvilResumeConfig(next_offset=3, parent_eid="o2"),
)
- manager = _make_manager(AnvilResumeConfig(next_offset=3, parent_eid="o2"))
- list(get_rows("key", "casts", mock.MagicMock(), manager))
-
- page_calls = session.post.call_args_list[1:]
- assert len(page_calls) == 1
- variables = page_calls[0].kwargs["json"]["variables"]
+ assert result.raised is None
+ assert len(result.requests) == 2
+ variables = result.requests[1].json()["variables"]
assert variables["organizationEid"] == "o2"
assert variables["offset"] == 3
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_deleted_organization_is_skipped(self, mock_make_session):
- _mock_session(
- mock_make_session,
+ def test_deleted_organization_is_skipped(self) -> None:
+ result = _driver().run(
+ "casts",
[
_org_eids("o1", "o2"),
- _response({"data": {"organization": None}}),
+ ScriptedResponse(json={"data": {"organization": None}}),
_org_page("casts", [{"eid": "c1"}]),
],
)
- batches = list(get_rows("key", "casts", mock.MagicMock(), _make_manager()))
+ assert result.raised is None
+ assert result.rows == [{"eid": "c1", "organizationEid": "o2"}]
- assert [row for batch in batches for row in batch] == [{"eid": "c1", "organizationEid": "o2"}]
-
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_non_advancing_page_raises_instead_of_looping(self, mock_make_session):
- _mock_session(
- mock_make_session,
+ def test_non_advancing_page_raises_instead_of_looping(self) -> None:
+ result = _driver().run(
+ "casts",
[
_org_eids("o1"),
_org_page("casts", [{"eid": "c1"}], page=1, page_count=2),
@@ -176,17 +154,14 @@ class TestOrganizationPagedEndpoints:
],
)
- with pytest.raises(AnvilAPIError) as exc_info:
- list(get_rows("key", "casts", mock.MagicMock(), _make_manager()))
-
- assert "did not advance" in str(exc_info.value)
+ assert isinstance(result.raised, AnvilAPIError)
+ assert "did not advance" in str(result.raised)
class TestWeldDatasFanOut:
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_fans_out_over_welds_across_organizations(self, mock_make_session):
- session = _mock_session(
- mock_make_session,
+ def test_fans_out_over_welds_across_organizations(self) -> None:
+ result = _driver().run(
+ "weld_datas",
[
_org_eids("o1", "o2"),
_org_page("welds", [{"eid": "w1"}]),
@@ -197,18 +172,14 @@ class TestWeldDatasFanOut:
],
)
- manager = _make_manager()
- batches = list(get_rows("key", "weld_datas", mock.MagicMock(), manager))
-
- assert [row for batch in batches for row in batch] == [
+ assert result.raised is None
+ assert result.rows == [
{"eid": "d1", "weldEid": "w1"},
{"eid": "d2", "weldEid": "w1"},
{"eid": "d3", "weldEid": "w2"},
]
- weld_data_calls = [call.kwargs["json"]["variables"] for call in session.post.call_args_list[3:]]
- assert [call["weldEid"] for call in weld_data_calls] == ["w1", "w1", "w2"]
- saved = [call.args[0] for call in manager.save_state.call_args_list]
- assert [(state.next_offset, state.parent_eid) for state in saved] == [(2, "w1"), (None, "w2")]
+ assert [request.json()["variables"]["weldEid"] for request in result.requests[3:]] == ["w1", "w1", "w2"]
+ assert [(state.next_offset, state.parent_eid) for state in result.saved_states] == [(2, "w1"), (None, "w2")]
class TestQueryDocuments:
@@ -235,10 +206,13 @@ class TestQueryDocuments:
class TestAnvilSourceResponse:
@pytest.mark.parametrize("endpoint", list(ENDPOINTS))
- def test_partition_wiring_per_endpoint(self, endpoint):
+ def test_partition_wiring_per_endpoint(self, endpoint: str) -> None:
config = ANVIL_ENDPOINTS[endpoint]
- response = anvil_source("key", endpoint, mock.MagicMock(), _make_manager())
+ result = _driver().run(endpoint, [_org_eids()])
+ assert result.raised is None
+ response = result.response
+ assert response is not None
assert response.name == endpoint
assert response.primary_keys == config.primary_keys
# List ordering is undocumented, so the watermark commits only at run end.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/tests/test_apify_dataset.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/tests/test_apify_dataset.py
index 3cded24b0b19..68f95e457814 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/tests/test_apify_dataset.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apify_dataset/tests/test_apify_dataset.py
@@ -1,220 +1,139 @@
-import json
from datetime import UTC, datetime
from typing import Any
-import pytest
-from unittest import mock
-
-from requests import Response
+from unittest.mock import patch
from products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset import apify_dataset
from products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset.apify_dataset import (
ApifyResumeConfig,
- apify_dataset_source,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset.settings import (
ACTOR_RUNS_ENDPOINT,
ACTORS_ENDPOINT,
+ DATASET_ITEMS_ENDPOINT,
USAGE_MONTHLY_ENDPOINT,
)
-
-CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
-APIFY_SESSION_PATCH = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset.apify_dataset.make_tracked_session"
+from products.warehouse_sources.backend.temporal.data_imports.sources.apify_dataset.source import ApifyDatasetSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.apifydataset import (
+ ApifyDatasetSourceConfig,
)
-def _response(body: Any, *, total: int | None = None) -> Response:
- resp = Response()
- resp.status_code = 200
- resp._content = json.dumps(body).encode()
- if total is not None:
- resp.headers["X-Apify-Pagination-Total"] = str(total)
- return resp
-
-
-def _make_manager(resume_state: ApifyResumeConfig | None = None) -> mock.MagicMock:
- manager = mock.MagicMock()
- manager.can_resume.return_value = resume_state is not None
- manager.load_state.return_value = resume_state
- return manager
-
-
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
- session.headers = {}
- params: list[dict[str, Any]] = []
-
- def _prepare(request: Any) -> mock.MagicMock:
- params.append(dict(request.params or {}))
- return mock.MagicMock()
-
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = responses
- return params
-
-
-def _rows(source_response) -> list[dict[str, Any]]:
- return [row for page in source_response.items() for row in page]
-
-
-def _run(manager, responses):
- return apify_dataset_source(
- api_token="tok",
- dataset_id="ds1",
- endpoint="dataset_items",
- team_id=1,
- job_id="j",
- resumable_source_manager=manager,
- )
-
-
-def _platform_response(items: Any, total: int | None = None) -> Response:
- """Shape of every Apify platform list endpoint: rows wrapped in a data envelope."""
- return _response({"data": {"items": items, "total": total if total is not None else len(items)}})
+def _driver() -> SourceDriver:
+ return SourceDriver(ApifyDatasetSource(), ApifyDatasetSourceConfig(api_token="tok", dataset_id="ds1"))
-def _run_platform(
- endpoint: str,
- manager,
- *,
- db_incremental_field_last_value: Any = None,
- should_use_incremental_field: bool = False,
-):
- return apify_dataset_source(
- api_token="tok",
- dataset_id="ds1",
- endpoint=endpoint,
- team_id=1,
- job_id="j",
- resumable_source_manager=manager,
- db_incremental_field_last_value=db_incremental_field_last_value,
- should_use_incremental_field=should_use_incremental_field,
- )
+def _platform_page(items: Any, total: int | None = None) -> ScriptedResponse:
+ return ScriptedResponse(json={"data": {"items": items, "total": total if total is not None else len(items)}})
class TestPagination:
- @mock.patch.object(apify_dataset, "PAGE_SIZE", 2)
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_progresses_offset_and_terminates_on_header_total(self, MockSession) -> None:
- session = MockSession.return_value
+ @patch.object(apify_dataset, "PAGE_SIZE", 2)
+ def test_progresses_offset_and_terminates_on_header_total(self) -> None:
# total=3: page 1 (2 rows, full) -> continue; page 2 (offset 2, 1 row) -> offset 4 >= 3 -> stop.
- params = _wire(session, [_response([{"i": 0}, {"i": 1}], total=3), _response([{"i": 2}], total=3)])
-
- manager = _make_manager()
- rows = _rows(_run(manager, None))
-
- assert [r["i"] for r in rows] == [0, 1, 2]
- assert params[0]["offset"] == 0
- assert params[0]["limit"] == 2
- assert params[0]["format"] == "json"
- assert params[1]["offset"] == 2
- manager.save_state.assert_called_once()
- assert manager.save_state.call_args.args[0] == ApifyResumeConfig(offset=2)
-
- @mock.patch.object(apify_dataset, "PAGE_SIZE", 2)
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_resumes_from_saved_offset(self, MockSession) -> None:
- session = MockSession.return_value
- params = _wire(session, [_response([{"i": 200}], total=201)])
-
- manager = _make_manager(ApifyResumeConfig(offset=200))
- _rows(_run(manager, None))
+ result = _driver().run(
+ DATASET_ITEMS_ENDPOINT,
+ [
+ ScriptedResponse(json=[{"i": 0}, {"i": 1}], headers={"X-Apify-Pagination-Total": "3"}),
+ ScriptedResponse(json=[{"i": 2}], headers={"X-Apify-Pagination-Total": "3"}),
+ ],
+ )
- assert params[0]["offset"] == 200
+ assert [row["i"] for row in result.rows] == [0, 1, 2]
+ assert result.params("offset") == ["0", "2"]
+ assert result.params("limit") == ["2", "2"]
+ assert result.params("format") == ["json", "json"]
+ assert result.saved_states == [ApifyResumeConfig(offset=2)]
+
+ @patch.object(apify_dataset, "PAGE_SIZE", 2)
+ def test_resumes_from_saved_offset(self) -> None:
+ result = _driver().run(
+ DATASET_ITEMS_ENDPOINT,
+ [ScriptedResponse(json=[{"i": 200}], headers={"X-Apify-Pagination-Total": "201"})],
+ resume_state=ApifyResumeConfig(offset=200),
+ )
- @mock.patch.object(apify_dataset, "PAGE_SIZE", 2)
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_non_list_body_raises_loudly(self, MockSession) -> None:
- session = MockSession.return_value
- _wire(session, [_response({"error": "wrong shape"}, total=0)])
+ assert result.params("offset") == ["200"]
+ @patch.object(apify_dataset, "PAGE_SIZE", 2)
+ def test_non_list_body_raises_loudly(self) -> None:
# A misrouted request returning an error object (not a list) must fail loud, not sync it as a row.
- with pytest.raises(ValueError, match="list response body"):
- _rows(_run(_make_manager(), None))
+ result = _driver().run(
+ DATASET_ITEMS_ENDPOINT,
+ [ScriptedResponse(json={"error": "wrong shape"}, headers={"X-Apify-Pagination-Total": "0"})],
+ )
+
+ assert isinstance(result.raised, ValueError)
+ assert "list response body" in str(result.raised)
class TestValidateCredentials:
- @mock.patch(APIFY_SESSION_PATCH)
- def test_ok(self, mock_session) -> None:
- mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
- assert validate_credentials("tok", "ds1") == (True, None)
-
- @mock.patch(APIFY_SESSION_PATCH)
- def test_unauthorized_message(self, mock_session) -> None:
- mock_session.return_value.get.return_value = mock.MagicMock(status_code=401)
- ok, msg = validate_credentials("tok", "ds1")
+ def test_ok(self) -> None:
+ with scripted_network([ScriptedResponse(status=200)]):
+ assert validate_credentials("tok", "ds1") == (True, None)
+
+ def test_unauthorized_message(self) -> None:
+ with scripted_network([ScriptedResponse(status=401)]):
+ ok, msg = validate_credentials("tok", "ds1")
assert ok is False
assert "token" in (msg or "")
- @mock.patch(APIFY_SESSION_PATCH)
- def test_not_found_message(self, mock_session) -> None:
- mock_session.return_value.get.return_value = mock.MagicMock(status_code=404)
- ok, msg = validate_credentials("tok", "ds1")
+ def test_not_found_message(self) -> None:
+ with scripted_network([ScriptedResponse(status=404)]):
+ ok, msg = validate_credentials("tok", "ds1")
assert ok is False
assert "Dataset not found" in (msg or "")
- @mock.patch(APIFY_SESSION_PATCH)
- def test_network_error_message(self, mock_session) -> None:
- mock_session.return_value.get.side_effect = Exception("boom")
- ok, msg = validate_credentials("tok", "ds1")
+ def test_network_error_message(self) -> None:
+ with scripted_network([ConnectionResetError("boom")]):
+ ok, msg = validate_credentials("tok", "ds1")
assert ok is False
assert "reach the Apify API" in (msg or "")
class TestPlatformEndpoints:
- @mock.patch.object(apify_dataset, "PAGE_SIZE", 2)
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_pages_on_envelope_total_and_checkpoints_offset(self, MockSession) -> None:
- session = MockSession.return_value
- params = _wire(
- session,
- [
- _platform_response([{"id": "a"}, {"id": "b"}], total=3),
- _platform_response([{"id": "c"}], total=3),
- ],
+ @patch.object(apify_dataset, "PAGE_SIZE", 2)
+ def test_pages_on_envelope_total_and_checkpoints_offset(self) -> None:
+ result = _driver().run(
+ ACTOR_RUNS_ENDPOINT,
+ [_platform_page([{"id": "a"}, {"id": "b"}], total=3), _platform_page([{"id": "c"}], total=3)],
)
- manager = _make_manager()
- rows = _rows(_run_platform(ACTOR_RUNS_ENDPOINT, manager))
-
- assert [r["id"] for r in rows] == ["a", "b", "c"]
- assert [p["offset"] for p in params] == [0, 2]
- assert manager.save_state.call_args.args[0] == ApifyResumeConfig(offset=2)
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_incremental_sends_started_after_from_watermark(self, MockSession) -> None:
- session = MockSession.return_value
- params = _wire(session, [_platform_response([])])
-
- _rows(
- _run_platform(
- ACTOR_RUNS_ENDPOINT,
- _make_manager(),
- db_incremental_field_last_value=datetime(2026, 3, 4, 5, 6, 7, 890000, tzinfo=UTC),
- should_use_incremental_field=True,
- )
+ assert [row["id"] for row in result.rows] == ["a", "b", "c"]
+ assert result.params("offset") == ["0", "2"]
+ assert result.saved_states == [ApifyResumeConfig(offset=2)]
+
+ def test_incremental_sends_started_after_from_watermark(self) -> None:
+ result = _driver().run(
+ ACTOR_RUNS_ENDPOINT,
+ [_platform_page([])],
+ incremental_field="startedAt",
+ db_incremental_field_last_value=datetime(2026, 3, 4, 5, 6, 7, 890000, tzinfo=UTC),
)
# Truncated to whole seconds, which only ever re-fetches the boundary row.
- assert params[0]["startedAfter"] == "2026-03-04T05:06:07Z"
+ assert result.requests[0].param("startedAfter") == "2026-03-04T05:06:07Z"
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_missing_envelope_raises_loudly(self, MockSession) -> None:
- session = MockSession.return_value
- _wire(session, [_response({"error": {"type": "insufficient-permissions"}})])
+ def test_missing_envelope_raises_loudly(self) -> None:
+ result = _driver().run(
+ ACTORS_ENDPOINT, [ScriptedResponse(json={"error": {"type": "insufficient-permissions"}})]
+ )
- with pytest.raises(ValueError, match="matched nothing"):
- _rows(_run_platform(ACTORS_ENDPOINT, _make_manager()))
+ assert isinstance(result.raised, ValueError)
+ assert "matched nothing" in str(result.raised)
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_monthly_usage_becomes_one_row_per_day(self, MockSession) -> None:
- session = MockSession.return_value
- _wire(
- session,
+ def test_monthly_usage_becomes_one_row_per_day(self) -> None:
+ result = _driver().run(
+ USAGE_MONTHLY_ENDPOINT,
[
- _response(
- {
+ ScriptedResponse(
+ json={
"data": {
"usageCycle": {"startAt": "2026-03-01T00:00:00.000Z", "endAt": "2026-03-31T23:59:59.999Z"},
"monthlyServiceUsage": {"ACTOR_COMPUTE_UNITS": {"quantity": 3}},
@@ -230,18 +149,17 @@ class TestPlatformEndpoints:
],
)
- manager = _make_manager()
- rows = _rows(_run_platform(USAGE_MONTHLY_ENDPOINT, manager))
-
- assert [r["date"] for r in rows] == ["2026-03-01", "2026-03-02"]
- assert [r["totalUsageCreditsUsd"] for r in rows] == [0.5, 1.5]
- assert rows[0]["usageCycleStartAt"] == "2026-03-01T00:00:00.000Z"
- assert rows[0]["usageCycleEndAt"] == "2026-03-31T23:59:59.999Z"
- assert rows[0]["totalUsageCreditsUsdAfterVolumeDiscount"] == 2.0
+ assert [row["date"] for row in result.rows] == ["2026-03-01", "2026-03-02"]
+ assert [row["totalUsageCreditsUsd"] for row in result.rows] == [0.5, 1.5]
+ assert result.rows[0]["usageCycleStartAt"] == "2026-03-01T00:00:00.000Z"
+ assert result.rows[0]["usageCycleEndAt"] == "2026-03-31T23:59:59.999Z"
+ assert result.rows[0]["totalUsageCreditsUsdAfterVolumeDiscount"] == 2.0
# A single object endpoint has no cursor, so nothing is checkpointed.
- assert session.send.call_count == 1
- manager.save_state.assert_not_called()
+ assert len(result.requests) == 1
+ assert result.saved_states == []
def test_unknown_endpoint_raises(self) -> None:
- with pytest.raises(ValueError, match="Unknown Apify endpoint"):
- _run_platform("not_a_table", _make_manager())
+ result = _driver().run("not_a_table", [])
+
+ assert isinstance(result.raised, ValueError)
+ assert "Unknown Apify endpoint" in str(result.raised)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apitally/tests/test_apitally.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apitally/tests/test_apitally.py
index 3e2e4a691f97..d54278de0663 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apitally/tests/test_apitally.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apitally/tests/test_apitally.py
@@ -1,45 +1,29 @@
from datetime import UTC, datetime
-from typing import Any, cast
-
-from unittest.mock import Mock, patch
+from typing import Any
from parameterized import parameterized
+from requests.exceptions import ConnectionError
from products.warehouse_sources.backend.temporal.data_imports.sources.apitally.apitally import (
_format_apitally_datetime,
_incremental_window,
- apitally_source,
get_resource,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.apitally.source import ApitallySource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.apitally import (
+ ApitallySourceConfig,
+)
-class _FakeDltResource:
- """Lightweight stand-in for a DltResource returned by rest_api_resources.
-
- ``process_parent_data_item`` injects parent fields as ``_<parent_resource>_<field>``
- (see ``make_parent_key_name``), so test data should include those prefixed keys to
- exercise the row mappers.
- """
-
- def __init__(self, name: str, rows: list[dict]) -> None:
- self.name = name
- self._rows = rows
-
- def add_map(self, mapper):
- self._rows = [mapper(dict(row)) for row in self._rows]
- return self
-
- def __iter__(self):
- return iter(self._rows)
-
-
-def _response(status_code: int = 200, json_body: Any = None, text: str = "") -> Mock:
- response = Mock()
- response.status_code = status_code
- response.json.return_value = json_body if json_body is not None else {}
- response.text = text
- return response
+def _driver() -> SourceDriver:
+ return SourceDriver(ApitallySource(), ApitallySourceConfig(api_key="key"))
class TestFormatApitallyDatetime:
@@ -77,27 +61,23 @@ class TestGetResource:
class TestValidateCredentials:
- @patch("products.warehouse_sources.backend.temporal.data_imports.sources.apitally.apitally.make_tracked_session")
- def test_valid_key(self, mock_make_session) -> None:
- mock_make_session.return_value.get.return_value = _response(200, {"data": []})
-
- result = validate_credentials("valid-key")
+ def test_valid_key(self) -> None:
+ with scripted_network([ScriptedResponse(json={"data": []})]) as network:
+ result = validate_credentials("valid-key")
assert result == (True, None)
+ assert [request.path for request in network.requests_log] == ["/v1/apps"]
+ assert network.requests_log[0].headers["api-key"] == "valid-key"
- @patch("products.warehouse_sources.backend.temporal.data_imports.sources.apitally.apitally.make_tracked_session")
- def test_invalid_key(self, mock_make_session) -> None:
- mock_make_session.return_value.get.return_value = _response(401)
-
- result = validate_credentials("bad-key")
+ def test_invalid_key(self) -> None:
+ with scripted_network([ScriptedResponse(status=401)]):
+ result = validate_credentials("bad-key")
assert result == (False, "Invalid Apitally API key.")
- @patch("products.warehouse_sources.backend.temporal.data_imports.sources.apitally.apitally.make_tracked_session")
- def test_forbidden_reports_premium_plan_requirement(self, mock_make_session) -> None:
- mock_make_session.return_value.get.return_value = _response(403)
-
- result = validate_credentials("key")
+ def test_forbidden_reports_premium_plan_requirement(self) -> None:
+ with scripted_network([ScriptedResponse(status=403)]):
+ result = validate_credentials("key")
assert result == (
False,
@@ -105,37 +85,28 @@ class TestValidateCredentials:
)
@parameterized.expand([(500,), (503,)])
- @patch("products.warehouse_sources.backend.temporal.data_imports.sources.apitally.apitally.make_tracked_session")
- def test_other_error_uses_response_detail(self, status_code: int, mock_make_session) -> None:
- mock_make_session.return_value.get.return_value = _response(status_code, {"detail": "server exploded"})
-
- result = validate_credentials("key")
+ def test_other_error_uses_response_detail(self, status_code: int) -> None:
+ with scripted_network(always(ScriptedResponse(status=status_code, json={"detail": "server exploded"}))):
+ result = validate_credentials("key")
assert result == (False, "server exploded")
- @patch("products.warehouse_sources.backend.temporal.data_imports.sources.apitally.apitally.make_tracked_session")
- def test_network_error_returns_false(self, mock_make_session) -> None:
- from requests.exceptions import ConnectionError
-
- mock_make_session.return_value.get.side_effect = ConnectionError("boom")
-
- result = validate_credentials("key")
+ def test_network_error_returns_false(self) -> None:
+ with scripted_network(always(ConnectionError("boom"))):
+ valid, message = validate_credentials("key")
- assert result == (False, "boom")
+ # The real stack retries a dropped connection and wraps the cause in its own message.
+ assert valid is False
+ assert message is not None and "boom" in message
class TestApitallySourceTopLevel:
- @patch("products.warehouse_sources.backend.temporal.data_imports.sources.apitally.apitally.rest_api_resource")
- def test_apps_builds_response(self, mock_rest_api_resource) -> None:
- mock_rest_api_resource.return_value = Mock()
-
- resp = apitally_source(
- api_key="key",
- endpoint="Apps",
- team_id=1,
- job_id="job-1",
- )
+ def test_apps_builds_response(self) -> None:
+ result = _driver().run("Apps", [ScriptedResponse(json={"data": []})])
+ assert result.raised is None
+ resp = result.response
+ assert resp is not None
assert resp.name == "Apps"
assert resp.primary_keys == ["id"]
assert resp.partition_mode == "datetime"
@@ -145,62 +116,45 @@ class TestApitallySourceTopLevel:
class TestApitallyFanout:
@parameterized.expand(
[
- ("Consumers", {"id": "c1", "_Apps_id": "1"}),
- ("Traffic", {"period_start": "2025-01-01T00:00:00Z", "_Apps_id": "1"}),
- ("RequestLogs", {"request_uuid": "r1", "_Apps_id": "1"}),
+ ("Consumers", {"id": "c1"}),
+ ("Traffic", {"period_start": "2025-01-01T00:00:00Z"}),
+ ("RequestLogs", {"request_uuid": "r1"}),
]
)
- @patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"
- )
- def test_fanout_row_format_renames_parent_id_to_app_id(self, endpoint, child_row, mock_rest_api_resources) -> None:
- mock_rest_api_resources.return_value = [
- _FakeDltResource("Apps", [{"id": "1"}]),
- _FakeDltResource(endpoint, [child_row]),
- ]
-
- resp = apitally_source(
- api_key="key",
- endpoint=endpoint,
- team_id=1,
- job_id="job-1",
+ def test_fanout_row_format_renames_parent_id_to_app_id(self, endpoint: str, child_row: dict[str, Any]) -> None:
+ result = _driver().run(
+ endpoint,
+ [ScriptedResponse(json={"data": [{"id": "1"}]}), ScriptedResponse(json=[child_row])],
)
- rows = list(cast(Any, resp.items()))
- assert len(rows) == 1
- row = rows[0]
+ assert result.raised is None
+ child_path = "request-logs" if endpoint == "RequestLogs" else endpoint.lower()
+ assert result.paths == ["/v1/apps", f"/v1/apps/1/{child_path}"]
+ assert len(result.rows) == 1
+ row = result.rows[0]
assert row["app_id"] == "1"
assert "_Apps_id" not in row
@parameterized.expand(["Consumers", "Endpoints", "Traffic", "RequestLogs"])
- @patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.apitally.apitally.build_dependent_resource"
- )
- def test_fanout_unwraps_parent_data_envelope(self, endpoint, mock_build) -> None:
- mock_build.return_value = iter([])
-
- apitally_source(api_key="key", endpoint=endpoint, team_id=1, job_id="job-1")
+ def test_fanout_unwraps_parent_data_envelope(self, endpoint: str) -> None:
+ result = _driver().run(
+ endpoint,
+ [ScriptedResponse(json={"data": [{"id": "1"}]}), ScriptedResponse(json=[])],
+ )
- _, kwargs = mock_build.call_args
- assert kwargs["parent_endpoint_extra"] == {"data_selector": "data"}
+ assert result.raised is None
+ assert result.paths[0] == "/v1/apps"
+ assert result.paths[1].startswith("/v1/apps/1/")
- @patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.apitally.apitally.build_dependent_resource"
- )
- def test_traffic_incremental_passes_window_factory(self, mock_build) -> None:
- mock_build.return_value = iter([])
-
- apitally_source(
- api_key="key",
- endpoint="Traffic",
- team_id=1,
- job_id="job-1",
- should_use_incremental_field=True,
+ def test_traffic_incremental_passes_window_factory(self) -> None:
+ result = _driver().run(
+ "Traffic",
+ [ScriptedResponse(json={"data": [{"id": "1"}]}), ScriptedResponse(json=[])],
db_incremental_field_last_value=datetime(2025, 1, 1, tzinfo=UTC),
incremental_field="period_end",
)
- _, kwargs = mock_build.call_args
- assert kwargs["should_use_incremental_field"] is True
- assert kwargs["incremental_field"] == "period_end"
- assert kwargs["incremental_config_factory"] is _incremental_window
+ assert result.raised is None
+ assert result.paths == ["/v1/apps", "/v1/apps/1/traffic"]
+ assert result.params("start") == [None, "2025-01-01T00:00:00Z"]
+ assert result.requests[1].param("end") is not None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apollo/tests/test_apollo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apollo/tests/test_apollo.py
index 5b04c24855df..dc7b224f05b9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apollo/tests/test_apollo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apollo/tests/test_apollo.py
@@ -15,15 +15,31 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.apollo.apo
_parse_retry_after,
_parse_timestamp,
_wait_apollo,
- apollo_source,
get_rows,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.apollo.settings import APOLLO_ENDPOINTS, ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.apollo.source import ApolloSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.apollo import ApolloSourceConfig
_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.apollo.apollo"
+def _driver() -> SourceDriver:
+ return SourceDriver(ApolloSource(), ApolloSourceConfig(api_key="key"))
+
+
+def _page(data_key: str, items: list[dict[str, Any]], total_pages: int = 1) -> ScriptedResponse:
+ return ScriptedResponse(
+ json={data_key: items, "pagination": {"page": 1, "per_page": PAGE_SIZE, "total_pages": total_pages}}
+ )
+
+
def _make_manager(resume_state: ApolloResumeConfig | None = None) -> mock.MagicMock:
manager = mock.MagicMock()
manager.can_resume.return_value = resume_state is not None
@@ -42,31 +58,6 @@ def _response(data_key: str, items: list[dict[str, Any]], total_pages: int = 1)
return resp
-def _raw_response(body: dict[str, Any]) -> mock.MagicMock:
- resp = mock.MagicMock()
- resp.json.return_value = body
- resp.status_code = 200
- resp.ok = True
- return resp
-
-
-def _lookup_response(data_key: str, items: list[dict[str, Any]]) -> mock.MagicMock:
- # The stage lookups answer with just the rows: no page params echoed, no pagination object.
- resp = mock.MagicMock()
- resp.json.return_value = {data_key: items}
- resp.status_code = 200
- resp.ok = True
- return resp
-
-
-def _rate_limited(retry_after: str | None = None) -> mock.MagicMock:
- resp = mock.MagicMock()
- resp.status_code = 429
- resp.ok = False
- resp.headers = {"Retry-After": retry_after} if retry_after is not None else {}
- return resp
-
-
class TestParseTimestamp:
@pytest.mark.parametrize(
"value, expected",
@@ -83,127 +74,98 @@ class TestParseTimestamp:
class TestValidateCredentials:
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_valid_when_logged_in(self, mock_session):
- resp = mock.MagicMock()
- resp.status_code = 200
- resp.json.return_value = {"is_logged_in": True}
- mock_session.return_value.get.return_value = resp
+ def test_valid_when_logged_in(self) -> None:
+ with scripted_network([ScriptedResponse(json={"is_logged_in": True})]) as network:
+ assert validate_credentials("key") is True
- assert validate_credentials("key") is True
+ assert [request.path for request in network.requests_log] == ["/api/v1/auth/health"]
+ assert network.requests_log[0].headers["x-api-key"] == "key"
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_invalid_when_not_logged_in(self, mock_session):
- resp = mock.MagicMock()
- resp.status_code = 200
- resp.json.return_value = {"is_logged_in": False}
- mock_session.return_value.get.return_value = resp
-
- assert validate_credentials("key") is False
-
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_invalid_on_error_status(self, mock_session):
- resp = mock.MagicMock()
- resp.status_code = 401
- mock_session.return_value.get.return_value = resp
+ def test_invalid_when_not_logged_in(self) -> None:
+ with scripted_network([ScriptedResponse(json={"is_logged_in": False})]):
+ assert validate_credentials("key") is False
- assert validate_credentials("key") is False
+ def test_invalid_on_error_status(self) -> None:
+ with scripted_network([ScriptedResponse(status=401)]):
+ assert validate_credentials("key") is False
class TestGetRows:
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_incremental_sorts_desc_and_stops_at_watermark(self, mock_session):
+ def test_incremental_sorts_desc_and_stops_at_watermark(self) -> None:
page = [
{"id": "new", "updated_at": "2024-06-01T00:00:00Z"},
{"id": "old", "updated_at": "2024-01-01T00:00:00Z"},
]
- mock_session.return_value.post.return_value = _response("contacts", page, total_pages=5)
-
- manager = _make_manager()
- batches = list(
- get_rows(
- "key",
- "contacts",
- mock.MagicMock(),
- manager,
- should_use_incremental_field=True,
- db_incremental_field_last_value=datetime(2024, 3, 1, tzinfo=UTC),
- )
+ result = _driver().run(
+ "contacts",
+ [_page("contacts", page, total_pages=5)],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 3, 1, tzinfo=UTC),
)
# Only the newer row is yielded and the walk stops on crossing.
- assert [item["id"] for batch in batches for item in batch] == ["new"]
- assert mock_session.return_value.post.call_count == 1
- body = mock_session.return_value.post.call_args.kwargs["json"]
+ assert [item["id"] for item in result.rows] == ["new"]
+ assert result.raised is None
+ assert len(result.requests) == 1
+ body = result.requests[0].json()
assert body["sort_by_field"] == "contact_updated_at"
assert body["sort_ascending"] is False
@pytest.mark.parametrize("endpoint", ["tasks", "emailer_campaigns"])
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_query_param_post_endpoints_paginate_in_the_query_string(self, mock_session, endpoint):
+ def test_query_param_post_endpoints_paginate_in_the_query_string(self, endpoint: str) -> None:
# These POSTs only read page params from the query string. Sent in the JSON body they
# are ignored, so every request comes back as page 1 and the walk re-yields it until
# the 500-page cap.
- mock_session.return_value.post.side_effect = [
- _response(endpoint, [{"id": "a1"}], total_pages=2),
- _response(endpoint, [{"id": "a2"}], total_pages=2),
- ]
-
- batches = list(get_rows("key", endpoint, mock.MagicMock(), _make_manager()))
+ result = _driver().run(
+ endpoint,
+ [
+ _page(endpoint, [{"id": "a1"}], total_pages=2),
+ _page(endpoint, [{"id": "a2"}], total_pages=2),
+ ],
+ )
- assert [item["id"] for batch in batches for item in batch] == ["a1", "a2"]
- calls = mock_session.return_value.post.call_args_list
- assert [call.kwargs["params"]["page"] for call in calls] == [1, 2]
- assert calls[0].kwargs["params"]["per_page"] == PAGE_SIZE
- assert calls[0].kwargs["json"] == {}
+ assert [item["id"] for item in result.rows] == ["a1", "a2"]
+ assert result.raised is None
+ assert result.params("page") == ["1", "2"]
+ assert result.params("per_page") == [str(PAGE_SIZE), str(PAGE_SIZE)]
+ assert result.requests[0].json() == {}
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_emailer_messages_stops_without_a_pagination_object(self, mock_session):
+ def test_emailer_messages_stops_without_a_pagination_object(self) -> None:
# This endpoint answers with no pagination object at all, so there is no total_pages
# to break on — the walk has to end on the first empty page instead of running to the cap.
page = {"emailer_messages": [{"id": "m1", "created_at": "2024-01-01T00:00:00Z"}], "emailer_steps": []}
empty: dict[str, list[Any]] = {"emailer_messages": [], "emailer_steps": []}
- mock_session.return_value.get.side_effect = [
- _raw_response(page),
- _raw_response(empty),
- ]
-
- batches = list(get_rows("key", "emailer_messages", mock.MagicMock(), _make_manager()))
+ result = _driver().run("emailer_messages", [ScriptedResponse(json=page), ScriptedResponse(json=empty)])
- assert [item["id"] for batch in batches for item in batch] == ["m1"]
- assert mock_session.return_value.get.call_count == 2
+ assert [item["id"] for item in result.rows] == ["m1"]
+ assert result.raised is None
+ assert result.params("page") == ["1", "2"]
@pytest.mark.parametrize("endpoint", ["contact_stages", "account_stages", "opportunity_stages"])
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_lookup_endpoints_read_one_unpaginated_page(self, mock_session, endpoint):
+ def test_lookup_endpoints_read_one_unpaginated_page(self, endpoint: str) -> None:
# Without the single-page stop these would loop forever: the response carries no
# total_pages to break on, so every pass re-yields the same rows.
- mock_session.return_value.get.return_value = _lookup_response(endpoint, [{"id": "s1"}])
-
- manager = _make_manager()
- batches = list(get_rows("key", endpoint, mock.MagicMock(), manager))
+ # The stage lookups answer with just the rows: no page params echoed, no pagination object.
+ result = _driver().run(endpoint, [ScriptedResponse(json={endpoint: [{"id": "s1"}]})])
- assert [item["id"] for batch in batches for item in batch] == ["s1"]
- assert mock_session.return_value.get.call_count == 1
- assert mock_session.return_value.post.call_count == 0
- assert mock_session.return_value.get.call_args.kwargs["params"] == {}
- manager.save_state.assert_not_called()
+ assert [item["id"] for item in result.rows] == ["s1"]
+ assert result.raised is None
+ assert len(result.requests) == 1
+ assert result.requests[0].method == "GET"
+ assert result.requests[0].query == {}
+ assert result.saved_states == []
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_users_paginates_with_query_params(self, mock_session):
+ def test_users_paginates_with_query_params(self) -> None:
# Page params have to ride the query string on this GET; sent as a body they are
# ignored and every page comes back as page 1.
- mock_session.return_value.get.side_effect = [
- _response("users", [{"id": "u1"}], total_pages=2),
- _response("users", [{"id": "u2"}], total_pages=2),
- ]
-
- batches = list(get_rows("key", "users", mock.MagicMock(), _make_manager()))
+ result = _driver().run(
+ "users", [_page("users", [{"id": "u1"}], total_pages=2), _page("users", [{"id": "u2"}], total_pages=2)]
+ )
- assert [item["id"] for batch in batches for item in batch] == ["u1", "u2"]
- pages = [call.kwargs["params"]["page"] for call in mock_session.return_value.get.call_args_list]
- assert pages == [1, 2]
- assert mock_session.return_value.get.call_args.kwargs["params"]["per_page"] == PAGE_SIZE
+ assert [item["id"] for item in result.rows] == ["u1", "u2"]
+ assert result.raised is None
+ assert result.params("page") == ["1", "2"]
+ assert result.params("per_page") == [str(PAGE_SIZE), str(PAGE_SIZE)]
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_search_cap_is_logged(self, mock_session):
@@ -233,8 +195,7 @@ class TestGetRows:
assert len(batches) == 1
logger.error.assert_called_once()
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_incremental_keeps_records_without_parseable_updated_at(self, mock_session):
+ def test_incremental_keeps_records_without_parseable_updated_at(self) -> None:
# A record with a missing updated_at must not be dropped, and must not stop
# the walk before a genuinely older record is reached.
page = [
@@ -242,30 +203,27 @@ class TestGetRows:
{"id": "no-ts"},
{"id": "old", "updated_at": "2024-01-01T00:00:00Z"},
]
- mock_session.return_value.post.return_value = _response("contacts", page, total_pages=5)
-
- manager = _make_manager()
- batches = list(
- get_rows(
- "key",
- "contacts",
- mock.MagicMock(),
- manager,
- should_use_incremental_field=True,
- db_incremental_field_last_value=datetime(2024, 3, 1, tzinfo=UTC),
- )
+ result = _driver().run(
+ "contacts",
+ [_page("contacts", page, total_pages=5)],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 3, 1, tzinfo=UTC),
)
- assert [item["id"] for batch in batches for item in batch] == ["new", "no-ts"]
- assert mock_session.return_value.post.call_count == 1
+ assert [item["id"] for item in result.rows] == ["new", "no-ts"]
+ assert result.raised is None
+ assert len(result.requests) == 1
class TestApolloSourceResponse:
@pytest.mark.parametrize("endpoint", list(ENDPOINTS))
- def test_response_metadata_per_endpoint(self, endpoint):
+ def test_response_metadata_per_endpoint(self, endpoint: str) -> None:
config = APOLLO_ENDPOINTS[endpoint]
- response = apollo_source("key", endpoint, mock.MagicMock(), _make_manager())
+ result = _driver().run(endpoint, [ScriptedResponse(json={config.data_key: []})])
+ response = result.response
+ assert result.raised is None
+ assert response is not None
assert response.name == endpoint
assert response.primary_keys == [config.primary_key]
assert response.sort_mode == ("desc" if config.sort_by_field else "asc")
@@ -315,16 +273,17 @@ class TestRetryAfter:
== MAX_RETRY_AFTER_SECONDS
)
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_429_is_retried_and_recovers(self, mock_session):
+ def test_429_is_retried_and_recovers(self) -> None:
# Retry-After "0" keeps the retry instant while still proving the header is
# read and honored end-to-end from the raise site through get_rows.
- mock_session.return_value.post.side_effect = [
- _rate_limited(retry_after="0"),
- _response("contacts", [{"id": "c1", "updated_at": "2024-01-01T00:00:00Z"}]),
- ]
-
- batches = list(get_rows("key", "contacts", mock.MagicMock(), _make_manager()))
+ result = _driver().run(
+ "contacts",
+ [
+ ScriptedResponse(status=429, headers={"Retry-After": "0"}),
+ _page("contacts", [{"id": "c1", "updated_at": "2024-01-01T00:00:00Z"}]),
+ ],
+ )
- assert [item["id"] for batch in batches for item in batch] == ["c1"]
- assert mock_session.return_value.post.call_count == 2
+ assert [item["id"] for item in result.rows] == ["c1"]
+ assert result.raised is None
+ assert len(result.requests) == 2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py
index 74f098ed5de5..be011f272c3c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py
@@ -3,40 +3,34 @@ from typing import Any
import pytest
import time_machine
-from unittest import mock
-from products.warehouse_sources.backend.temporal.data_imports.sources.appfigures import appfigures
from products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.appfigures import (
AppfiguresResumeConfig,
_flatten_ranks,
_flatten_report,
_to_date_str,
- appfigures_source,
check_credentials,
- get_rows,
)
-
-_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.appfigures"
+from products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.source import AppfiguresSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.appfigures import (
+ AppfiguresSourceConfig,
+)
_PAGE_LIMIT_REASON = (
"page * count must be less than or equal to 10000. Please request fewer products or a smaller date range."
)
-def _response(status_code: int, reason: str = "", text: str = "") -> mock.MagicMock:
- response = mock.MagicMock()
- response.status_code = status_code
- response.reason = reason
- response.text = text
- response.ok = status_code < 400
- return response
-
-
-def _manager(resume: AppfiguresResumeConfig | None = None) -> mock.MagicMock:
- manager = mock.MagicMock()
- manager.can_resume.return_value = resume is not None
- manager.load_state.return_value = resume
- return manager
+def _driver(aso_countries: str | None = None) -> SourceDriver:
+ return SourceDriver(
+ AppfiguresSource(), AppfiguresSourceConfig(personal_access_token="pat", aso_countries=aso_countries)
+ )
class TestToDateStr:
@@ -51,17 +45,17 @@ class TestToDateStr:
("2024-03-04", "2024-03-04"),
],
)
- def test_to_date_str(self, value: Any, expected: str | None):
+ def test_to_date_str(self, value: Any, expected: str | None) -> None:
assert _to_date_str(value) == expected
@pytest.mark.parametrize("value", ["2024-01", "not-a-date", "garbage123"])
- def test_to_date_str_raises_on_unparseable_fragment(self, value: str):
+ def test_to_date_str_raises_on_unparseable_fragment(self, value: str) -> None:
with pytest.raises(ValueError, match="Could not derive a yyyy-mm-dd date"):
_to_date_str(value)
class TestFlattenReport:
- def test_keyed_by_date_becomes_sorted_rows_with_date_injected(self):
+ def test_keyed_by_date_becomes_sorted_rows_with_date_injected(self) -> None:
body = {
"2024-01-02": {"downloads": 5, "revenue": 1.0},
"2024-01-01": {"downloads": 3, "revenue": 0.5},
@@ -72,91 +66,68 @@ class TestFlattenReport:
{"date": "2024-01-02", "downloads": 5, "revenue": 1.0},
]
- def test_non_dict_input_returns_empty(self):
+ def test_non_dict_input_returns_empty(self) -> None:
assert _flatten_report([1, 2, 3]) == []
class TestIterObject:
- def test_products_object_flattened_to_list_of_values(self):
+ def test_products_object_flattened_to_list_of_values(self) -> None:
body = {"42": {"id": 42, "name": "App A"}, "7": {"id": 7, "name": "App B"}}
- with mock.patch(f"{_MODULE}._fetch", return_value=body):
- batches = list(
- get_rows(token="pat", endpoint="products", logger=mock.MagicMock(), resumable_source_manager=_manager())
- )
- assert len(batches) == 1
- assert {row["id"] for row in batches[0]} == {42, 7}
+ result = _driver().run("products", [ScriptedResponse(json=body)])
+ assert result.raised is None
+ assert len(result.items) == 1
+ assert {row["id"] for row in result.rows} == {42, 7}
class TestIterPaged:
- def test_incremental_sets_start_param_from_watermark(self):
+ def test_incremental_sets_start_param_from_watermark(self) -> None:
body = {"total": 0, "pages": 1, "this_page": 1, "reviews": []}
- with mock.patch(f"{_MODULE}._fetch", return_value=body) as fetch:
- list(
- get_rows(
- token="pat",
- endpoint="reviews",
- logger=mock.MagicMock(),
- resumable_source_manager=_manager(),
- should_use_incremental_field=True,
- db_incremental_field_last_value=datetime(2024, 5, 1, 12, 0, tzinfo=UTC),
- )
- )
- assert fetch.call_args_list[0].args[2]["start"] == "2024-05-01"
-
- def test_page_limit_stops_and_keeps_rows_gathered_so_far(self):
+ result = _driver().run(
+ "reviews",
+ [ScriptedResponse(json=body)],
+ incremental_field="date",
+ db_incremental_field_last_value=datetime(2024, 5, 1, 12, 0, tzinfo=UTC),
+ )
+ assert result.raised is None
+ assert result.params("start") == ["2024-05-01"]
+
+ def test_page_limit_stops_and_keeps_rows_gathered_so_far(self) -> None:
# A backlog deep enough that offset pagination would cross Appfigures' page*count<=10000
# cap. Page 1 succeeds; page 2 hits the cap. get_rows must yield page 1's rows and NOT raise
# (the reported bug turned this benign boundary into a fatal HTTPError).
- page1 = _response(200)
- page1.json.return_value = {"total": 50000, "pages": 100, "this_page": 1, "reviews": [{"id": "a"}]}
- page_limit = _response(400, reason=_PAGE_LIMIT_REASON)
-
- session = mock.MagicMock()
- session.get.side_effect = [page1, page_limit]
-
- with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
- batches = list(
- get_rows(
- token="pat",
- endpoint="reviews",
- logger=mock.MagicMock(),
- resumable_source_manager=_manager(),
- )
- )
-
- assert [row["id"] for batch in batches for row in batch] == ["a"]
- assert session.get.call_count == 2
+ result = _driver().run(
+ "reviews",
+ [
+ ScriptedResponse(json={"total": 50000, "pages": 100, "this_page": 1, "reviews": [{"id": "a"}]}),
+ ScriptedResponse(status=400, body=_PAGE_LIMIT_REASON.encode()),
+ ],
+ )
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == ["a"]
+ assert len(result.requests) == 2
class TestIterReport:
@time_machine.travel("2024-02-15", tick=False)
- def test_windows_date_range_into_chunks(self):
- body_by_window: dict[str, dict] = {
- "2024-01-01": {"2024-01-01": {"downloads": 1}},
- "2024-01-31": {"2024-01-31": {"downloads": 2}},
- }
-
- def fake_fetch(_session, _url, params, _logger):
- return body_by_window[params["start_date"]]
-
- manager = _manager()
- with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch) as fetch:
- batches = list(
- get_rows(
- token="pat",
- endpoint="sales_report",
- logger=mock.MagicMock(),
- resumable_source_manager=manager,
- should_use_incremental_field=True,
- db_incremental_field_last_value=date(2024, 1, 1),
- )
- )
- windows = [(c.args[2]["start_date"], c.args[2]["end_date"]) for c in fetch.call_args_list]
+ def test_windows_date_range_into_chunks(self) -> None:
+ result = _driver().run(
+ "sales_report",
+ [
+ ScriptedResponse(json={"2024-01-01": {"downloads": 1}}),
+ ScriptedResponse(json={"2024-01-31": {"downloads": 2}}),
+ ],
+ incremental_field="date",
+ db_incremental_field_last_value=date(2024, 1, 1),
+ )
# 30-day windows: [01-01..01-30], then [01-31..02-15] (clamped to today).
- assert windows == [("2024-01-01", "2024-01-30"), ("2024-01-31", "2024-02-15")]
- assert [r["date"] for batch in batches for r in batch] == ["2024-01-01", "2024-01-31"]
+ assert result.raised is None
+ assert list(zip(result.params("start_date"), result.params("end_date"))) == [
+ ("2024-01-01", "2024-01-30"),
+ ("2024-01-31", "2024-02-15"),
+ ]
+ assert [row["date"] for row in result.rows] == ["2024-01-01", "2024-01-31"]
# State saved after the first window, pointing at the next window's start.
- manager.save_state.assert_called_once_with(AppfiguresResumeConfig(window_start="2024-01-31"))
+ assert result.saved_states == [AppfiguresResumeConfig(window_start="2024-01-31")]
def _ranks_body(dates: list[str], series: list[dict[str, Any]]) -> dict[str, Any]:
@@ -164,81 +135,58 @@ def _ranks_body(dates: list[str], series: list[dict[str, Any]]) -> dict[str, Any
class TestFlattenRanks:
- def test_series_arrays_shorter_than_dates_do_not_index_error(self):
+ def test_series_arrays_shorter_than_dates_do_not_index_error(self) -> None:
body = _ranks_body(
["2024-01-01", "2024-01-02"],
[{"country": "US", "product_id": 1, "category": {"id": 12}, "positions": [4], "deltas": []}],
)
rows = _flatten_ranks(body)
- assert [(r["date"], r["position"], r["delta"]) for r in rows] == [("2024-01-01", 4, None)]
+ assert [(row["date"], row["position"], row["delta"]) for row in rows] == [("2024-01-01", 4, None)]
@pytest.mark.parametrize("body", [None, [], {"dates": ["2024-01-01"]}, {"data": [{"positions": [1]}]}])
- def test_missing_or_malformed_body_returns_empty(self, body: Any):
+ def test_missing_or_malformed_body_returns_empty(self, body: Any) -> None:
assert _flatten_ranks(body) == []
class TestIterRanks:
@time_machine.travel("2024-02-15", tick=False)
- def test_walks_date_windows_and_saves_state_after_each(self):
- windows: list[tuple[str, str]] = []
-
- def fake_fetch(_session, url, _params, _logger):
- if url.endswith(appfigures.PRODUCTS_PATH):
- return {"1": {"id": 1, "type": "app"}}
- _, _, start, end = url.split("/ranks/")[1].split("/")
- windows.append((start, end))
- return _ranks_body(
- [start], [{"country": "US", "product_id": 1, "category": {"id": 12}, "positions": [5], "deltas": [0]}]
- )
-
- manager = _manager()
- with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch):
- list(
- get_rows(
- token="pat",
- endpoint="ranks",
- logger=mock.MagicMock(),
- resumable_source_manager=manager,
- should_use_incremental_field=True,
- db_incremental_field_last_value=date(2024, 1, 1),
- )
- )
-
- assert windows == [("2024-01-01", "2024-01-30"), ("2024-01-31", "2024-02-15")]
- manager.save_state.assert_called_once_with(AppfiguresResumeConfig(window_start="2024-01-31"))
+ def test_walks_date_windows_and_saves_state_after_each(self) -> None:
+ series = [{"country": "US", "product_id": 1, "category": {"id": 12}, "positions": [5], "deltas": [0]}]
+ result = _driver().run(
+ "ranks",
+ [
+ ScriptedResponse(json={"1": {"id": 1, "type": "app"}}),
+ ScriptedResponse(json=_ranks_body(["2024-01-01"], series)),
+ ScriptedResponse(json=_ranks_body(["2024-01-31"], series)),
+ ],
+ incremental_field="date",
+ db_incremental_field_last_value=date(2024, 1, 1),
+ )
+ assert result.raised is None
+ assert result.paths[1:] == [
+ "/v2/ranks/1/daily/2024-01-01/2024-01-30",
+ "/v2/ranks/1/daily/2024-01-31/2024-02-15",
+ ]
+ assert result.saved_states == [AppfiguresResumeConfig(window_start="2024-01-31")]
@time_machine.travel("2024-02-15", tick=False)
- def test_resume_starts_from_saved_window(self):
- starts: list[str] = []
-
- def fake_fetch(_session, url, _params, _logger):
- if url.endswith(appfigures.PRODUCTS_PATH):
- return {"1": {"id": 1, "type": "app"}}
- starts.append(url.split("/ranks/")[1].split("/")[2])
- return {}
-
- with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch):
- list(
- get_rows(
- token="pat",
- endpoint="ranks",
- logger=mock.MagicMock(),
- resumable_source_manager=_manager(AppfiguresResumeConfig(window_start="2024-02-10")),
- )
- )
- assert starts == ["2024-02-10"]
-
- def test_account_with_no_rankable_products_makes_no_ranks_request(self):
- def fake_fetch(_session, url, _params, _logger):
- assert url.endswith(appfigures.PRODUCTS_PATH)
- return {"999": {"id": 999, "type": "inapp"}}
-
- with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch) as fetch:
- batches = list(
- get_rows(token="pat", endpoint="ranks", logger=mock.MagicMock(), resumable_source_manager=_manager())
- )
- assert batches == []
- assert fetch.call_count == 1
+ def test_resume_starts_from_saved_window(self) -> None:
+ result = _driver().run(
+ "ranks",
+ [
+ ScriptedResponse(json={"1": {"id": 1, "type": "app"}}),
+ ScriptedResponse(json={}),
+ ],
+ resume_state=AppfiguresResumeConfig(window_start="2024-02-10"),
+ )
+ assert result.raised is None
+ assert result.paths[1:] == ["/v2/ranks/1/daily/2024-02-10/2024-02-15"]
+
+ def test_account_with_no_rankable_products_makes_no_ranks_request(self) -> None:
+ result = _driver().run("ranks", [ScriptedResponse(json={"999": {"id": 999, "type": "inapp"}})])
+ assert result.raised is None
+ assert result.items == []
+ assert result.paths == ["/v2/products/mine"]
def _aso_page(results: list[dict[str, Any]], page: int = 1, total_pages: int = 1) -> dict[str, Any]:
@@ -250,128 +198,84 @@ def _aso_page(results: list[dict[str, Any]], page: int = 1, total_pages: int = 1
class TestIterAso:
@time_machine.travel("2024-02-15", tick=False)
- def test_resume_target_missing_from_catalog_starts_over(self):
- def fake_fetch(_session, url, _params, _logger):
- if url.endswith(appfigures.PRODUCTS_PATH):
- return {"1": {"id": 1, "type": "app"}}
- return _aso_page([])
-
- with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch) as fetch:
- list(
- get_rows(
- token="pat",
- endpoint="aso_keywords",
- logger=mock.MagicMock(),
- resumable_source_manager=_manager(AppfiguresResumeConfig(aso_target="404:US", next_page=7)),
- aso_countries="US",
- )
- )
- assert [(c.args[2]["products"], c.args[2]["page"]) for c in fetch.call_args_list[1:]] == [("1", 1)]
+ def test_resume_target_missing_from_catalog_starts_over(self) -> None:
+ result = _driver("US").run(
+ "aso_keywords",
+ [
+ ScriptedResponse(json={"1": {"id": 1, "type": "app"}}),
+ ScriptedResponse(json=_aso_page([])),
+ ],
+ resume_state=AppfiguresResumeConfig(aso_target="404:US", next_page=7),
+ )
+ assert result.raised is None
+ assert [(request.param("products"), request.param("page")) for request in result.requests[1:]] == [("1", "1")]
@time_machine.travel("2024-02-15", tick=False)
- def test_page_limit_stops_the_target_and_moves_to_the_next(self):
- products = _response(200)
- products.json.return_value = {"1": {"id": 1, "type": "app"}, "2": {"id": 2, "type": "app"}}
- first_page = _response(200)
- first_page.json.return_value = _aso_page([{"keyword_id": "k1"}], page=1, total_pages=9)
- page_limit = _response(400, reason=_PAGE_LIMIT_REASON)
- second_target = _response(200)
- second_target.json.return_value = _aso_page([{"keyword_id": "k2"}])
-
- session = mock.MagicMock()
- session.get.side_effect = [products, first_page, page_limit, second_target]
-
- with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
- batches = list(
- get_rows(
- token="pat",
- endpoint="aso_keywords",
- logger=mock.MagicMock(),
- resumable_source_manager=_manager(),
- aso_countries="US",
- )
- )
-
- assert [row["keyword_id"] for batch in batches for row in batch] == ["k1", "k2"]
- assert session.get.call_count == 4
-
- def test_account_with_no_rankable_products_makes_no_aso_request(self):
- with mock.patch(f"{_MODULE}._fetch", return_value={"9": {"id": 9, "type": "inapp"}}) as fetch:
- batches = list(
- get_rows(
- token="pat",
- endpoint="aso_keywords",
- logger=mock.MagicMock(),
- resumable_source_manager=_manager(),
- )
- )
- assert batches == []
- assert fetch.call_count == 1
+ def test_page_limit_stops_the_target_and_moves_to_the_next(self) -> None:
+ result = _driver("US").run(
+ "aso_keywords",
+ [
+ ScriptedResponse(json={"1": {"id": 1, "type": "app"}, "2": {"id": 2, "type": "app"}}),
+ ScriptedResponse(json=_aso_page([{"keyword_id": "k1"}], page=1, total_pages=9)),
+ ScriptedResponse(status=400, body=_PAGE_LIMIT_REASON.encode()),
+ ScriptedResponse(json=_aso_page([{"keyword_id": "k2"}])),
+ ],
+ )
+ assert result.raised is None
+ assert [row["keyword_id"] for row in result.rows] == ["k1", "k2"]
+ assert len(result.requests) == 4
+
+ def test_account_with_no_rankable_products_makes_no_aso_request(self) -> None:
+ result = _driver().run("aso_keywords", [ScriptedResponse(json={"9": {"id": 9, "type": "inapp"}})])
+ assert result.raised is None
+ assert result.items == []
+ assert result.paths == ["/v2/products/mine"]
class TestIterAsoStats:
@time_machine.travel("2024-02-15", tick=False)
- def test_one_row_per_target_with_identity_and_window(self):
- def fake_fetch(_session, url, params, _logger):
- if url.endswith(appfigures.PRODUCTS_PATH):
- return {"1": {"id": 1, "type": "app"}, "2": {"id": 2, "type": "app"}}
- return {"avg_position": 21, "top_5": 1, "total_keywords": 5, "_asked": params["products"]}
-
- manager = _manager()
- with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch) as fetch:
- batches = list(
- get_rows(
- token="pat",
- endpoint="aso_stats",
- logger=mock.MagicMock(),
- resumable_source_manager=manager,
- aso_countries="US",
- )
- )
-
- assert [len(batch) for batch in batches] == [1, 1]
- rows = [row for batch in batches for row in batch]
- assert [(r["date"], r["product_id"], r["country"], r["avg_position"]) for r in rows] == [
+ def test_one_row_per_target_with_identity_and_window(self) -> None:
+ result = _driver("US").run(
+ "aso_stats",
+ [
+ ScriptedResponse(json={"1": {"id": 1, "type": "app"}, "2": {"id": 2, "type": "app"}}),
+ ScriptedResponse(json={"avg_position": 21, "top_5": 1, "total_keywords": 5}),
+ ScriptedResponse(json={"avg_position": 21, "top_5": 1, "total_keywords": 5}),
+ ],
+ )
+ assert result.raised is None
+ assert [len(batch) for batch in result.items] == [1, 1]
+ assert [(row["date"], row["product_id"], row["country"], row["avg_position"]) for row in result.rows] == [
("2024-02-15", "1", "US", 21),
("2024-02-15", "2", "US", 21),
]
# /aso/stats spells its window start/end rather than start_date/end_date.
- params = fetch.call_args_list[1].args[2]
- assert (params["start"], params["end"]) == ("2024-01-17", "2024-02-15")
- manager.save_state.assert_called_once_with(AppfiguresResumeConfig(aso_target="2:US"))
+ assert (result.requests[1].param("start"), result.requests[1].param("end")) == ("2024-01-17", "2024-02-15")
+ assert result.saved_states == [AppfiguresResumeConfig(aso_target="2:US")]
@time_machine.travel("2024-02-15", tick=False)
- def test_resume_skips_targets_already_walked(self):
- def fake_fetch(_session, url, _params, _logger):
- if url.endswith(appfigures.PRODUCTS_PATH):
- return {str(index): {"id": index, "type": "app"} for index in (1, 2, 3)}
- return {"avg_position": 1}
-
- with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch) as fetch:
- list(
- get_rows(
- token="pat",
- endpoint="aso_stats",
- logger=mock.MagicMock(),
- resumable_source_manager=_manager(AppfiguresResumeConfig(aso_target="3:US")),
- aso_countries="US",
- )
- )
- assert [c.args[2]["products"] for c in fetch.call_args_list[1:]] == ["3"]
+ def test_resume_skips_targets_already_walked(self) -> None:
+ result = _driver("US").run(
+ "aso_stats",
+ [
+ ScriptedResponse(json={str(index): {"id": index, "type": "app"} for index in (1, 2, 3)}),
+ ScriptedResponse(json={"avg_position": 1}),
+ ],
+ resume_state=AppfiguresResumeConfig(aso_target="3:US"),
+ )
+ assert result.raised is None
+ assert [request.param("products") for request in result.requests[1:]] == ["3"]
class TestCheckCredentials:
@pytest.mark.parametrize("status", [200, 401, 403, 500])
- def test_returns_status_code(self, status):
- session = mock.MagicMock()
- session.get.return_value = mock.MagicMock(status_code=status)
- with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ def test_returns_status_code(self, status: int) -> None:
+ with scripted_network(always(ScriptedResponse(status=status))) as network:
assert check_credentials("pat", "/products/mine") == status
+ assert network.requests_log[0].path == "/v2/products/mine"
- def test_network_failure_returns_none(self):
- session = mock.MagicMock()
- session.get.side_effect = Exception("boom")
- with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ def test_network_failure_returns_none(self) -> None:
+ with scripted_network([ConnectionResetError("boom")]):
assert check_credentials("pat") is None
@@ -392,15 +296,12 @@ class TestAppfiguresSourceResponse:
("countries", ["iso"], None),
],
)
- def test_response_shape(self, endpoint, primary_keys, partition_key):
- response = appfigures_source(
- token="pat",
- endpoint=endpoint,
- logger=mock.MagicMock(),
- resumable_source_manager=_manager(),
- )
- assert response.name == endpoint
- assert response.primary_keys == primary_keys
- assert response.partition_mode == ("datetime" if partition_key else None)
- assert response.partition_keys == ([partition_key] if partition_key else None)
- assert response.sort_mode == "asc"
+ def test_response_shape(self, endpoint: str, primary_keys: list[str], partition_key: str | None) -> None:
+ result = _driver().run(endpoint, always(ScriptedResponse(json={})))
+ assert result.raised is None
+ assert result.response is not None
+ assert result.response.name == endpoint
+ assert result.response.primary_keys == primary_keys
+ assert result.response.partition_mode == ("datetime" if partition_key else None)
+ assert result.response.partition_keys == ([partition_key] if partition_key else None)
+ assert result.response.sort_mode == "asc"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures_source.py
index e4798f7e2284..434c757791cc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures_source.py
@@ -1,7 +1,11 @@
import pytest
-from unittest import mock
from products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.source import AppfiguresSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ always,
+ scripted_network,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.appfigures import (
AppfiguresSourceConfig,
)
@@ -37,11 +41,9 @@ class TestAppfiguresSource:
(None, None, False),
],
)
- def test_validate_credentials(self, status, schema_name, expected_ok):
- with mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.source.check_credentials",
- return_value=status,
- ):
+ def test_validate_credentials(self, status: int | None, schema_name: str | None, expected_ok: bool) -> None:
+ script = always(ScriptedResponse(status=status)) if status is not None else [ConnectionResetError("boom")]
+ with scripted_network(script):
ok, _ = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
assert ok is expected_ok
@@ -54,18 +56,16 @@ class TestAppfiguresSource:
("ranks", "/reviews"),
],
)
- def test_validate_credentials_probes_schema_specific_path(self, schema_name: str, expected_path: str):
- with mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.source.check_credentials",
- return_value=200,
- ) as probe:
+ def test_validate_credentials_probes_schema_specific_path(self, schema_name: str, expected_path: str) -> None:
+ with scripted_network([ScriptedResponse(status=200)]) as network:
self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
- probe.assert_called_once_with("pat_test", expected_path)
+ assert len(network.requests_log) == 1
+ assert network.requests_log[0].path == f"/v2{expected_path}"
+ assert network.requests_log[0].headers["authorization"] == "Bearer pat_test"
- def test_validate_credentials_defaults_to_products_path(self):
- with mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.source.check_credentials",
- return_value=200,
- ) as probe:
+ def test_validate_credentials_defaults_to_products_path(self) -> None:
+ with scripted_network([ScriptedResponse(status=200)]) as network:
self.source.validate_credentials(self.config, self.team_id)
- probe.assert_called_once_with("pat_test", "/products/mine")
+ assert len(network.requests_log) == 1
+ assert network.requests_log[0].path == "/v2/products/mine"
+ assert network.requests_log[0].headers["authorization"] == "Bearer pat_test"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/tests/test_applovin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/tests/test_applovin.py
index 186965736384..38705c4abacd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/tests/test_applovin.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/tests/test_applovin.py
@@ -1,7 +1,6 @@
-from collections.abc import Iterable
from datetime import UTC, date, datetime, timedelta
-from typing import Any, Optional, cast
-from urllib.parse import parse_qs, quote, quote_plus, urlparse
+from typing import Any, Optional
+from urllib.parse import quote, quote_plus
import pytest
from unittest import mock
@@ -16,7 +15,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.applovin.a
AppLovinResumeConfig,
_body_code,
_to_date,
- applovin_source,
get_rows,
validate_credentials,
)
@@ -28,7 +26,18 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.applovin.s
REPORT_PAGE_SIZE,
REPORT_WINDOW_DAYS,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.applovin.source import AppLovinSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ RecordedRequest,
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.applovin import (
+ AppLovinSourceConfig,
+)
_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.applovin.applovin"
@@ -66,16 +75,16 @@ def _response(body: Any = None, status_code: int = 200, text: str = "", json_err
return resp
-def _rows(count: int) -> list[dict[str, str]]:
- return [{"day": "2026-07-01", "package_name": f"com.app.{index}"} for index in range(count)]
+def _driver(api_key: str = "key") -> SourceDriver:
+ return SourceDriver(AppLovinSource(), AppLovinSourceConfig(api_key=api_key))
-def _query(url: str) -> dict[str, list[str]]:
- return parse_qs(urlparse(url).query)
+def _page(rows: Any = None) -> ScriptedResponse:
+ return ScriptedResponse(json={"code": 200, "results": rows})
-def _urls(session: mock.MagicMock) -> list[str]:
- return [call.args[0] for call in session.return_value.get.call_args_list]
+def _rows(count: int) -> list[dict[str, str]]:
+ return [{"day": "2026-07-01", "package_name": f"com.app.{index}"} for index in range(count)]
def _today() -> date:
@@ -120,13 +129,11 @@ class TestHelpers:
class TestRequestShape:
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_report_key_is_registered_for_redaction(self, mock_session: mock.MagicMock) -> None:
- mock_session.return_value.get.return_value = _response({"code": 200, "results": []})
-
- list(get_rows("secret-key", "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))
+ def test_report_key_is_registered_for_redaction(self) -> None:
+ result = _driver("secret-key").run("max_ad_revenue", [_page([]) for _ in range(7)])
- assert mock_session.call_args.kwargs["redact_values"] == ("secret-key",)
+ assert result.raised is None
+ assert result.session_options[0]["redact_values"] == ("secret-key",)
class TestWindowWalking:
@@ -146,128 +153,95 @@ class TestWindowWalking:
class TestPagination:
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_full_page_advances_offset_and_short_page_ends_the_window(self, mock_session: mock.MagicMock) -> None:
- first_window = [
- _response({"code": 200, "results": _rows(REPORT_PAGE_SIZE)}),
- _response({"code": 200, "results": _rows(REPORT_PAGE_SIZE)}),
- _response({"code": 200, "results": _rows(3)}),
- ]
- # Every later window returns a single short page.
- mock_session.return_value.get.side_effect = [
- *first_window,
- *[_response({"code": 200, "results": []}) for _ in range(50)],
- ]
- manager = FakeResumeManager()
-
- batches = list(get_rows("key", "max_ad_revenue", mock.MagicMock(), manager))
+ def test_full_page_advances_offset_and_short_page_ends_the_window(self) -> None:
+ result = _driver().run(
+ "max_ad_revenue",
+ [
+ _page(_rows(REPORT_PAGE_SIZE)),
+ _page(_rows(REPORT_PAGE_SIZE)),
+ _page(_rows(3)),
+ *[_page([]) for _ in range(6)],
+ ],
+ )
- offsets = [_query(url)["offset"][0] for url in _urls(mock_session)[:4]]
- assert offsets == ["0", str(REPORT_PAGE_SIZE), str(REPORT_PAGE_SIZE * 2), "0"]
+ assert result.raised is None
+ assert result.params("offset")[:4] == ["0", str(REPORT_PAGE_SIZE), str(REPORT_PAGE_SIZE * 2), "0"]
# The empty later windows yield nothing, so only the three real pages come through.
- assert [len(batch) for batch in batches] == [REPORT_PAGE_SIZE, REPORT_PAGE_SIZE, 3]
+ assert [len(batch) for batch in result.items] == [REPORT_PAGE_SIZE, REPORT_PAGE_SIZE, 3]
# Mid-window checkpoints carry the offset; the window rollover resets it.
- assert (manager.saved[0].next_window_start, manager.saved[0].next_offset) == (
+ assert (result.saved_states[0].next_window_start, result.saved_states[0].next_offset) == (
_earliest().isoformat(),
REPORT_PAGE_SIZE,
)
- assert manager.saved[2].next_offset == 0
+ assert result.saved_states[2].next_offset == 0
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_resumes_from_saved_window_and_offset(self, mock_session: mock.MagicMock) -> None:
- mock_session.return_value.get.return_value = _response({"code": 200, "results": []})
+ def test_resumes_from_saved_window_and_offset(self) -> None:
resume_start = _today() - timedelta(days=1)
- manager = FakeResumeManager(
- AppLovinResumeConfig(next_window_start=resume_start.isoformat(), next_offset=REPORT_PAGE_SIZE)
+ result = _driver().run(
+ "max_ad_revenue",
+ [_page([])],
+ resume_state=AppLovinResumeConfig(next_window_start=resume_start.isoformat(), next_offset=REPORT_PAGE_SIZE),
)
- list(get_rows("key", "max_ad_revenue", mock.MagicMock(), manager))
-
- params = _query(_urls(mock_session)[0])
- assert params["start"] == [resume_start.isoformat()]
- assert params["offset"] == [str(REPORT_PAGE_SIZE)]
+ assert result.raised is None
+ assert result.requests[0].param("start") == resume_start.isoformat()
+ assert result.requests[0].param("offset") == str(REPORT_PAGE_SIZE)
# A single window remains, so nothing older gets re-walked.
- assert len(_urls(mock_session)) == 1
+ assert len(result.requests) == 1
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_resume_state_behind_the_incremental_start_is_ignored(self, mock_session: mock.MagicMock) -> None:
- mock_session.return_value.get.return_value = _response({"code": 200, "results": []})
+ def test_resume_state_behind_the_incremental_start_is_ignored(self) -> None:
watermark = _today()
expected_start = watermark - timedelta(days=REPORT_LOOKBACK_DAYS)
- manager = FakeResumeManager(
- AppLovinResumeConfig(next_window_start=(expected_start - timedelta(days=10)).isoformat())
+ result = _driver().run(
+ "max_ad_revenue",
+ [_page([]), _page([])],
+ resume_state=AppLovinResumeConfig(next_window_start=(expected_start - timedelta(days=10)).isoformat()),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark.isoformat(),
)
- list(
- get_rows(
- "key",
- "max_ad_revenue",
- mock.MagicMock(),
- manager,
- should_use_incremental_field=True,
- db_incremental_field_last_value=watermark.isoformat(),
- )
- )
-
- assert _query(_urls(mock_session)[0])["start"] == [expected_start.isoformat()]
-
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_non_dict_results_are_dropped(self, mock_session: mock.MagicMock) -> None:
- mock_session.return_value.get.side_effect = [
- _response({"code": 200, "results": [{"day": "2026-07-01"}, "junk", None]}),
- *[_response({"code": 200, "results": None}) for _ in range(50)],
- ]
+ assert result.raised is None
+ assert result.requests[0].param("start") == expected_start.isoformat()
- batches = list(get_rows("key", "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))
+ def test_non_dict_results_are_dropped(self) -> None:
+ result = _driver().run(
+ "max_ad_revenue",
+ [_page([{"day": "2026-07-01"}, "junk", None]), *[_page(None) for _ in range(6)]],
+ )
- assert batches == [[{"day": "2026-07-01"}]]
+ assert result.raised is None
+ assert result.items == [[{"day": "2026-07-01"}]]
class TestErrorClassification:
@pytest.mark.parametrize("status_code", [401, 403])
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_auth_statuses_raise_the_auth_prefix(self, mock_session: mock.MagicMock, status_code: int) -> None:
- mock_session.return_value.get.return_value = _response(status_code=status_code, text="Authentication Failed")
-
- with pytest.raises(AppLovinAPIError) as exc_info:
- list(get_rows("key", "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))
+ def test_auth_statuses_raise_the_auth_prefix(self, status_code: int) -> None:
+ result = _driver().run("max_ad_revenue", [ScriptedResponse(status=status_code, body=b"Authentication Failed")])
- assert str(exc_info.value).startswith(AUTH_ERROR_PREFIX)
+ assert isinstance(result.raised, AppLovinAPIError)
+ assert str(result.raised).startswith(AUTH_ERROR_PREFIX)
@pytest.mark.parametrize("status_code", [400, 404, 422])
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_other_client_errors_raise_the_bad_request_prefix(
- self, mock_session: mock.MagicMock, status_code: int
- ) -> None:
- mock_session.return_value.get.return_value = _response(status_code=status_code, text="Invalid column")
-
- with pytest.raises(AppLovinAPIError) as exc_info:
- list(get_rows("key", "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))
+ def test_other_client_errors_raise_the_bad_request_prefix(self, status_code: int) -> None:
+ result = _driver().run("max_ad_revenue", [ScriptedResponse(status=status_code, body=b"Invalid column")])
- assert str(exc_info.value).startswith(BAD_REQUEST_ERROR_PREFIX)
- assert "Invalid column" in str(exc_info.value)
+ assert isinstance(result.raised, AppLovinAPIError)
+ assert str(result.raised).startswith(BAD_REQUEST_ERROR_PREFIX)
+ assert "Invalid column" in str(result.raised)
@pytest.mark.parametrize("status_code", [429, 500, 502, 503])
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_throttling_and_upstream_failures_stay_retryable(
- self, mock_session: mock.MagicMock, status_code: int
- ) -> None:
- mock_session.return_value.get.return_value = _response(status_code=status_code, text="try later")
-
- with pytest.raises(AppLovinAPIError) as exc_info:
- list(get_rows("key", "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))
+ def test_throttling_and_upstream_failures_stay_retryable(self, status_code: int) -> None:
+ result = _driver().run("max_ad_revenue", always(ScriptedResponse(status=status_code, body=b"try later")))
+ assert isinstance(result.raised, AppLovinAPIError)
# Must not be classified as a permanent rejection, or an outage disables the source.
- assert str(exc_info.value).startswith(TRANSIENT_ERROR_PREFIX)
-
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_non_json_body_on_a_200_is_a_bad_request(self, mock_session: mock.MagicMock) -> None:
- mock_session.return_value.get.return_value = _response(text="<html>oops</html>", json_error=True)
+ assert str(result.raised).startswith(TRANSIENT_ERROR_PREFIX)
- with pytest.raises(AppLovinAPIError) as exc_info:
- list(get_rows("key", "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))
+ def test_non_json_body_on_a_200_is_a_bad_request(self) -> None:
+ result = _driver().run("max_ad_revenue", [ScriptedResponse(body=b"<html>oops</html>")])
- assert str(exc_info.value).startswith(BAD_REQUEST_ERROR_PREFIX)
+ assert isinstance(result.raised, AppLovinAPIError)
+ assert str(result.raised).startswith(BAD_REQUEST_ERROR_PREFIX)
@pytest.mark.parametrize(
"body_code, expected_prefix",
@@ -279,91 +253,73 @@ class TestErrorClassification:
(500, TRANSIENT_ERROR_PREFIX),
],
)
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_body_level_error_code_on_a_200_is_classified(
- self, mock_session: mock.MagicMock, body_code: int, expected_prefix: str
- ) -> None:
- mock_session.return_value.get.return_value = _response({"code": body_code, "results": []})
-
- with pytest.raises(AppLovinAPIError) as exc_info:
- list(get_rows("key", "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))
+ def test_body_level_error_code_on_a_200_is_classified(self, body_code: int, expected_prefix: str) -> None:
+ result = _driver().run("max_ad_revenue", [ScriptedResponse(json={"code": body_code, "results": []})])
- assert str(exc_info.value).startswith(expected_prefix)
+ assert isinstance(result.raised, AppLovinAPIError)
+ assert str(result.raised).startswith(expected_prefix)
# A Report Key with reserved characters is percent-/plus-encoded in the request URL, so a
# transport error that quotes the URL never carries the raw key — redaction must cover the
# encoded forms too.
@pytest.mark.parametrize("api_key", ["super-secret", "ab/c+d=="])
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_transport_error_never_leaks_the_report_key(self, mock_session: mock.MagicMock, api_key: str) -> None:
+ def test_transport_error_never_leaks_the_report_key(self, api_key: str) -> None:
# `requests`/`urllib3` quote the built URL, where the key is URL-encoded.
leaked_url = f"/maxReport?api_key={quote_plus(api_key)}&columns=day"
- mock_session.return_value.get.side_effect = requests.ConnectionError(
- f"Max retries exceeded with url: {leaked_url}"
- )
- with pytest.raises(AppLovinAPIError) as exc_info:
- list(get_rows(api_key, "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))
+ def fail_request(_request: RecordedRequest) -> ScriptedResponse:
+ raise requests.ConnectionError(f"Max retries exceeded with url: {leaked_url}")
+
+ result = _driver(api_key).run("max_ad_revenue", fail_request)
- message = str(exc_info.value)
+ assert isinstance(result.raised, AppLovinAPIError)
+ message = str(result.raised)
assert api_key not in message
assert quote_plus(api_key) not in message
assert quote(api_key, safe="") not in message
assert "REDACTED" in message
# The original exception carries the unredacted URL, so it must not be chained.
- assert exc_info.value.__cause__ is None
+ assert result.raised.__cause__ is None
@pytest.mark.parametrize("api_key", ["super-secret", "ab/c+d=="])
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_error_body_echoing_the_report_key_is_redacted(self, mock_session: mock.MagicMock, api_key: str) -> None:
- mock_session.return_value.get.return_value = _response(
- status_code=400, text=f"bad request for api_key={api_key}"
+ def test_error_body_echoing_the_report_key_is_redacted(self, api_key: str) -> None:
+ result = _driver(api_key).run(
+ "max_ad_revenue", [ScriptedResponse(status=400, body=f"bad request for api_key={api_key}".encode())]
)
- with pytest.raises(AppLovinAPIError) as exc_info:
- list(get_rows(api_key, "max_ad_revenue", mock.MagicMock(), FakeResumeManager()))
-
- assert api_key not in str(exc_info.value)
+ assert isinstance(result.raised, AppLovinAPIError)
+ assert api_key not in str(result.raised)
class TestValidateCredentials:
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_advertiser_only_key_accepted_on_the_report_probe(self, mock_session: mock.MagicMock) -> None:
- mock_session.return_value.get.side_effect = [
- _response(status_code=403, text="Authentication Failed"),
- _response({"code": 200, "results": []}),
- ]
+ def test_advertiser_only_key_accepted_on_the_report_probe(self) -> None:
+ with scripted_network([ScriptedResponse(status=403, body=b"Authentication Failed"), _page([])]) as network:
+ assert validate_credentials("key") is True
- assert validate_credentials("key") is True
- assert [urlparse(url).path for url in _urls(mock_session)] == ["/maxReport", "/report"]
+ assert [request.path for request in network.requests_log] == ["/maxReport", "/report"]
@pytest.mark.parametrize(
"responses",
[
- [_response(status_code=403, text="Authentication Failed")] * 2,
- [_response({"code": 403, "results": []})] * 2,
- [_response(text="Authentication Failed", json_error=True)] * 2,
+ [ScriptedResponse(status=403, body=b"Authentication Failed")] * 2,
+ [ScriptedResponse(json={"code": 403, "results": []})] * 2,
+ [ScriptedResponse(body=b"Authentication Failed")] * 2,
],
)
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_rejected_key_is_invalid(self, mock_session: mock.MagicMock, responses: list[mock.MagicMock]) -> None:
- mock_session.return_value.get.side_effect = responses
+ def test_rejected_key_is_invalid(self, responses: list[ScriptedResponse]) -> None:
+ with scripted_network(responses) as network:
+ assert validate_credentials("bad") is False
- assert validate_credentials("bad") is False
+ assert [request.path for request in network.requests_log] == ["/maxReport", "/report"]
class TestSourceResponse:
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_items_yields_rows_as_returned_by_the_api(self, mock_session: mock.MagicMock) -> None:
- mock_session.return_value.get.side_effect = [
- _response({"code": 200, "results": [{"day": "2026-07-01", "estimated_revenue": "1.23"}]}),
- *[_response({"code": 200, "results": []}) for _ in range(50)],
- ]
- response = applovin_source("key", "max_ad_revenue", mock.MagicMock(), FakeResumeManager())
-
- batches = list(cast("Iterable[Any]", response.items()))
+ def test_items_yields_rows_as_returned_by_the_api(self) -> None:
+ rows = [{"day": "2026-07-01", "estimated_revenue": "1.23"}]
+ result = _driver().run("max_ad_revenue", [_page(rows), *[_page([]) for _ in range(6)]])
- assert batches == [[{"day": "2026-07-01", "estimated_revenue": "1.23"}]]
+ assert result.raised is None
+ assert result.items == [rows]
class TestEndpointCatalogInvariants:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/tests/test_applovin_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/tests/test_applovin_source.py
index de9716187b68..240c7102ef6f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/tests/test_applovin_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/applovin/tests/test_applovin_source.py
@@ -1,19 +1,20 @@
from typing import Optional
import pytest
-from unittest import mock
from products.warehouse_sources.backend.temporal.data_imports.sources.applovin.canonical_descriptions import (
CANONICAL_DESCRIPTIONS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.applovin.settings import ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.applovin.source import AppLovinSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ scripted_network,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.applovin import (
AppLovinSourceConfig,
)
-_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.applovin.source"
-
class TestAppLovinSource:
def setup_method(self) -> None:
@@ -34,21 +35,23 @@ class TestAppLovinSource:
(False, False, "Invalid AppLovin Report Key"),
],
)
- @mock.patch(f"{_SOURCE_MODULE}.validate_applovin_credentials")
def test_validate_credentials(
self,
- mock_validate: mock.MagicMock,
probe_result: bool,
expected_valid: bool,
expected_message: Optional[str],
) -> None:
- mock_validate.return_value = probe_result
-
- is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+ responses = (
+ [ScriptedResponse(json={"code": 200, "results": []})]
+ if probe_result
+ else [ScriptedResponse(status=403)] * 2
+ )
+ with scripted_network(responses) as network:
+ 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("report-key")
+ assert [request.param("api_key") for request in network.requests_log] == ["report-key"] * len(responses)
class TestAppLovinCanonicalDescriptions:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py
index 5fb4879395ad..dd7a4f1128db 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py
@@ -1,7 +1,6 @@
import io
from collections.abc import Iterator
from datetime import UTC, date, datetime, timedelta
-from urllib.parse import parse_qs, urlparse
import pytest
from unittest import mock
@@ -25,6 +24,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.appsflyer.
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.appsflyer.settings import APPSFLYER_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.appsflyer.source import AppsFlyerSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ DriveResult,
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.appsflyer import (
+ AppsFlyerSourceConfig,
+)
_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.appsflyer.appsflyer"
@@ -83,11 +93,22 @@ def _serve(text: str = _CSV, status: int = 200):
return lambda *args, **kwargs: _response(text, status)
-def _requested_windows(mock_session: mock.MagicMock) -> list[tuple[date, date]]:
+def _driver() -> SourceDriver:
+ return SourceDriver(AppsFlyerSource(), AppsFlyerSourceConfig(app_id="id123", api_token="token"))
+
+
+def _csv_response(body: str = _CSV) -> ScriptedResponse:
+ return ScriptedResponse(body=body.encode())
+
+
+def _requested_windows(result: DriveResult) -> list[tuple[date, date]]:
windows = []
- for call in mock_session.return_value.get.call_args_list:
- query = parse_qs(urlparse(call.args[0]).query)
- windows.append((date.fromisoformat(query["from"][0]), date.fromisoformat(query["to"][0])))
+ for request in result.requests:
+ start = request.param("from")
+ end = request.param("to")
+ assert start is not None
+ assert end is not None
+ windows.append((date.fromisoformat(start), date.fromisoformat(end)))
return windows
@@ -141,11 +162,11 @@ class TestHelpers:
class TestValidateCredentials:
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_validate_credentials_succeeds_on_200(self, mock_session):
- mock_session.return_value.get.return_value = _response("", status=200)
+ def test_validate_credentials_succeeds_on_200(self) -> None:
+ with scripted_network([ScriptedResponse(status=200)]) as network:
+ assert validate_credentials("token", "id123") is True
- assert validate_credentials("token", "id123") is True
+ assert len(network.requests_log) == 1
@pytest.mark.parametrize(
"status_code, expected_substring",
@@ -156,38 +177,34 @@ class TestValidateCredentials:
(404, "app id"),
],
)
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_validate_credentials_distinguishes_token_from_app_id(self, mock_session, status_code, expected_substring):
- mock_session.return_value.get.return_value = _response("", status=status_code)
-
- with pytest.raises(AppsFlyerCredentialsError) as exc:
- validate_credentials("token", "id123")
+ def test_validate_credentials_distinguishes_token_from_app_id(
+ self, status_code: int, expected_substring: str
+ ) -> None:
+ with scripted_network([ScriptedResponse(status=status_code)]):
+ with pytest.raises(AppsFlyerCredentialsError) as exc:
+ validate_credentials("token", "id123")
assert expected_substring in str(exc.value)
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_validate_rejects_bad_app_id_without_request(self, mock_session):
- with pytest.raises(AppsFlyerCredentialsError) as exc:
- validate_credentials("token", "bad app!")
+ def test_validate_rejects_bad_app_id_without_request(self) -> None:
+ with scripted_network([]) as network:
+ with pytest.raises(AppsFlyerCredentialsError) as exc:
+ validate_credentials("token", "bad app!")
assert "app id" in str(exc.value)
- mock_session.return_value.get.assert_not_called()
+ assert network.requests_log == []
@pytest.mark.parametrize("status_code", [400, 418, 451])
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_validate_raises_with_status_on_unexpected_code(self, mock_session, status_code):
- mock_session.return_value.get.return_value = _response("", status=status_code)
-
- with pytest.raises(AppsFlyerCredentialsError) as exc:
- validate_credentials("token", "id123")
+ def test_validate_raises_with_status_on_unexpected_code(self, status_code: int) -> None:
+ with scripted_network([ScriptedResponse(status=status_code)]):
+ with pytest.raises(AppsFlyerCredentialsError) as exc:
+ validate_credentials("token", "id123")
assert str(status_code) in str(exc.value)
@pytest.mark.parametrize("status_code", [429, 500, 503])
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_validate_raises_on_transient_status(self, mock_session, status_code):
+ def test_validate_raises_on_transient_status(self, status_code: int) -> None:
# Rate-limit / 5xx are transient; the caller must be able to tell them from a bad token.
- mock_session.return_value.get.return_value = _response("", status=status_code)
-
- with pytest.raises(AppsFlyerRetryableError):
- validate_credentials("token", "id123")
+ with scripted_network(always(ScriptedResponse(status=status_code))):
+ with pytest.raises(AppsFlyerRetryableError):
+ validate_credentials("token", "id123")
class TestGetRows:
@@ -215,68 +232,57 @@ class TestGetRows:
("master_report", "/api/master-agg-data/v4/app/id123"),
],
)
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_report_slug_matches_appsflyer_api(self, mock_session, endpoint, expected_path):
- mock_session.return_value.get.side_effect = _serve()
-
- list(get_rows("token", "id123", endpoint, mock.MagicMock()))
+ def test_report_slug_matches_appsflyer_api(self, endpoint: str, expected_path: str) -> None:
+ result = _driver().run(endpoint, always(_csv_response()))
- for call in mock_session.return_value.get.call_args_list:
- assert urlparse(call.args[0]).path == expected_path
+ assert result.raised is None
+ assert result.paths
+ assert all(path == expected_path for path in result.paths)
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_incremental_starts_at_watermark_minus_lookback(self, mock_session):
- mock_session.return_value.get.side_effect = _serve()
+ def test_incremental_starts_at_watermark_minus_lookback(self) -> None:
watermark = datetime.now(UTC).date()
- list(
- get_rows(
- "token",
- "id123",
- "daily_report",
- mock.MagicMock(),
- should_use_incremental_field=True,
- db_incremental_field_last_value=watermark,
- )
+ result = _driver().run(
+ "daily_report",
+ [_csv_response()],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
)
- url = mock_session.return_value.get.call_args.args[0]
- query = parse_qs(urlparse(url).query)
+ assert result.raised is None
expected_from = watermark.toordinal() - LOOKBACK_DAYS
- assert date.fromisoformat(query["from"][0]).toordinal() == expected_from
+ start = result.params("from")[0]
+ assert start is not None
+ assert date.fromisoformat(start).toordinal() == expected_from
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_rows_are_chunked(self, mock_session):
+ def test_rows_are_chunked(self) -> None:
header = "Date,Agency/PMD (af_prt),Media Source (pid),Campaign (c)\n"
body = "".join(f"2024-01-01,a,m,c{i}\n" for i in range(CHUNK_SIZE + 1))
- mock_session.return_value.get.side_effect = _serve(header + body)
- batches = list(get_rows("token", "id123", "daily_report", mock.MagicMock()))
+ result = _driver().run("daily_report", [_csv_response(header + body)])
- assert [len(batch) for batch in batches] == [CHUNK_SIZE, 1]
+ assert result.raised is None
+ assert [len(batch) for batch in result.items] == [CHUNK_SIZE, 1]
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_requests_csv_explicitly(self, mock_session):
- mock_session.return_value.get.side_effect = _serve()
-
- list(get_rows("token", "id123", "daily_report", mock.MagicMock()))
+ def test_requests_csv_explicitly(self) -> None:
+ result = _driver().run("daily_report", [_csv_response()])
- headers = mock_session.call_args.kwargs["headers"]
+ assert result.raised is None
+ headers = result.session_options[0]["headers"]
assert headers["Accept"] == "text/csv"
class TestRawAndMasterWindows:
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_raw_pull_walks_contiguous_windows_inside_the_lookback_limit(self, mock_session):
+ def test_raw_pull_walks_contiguous_windows_inside_the_lookback_limit(self) -> None:
# AppsFlyer refuses a raw window starting more than 90 days back, and the windows have to
# tile the range exactly once: a gap loses rows, an overlap re-merges them, and a window
# that doesn't advance loops forever.
- mock_session.return_value.get.side_effect = _serve()
today = datetime.now(UTC).date()
- list(get_rows("token", "id123", "installs", mock.MagicMock()))
+ result = _driver().run("installs", always(_csv_response()))
- windows = _requested_windows(mock_session)
+ assert result.raised is None
+ windows = _requested_windows(result)
assert windows[0][0] == today - timedelta(days=RAW_MAX_LOOKBACK_DAYS)
assert windows[-1][1] == today
for window_start, window_end in windows:
@@ -284,53 +290,46 @@ class TestRawAndMasterWindows:
for (_, previous_end), (next_start, _) in zip(windows, windows[1:]):
assert next_start == previous_end + timedelta(days=1)
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_master_pull_never_exceeds_the_31_day_call_limit(self, mock_session):
+ def test_master_pull_never_exceeds_the_31_day_call_limit(self) -> None:
# The Master API rejects a range wider than 31 days, so the backfill has to be windowed.
- mock_session.return_value.get.side_effect = _serve()
today = datetime.now(UTC).date()
- list(get_rows("token", "id123", "master_report", mock.MagicMock()))
+ result = _driver().run("master_report", always(_csv_response()))
- windows = _requested_windows(mock_session)
+ assert result.raised is None
+ windows = _requested_windows(result)
assert windows[0][0] == today - timedelta(days=MASTER_MAX_LOOKBACK_DAYS)
assert windows[-1][1] == today
for window_start, window_end in windows:
assert 0 <= (window_end - window_start).days < MASTER_MAX_REQUEST_DAYS
@pytest.mark.parametrize("endpoint", ["installs", "in_app_events", "ad_revenue"])
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_raw_incremental_repulls_a_whole_window_before_the_watermark(self, mock_session, endpoint):
+ def test_raw_incremental_repulls_a_whole_window_before_the_watermark(self, endpoint: str) -> None:
# A worker shutdown can interrupt a window part-way through, and AppsFlyer documents no row
# order within one, so the next run has to start far enough back to redo the whole window.
- mock_session.return_value.get.side_effect = _serve()
watermark = datetime.now(UTC).date() - timedelta(days=10)
- list(
- get_rows(
- "token",
- "id123",
- endpoint,
- mock.MagicMock(),
- should_use_incremental_field=True,
- db_incremental_field_last_value=watermark,
- )
+ result = _driver().run(
+ endpoint,
+ always(_csv_response()),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
)
- windows = _requested_windows(mock_session)
+ assert result.raised is None
+ windows = _requested_windows(result)
assert windows[0][0] == watermark - timedelta(days=RAW_LOOKBACK_DAYS)
assert RAW_LOOKBACK_DAYS >= RAW_MAX_REQUEST_DAYS
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_ad_revenue_pull_requests_its_monetization_dimensions(self, mock_session):
+ def test_ad_revenue_pull_requests_its_monetization_dimensions(self) -> None:
# monetization_network / ad_unit / placement are additional fields, and they make up the
# row key — without them every revenue row for a user collapses onto one key.
- mock_session.return_value.get.side_effect = _serve()
-
- list(get_rows("token", "id123", "ad_revenue", mock.MagicMock()))
+ result = _driver().run("ad_revenue", always(_csv_response()))
- query = parse_qs(urlparse(mock_session.return_value.get.call_args.args[0]).query)
- requested = set(query["additional_fields"][0].split(","))
+ assert result.raised is None
+ additional_fields = result.params("additional_fields")[0]
+ assert additional_fields is not None
+ requested = set(additional_fields.split(","))
assert {"monetization_network", "ad_unit", "placement"} <= requested
assert set(APPSFLYER_ENDPOINTS["ad_revenue"].primary_keys) - {"appsflyer_id", "event_time"} <= requested
@@ -343,27 +342,27 @@ class TestRawAndMasterWindows:
("post_attribution_installs", "detection_date"),
],
)
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_protect360_pull_requests_its_fraud_columns(self, mock_session, endpoint, expected_field):
+ def test_protect360_pull_requests_its_fraud_columns(self, endpoint: str, expected_field: str) -> None:
# The fraud classification is an additional field, so a report pulled without asking for it
# comes back saying nothing about why the row was blocked.
- mock_session.return_value.get.side_effect = _serve()
-
- list(get_rows("token", "id123", endpoint, mock.MagicMock()))
+ result = _driver().run(endpoint, always(_csv_response()))
- query = parse_qs(urlparse(mock_session.return_value.get.call_args.args[0]).query)
- assert expected_field in query["additional_fields"][0].split(",")
+ assert result.raised is None
+ additional_fields = result.params("additional_fields")[0]
+ assert additional_fields is not None
+ assert expected_field in additional_fields.split(",")
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_master_pull_sends_groupings_and_kpis(self, mock_session):
+ def test_master_pull_sends_groupings_and_kpis(self) -> None:
# The Master API rejects a request that omits either one.
- mock_session.return_value.get.side_effect = _serve()
+ result = _driver().run("master_report", always(_csv_response()))
- list(get_rows("token", "id123", "master_report", mock.MagicMock()))
-
- query = parse_qs(urlparse(mock_session.return_value.get.call_args.args[0]).query)
- assert "install_time" in query["groupings"][0].split(",")
- assert "installs" in query["kpis"][0].split(",")
+ assert result.raised is None
+ groupings = result.params("groupings")[0]
+ kpis = result.params("kpis")[0]
+ assert groupings is not None
+ assert kpis is not None
+ assert "install_time" in groupings.split(",")
+ assert "installs" in kpis.split(",")
@mock.patch(f"{_MODULE}.RAW_MAX_ROWS", 2)
@mock.patch(f"{_MODULE}.make_tracked_session")
@@ -376,15 +375,14 @@ class TestRawAndMasterWindows:
assert logger.warning.called
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_value_with_an_embedded_newline_survives_streaming(self, mock_session):
+ def test_value_with_an_embedded_newline_survives_streaming(self) -> None:
# Raw event values carry newlines; splitting the body into lines would tear the row apart.
csv_body = 'AppsFlyer ID,Event Time,Event Value\naf-1,2024-01-01 00:00:00,"line one\nline two"\n'
- mock_session.return_value.get.side_effect = _serve(csv_body)
- rows = [row for batch in get_rows("token", "id123", "installs", mock.MagicMock()) for row in batch]
+ result = _driver().run("installs", always(_csv_response(csv_body)))
- assert rows[0] == {
+ assert result.raised is None
+ assert result.rows[0] == {
"appsflyer_id": "af-1",
"event_time": "2024-01-01 00:00:00",
"event_value": "line one\nline two",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/tests/test_appstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/tests/test_appstack.py
index 45bb4c26f2da..a15e3dd770be 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/tests/test_appstack.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appstack/tests/test_appstack.py
@@ -2,7 +2,6 @@ from datetime import UTC, date, datetime
from typing import Any
import pytest
-from unittest.mock import MagicMock, patch
from parameterized import parameterized
from requests.exceptions import HTTPError
@@ -11,11 +10,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.appstack.a
AppstackResumeConfig,
_export_window_start,
_to_unix_seconds,
- appstack_source,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.appstack.settings import PAGE_SIZE
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.appstack.source import AppstackSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.appstack import (
+ AppstackSourceConfig,
+)
class TestToUnixSeconds:
@@ -52,119 +59,94 @@ class TestExportWindowStart:
class TestAppstackSource:
- def _manager(self, *, can_resume: bool, state: AppstackResumeConfig | None = None) -> MagicMock:
- manager = MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = can_resume
- manager.load_state.return_value = state
- return manager
-
- def _call(self, manager: MagicMock, **kwargs: Any) -> Any:
- defaults: dict[str, Any] = {
- "api_key": "key",
- "endpoint": "events",
- "team_id": 1,
- "job_id": "job",
- "resumable_source_manager": manager,
- "db_incremental_field_last_value": None,
- "should_use_incremental_field": False,
- }
- defaults.update(kwargs)
- return appstack_source(**defaults)
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.rest_api_resource")
- def test_paginator_never_trusts_total_count(self, mock_rest: MagicMock) -> None:
+ @staticmethod
+ def _driver() -> SourceDriver:
+ return SourceDriver(AppstackSource(), AppstackSourceConfig(api_key="key"))
+
+ @staticmethod
+ def _page(rows: list[dict[str, Any]]) -> ScriptedResponse:
+ return ScriptedResponse(json={"data": rows, "total_count": len(rows)})
+
+ def test_paginator_never_trusts_total_count(self) -> None:
# Appstack's `total_count` counts the current page, not the whole window; a paginator
# reading it as a grand total would stop after the first page and silently truncate.
- mock_rest.return_value = MagicMock(name="events", column_hints=None)
-
- self._call(self._manager(can_resume=False))
+ result = self._driver().run(
+ "events",
+ [self._page([{"event_id": str(index)} for index in range(PAGE_SIZE)]), self._page([{"event_id": "last"}])],
+ )
- paginator = mock_rest.call_args.args[0]["client"]["paginator"]
- assert paginator.total_path is None
- assert paginator.limit == PAGE_SIZE
+ assert result.raised is None
+ assert result.params("offset") == ["0", str(PAGE_SIZE)]
+ assert result.params("limit") == [str(PAGE_SIZE), str(PAGE_SIZE)]
+ assert len(result.rows) == PAGE_SIZE + 1
+ assert result.rows[-1]["event_id"] == "last"
- @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.make_tracked_session")
- @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.rest_api_resource")
- def test_client_session_disables_sample_capture(self, mock_rest: MagicMock, mock_session: MagicMock) -> None:
+ def test_client_session_disables_sample_capture(self) -> None:
# Export rows carry device/user identifiers the sample scrubbers can't recognise; the client
# must run on a capture=False session so response bodies stay out of shared sample storage.
- mock_rest.return_value = MagicMock(name="events", column_hints=None)
+ result = self._driver().run("events", [self._page([{"event_id": "one"}])])
- self._call(self._manager(can_resume=False))
+ assert result.raised is None
+ assert result.rows[0]["event_id"] == "one"
+ assert result.session_options[0]["capture"] is False
- assert mock_session.call_args.kwargs["capture"] is False
- assert mock_rest.call_args.args[0]["client"]["session"] is mock_session.return_value
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.rest_api_resource")
- def test_resume_replays_pinned_window_at_saved_offset(self, mock_rest: MagicMock) -> None:
+ def test_resume_replays_pinned_window_at_saved_offset(self) -> None:
# Offsets are positions within one export window: a resumed attempt must reuse the saved
# window's `timestamp`, not re-derive it from a watermark that advanced mid-walk.
- mock_rest.return_value = MagicMock(name="events", column_hints=None)
- manager = self._manager(can_resume=True, state=AppstackResumeConfig(offset=30000, window_start=1772593094))
-
- self._call(
- manager,
+ result = self._driver().run(
+ "events",
+ [self._page([{"event_id": "resumed"}])],
+ resume_state=AppstackResumeConfig(offset=30000, window_start=1772593094),
should_use_incremental_field=True,
db_incremental_field_last_value=datetime(2026, 6, 1, tzinfo=UTC),
)
- config = mock_rest.call_args.args[0]
- params = config["resources"][0]["endpoint"]["params"]
- assert params["timestamp"] == 1772593094
- assert mock_rest.call_args.kwargs["initial_paginator_state"] == {"offset": 30000}
-
- @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.rest_api_resource")
- def test_resume_hook_saves_offset_with_window(self, mock_rest: MagicMock) -> None:
- mock_rest.return_value = MagicMock(name="events", column_hints=None)
- manager = self._manager(can_resume=False)
-
- self._call(
- manager,
+ assert result.raised is None
+ assert result.params("timestamp") == ["1772593094"]
+ assert result.params("offset") == ["30000"]
+ assert result.rows[0]["event_id"] == "resumed"
+
+ def test_resume_hook_saves_offset_with_window(self) -> None:
+ result = self._driver().run(
+ "events",
+ [
+ self._page([{"event_id": str(index)} for index in range(PAGE_SIZE)]),
+ self._page([{"event_id": str(index)} for index in range(PAGE_SIZE, PAGE_SIZE * 2)]),
+ self._page([{"event_id": "last"}]),
+ ],
should_use_incremental_field=True,
db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
)
- resume_hook = mock_rest.call_args.kwargs["resume_hook"]
-
- # A page with a next offset persists the checkpoint together with its window.
- resume_hook({"offset": 20000})
- manager.save_state.assert_called_once_with(AppstackResumeConfig(offset=20000, window_start=1772593094))
-
- # A terminal page (no resume state) saves nothing.
- manager.save_state.reset_mock()
- resume_hook(None)
- manager.save_state.assert_not_called()
+ # Pages with a next offset save checkpoints. The terminal page saves none.
+ assert result.raised is None
+ assert result.params("offset") == ["0", str(PAGE_SIZE), str(PAGE_SIZE * 2)]
+ assert result.saved_states == [
+ AppstackResumeConfig(offset=PAGE_SIZE, window_start=1772593094),
+ AppstackResumeConfig(offset=PAGE_SIZE * 2, window_start=1772593094),
+ ]
class TestValidateCredentials:
@parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
- @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.make_tracked_session")
- def test_status_mapping(self, _label: str, status_code: int, expected: bool, mock_session: MagicMock) -> None:
- response = MagicMock()
- response.status_code = status_code
- mock_session.return_value.get.return_value = response
+ def test_status_mapping(self, _label: str, status_code: int, expected: bool) -> None:
+ with scripted_network([ScriptedResponse(status=status_code)]) as network:
+ assert validate_credentials("key") is expected
- assert validate_credentials("key") is expected
+ assert network.requests_log[0].path == "/api/v1/export"
+ assert network.requests_log[0].param("limit") == "1"
+ assert network.requests_log[0].headers["authorization"] == "key"
@parameterized.expand([("rate_limited", 429), ("server_error", 503)])
- @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.make_tracked_session")
- def test_transient_errors_raise(self, _label: str, status_code: int, mock_session: MagicMock) -> None:
+ def test_transient_errors_raise(self, _label: str, status_code: int) -> None:
# Transient/unexpected statuses must not be reported as an invalid API key — they raise.
- response = MagicMock()
- response.status_code = status_code
- response.raise_for_status.side_effect = HTTPError
- mock_session.return_value.get.return_value = response
-
- with pytest.raises(HTTPError):
- validate_credentials("key")
+ with scripted_network(always(ScriptedResponse(status=status_code))):
+ with pytest.raises(HTTPError):
+ validate_credentials("key")
- @patch("products.warehouse_sources.backend.temporal.data_imports.sources.appstack.appstack.make_tracked_session")
- def test_probe_disables_sample_capture(self, mock_session: MagicMock) -> None:
+ def test_probe_disables_sample_capture(self) -> None:
# The probe hits the same export endpoint, so its response body must not be captured either.
- response = MagicMock()
- response.status_code = 200
- mock_session.return_value.get.return_value = response
-
- validate_credentials("the-key")
+ with scripted_network([ScriptedResponse()]) as network:
+ assert validate_credentials("the-key") is True
- assert mock_session.call_args.kwargs["capture"] is False
+ assert network.session_options[0]["capture"] is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/arcade/tests/test_arcade.py b/products/warehouse_sources/backend/temporal/data_imports/sources/arcade/tests/test_arcade.py
index ae3fbd5d7757..cf13bafeeb04 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/arcade/tests/test_arcade.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/arcade/tests/test_arcade.py
@@ -1,16 +1,11 @@
-import json
-from collections.abc import Iterable, Iterator
-from typing import Any, cast
+from collections.abc import Iterator
+from typing import Any
import pytest
import time_machine
-from unittest.mock import MagicMock, patch
-
-from requests import PreparedRequest, Response, Session
from products.warehouse_sources.backend.temporal.data_imports.sources.arcade.arcade import (
ArcadeResumeConfig,
- arcade_source,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.arcade.settings import (
@@ -21,9 +16,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.arcade.set
PROVISIONING_ERROR,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.arcade.source import ArcadeSource
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.safe_point import activate_safe_point
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.arcade import ArcadeSourceConfig
@@ -32,87 +29,53 @@ def config() -> ArcadeSourceConfig:
return ArcadeSourceConfig(api_key="fake-arcade-key", team_id="team-example", start_date="2025-01-01")
-def manager() -> MagicMock:
- result = MagicMock(spec=ResumableSourceManager)
- result.can_resume.return_value = False
- return result
-
-
-def transport() -> Iterator[MagicMock]:
- with (
- Session() as session,
- patch.object(session, "send") as send,
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session",
- return_value=session,
- ),
- patch("time.sleep"),
- time_machine.travel("2025-02-01T00:00:00Z", tick=False),
- ):
- yield send
-
-
-def response(body: object, status: int = 200) -> Response:
- result = Response()
- result.status_code = status
- result.url = "https://api.arcade.software/insights"
- result.headers["Content-Type"] = "application/json"
- result._content = json.dumps(body).encode()
- return result
-
-
-def body(request: PreparedRequest) -> dict[str, Any]:
- assert isinstance(request.body, str | bytes)
- return json.loads(request.body)
-
-
-def sync_items(source: SourceResponse) -> Iterable[list[dict[str, Any]]]:
- return cast(Iterable[list[dict[str, Any]]], source.items())
[email protected](autouse=True)
+def fixed_time() -> Iterator[None]:
+ with time_machine.travel("2025-02-01T00:00:00Z", tick=False):
+ yield
@pytest.mark.parametrize("resume_page", [None, 3])
-def test_flow_pages_and_resume(
- config: ArcadeSourceConfig, manager: MagicMock, transport: MagicMock, resume_page: int | None
-) -> None:
- if resume_page:
- manager.can_resume.return_value = True
- manager.load_state.return_value = ArcadeResumeConfig(
+def test_flow_pages_and_resume(config: ArcadeSourceConfig, resume_page: int | None) -> None:
+ resume_state = (
+ ArcadeResumeConfig(
page=resume_page, period_start="2025-01-01T00:00:00+00:00", period_end="2025-01-31T00:00:00+00:00"
)
- transport.side_effect = [
- response([{"flowId": "flow-one", "plays": 7}]),
- response([{"flowId": "flow-two", "plays": 9}]),
- response([]),
- ]
- source = arcade_source(config, "flow_engagement", 1, "job-example", manager)
- with activate_safe_point(lambda: None, covers_framework_checkpoints=True):
- pages = iter(sync_items(source))
- first = next(pages)
- assert manager.save_state.call_args.args[0].page == (resume_page or 1) + 1
- remaining = list(pages)
- rows = first + [row for page in remaining for row in page]
- assert [row["flowId"] for row in rows] == ["flow-one", "flow-two"]
- assert all(row["team_id"] == "team-example" for row in rows)
- requests = [call.args[0] for call in transport.call_args_list]
+ if resume_page
+ else None
+ )
+ result = SourceDriver(ArcadeSource(), config).run(
+ "flow_engagement",
+ [
+ ScriptedResponse(json=[{"flowId": "flow-one", "plays": 7}]),
+ ScriptedResponse(json=[{"flowId": "flow-two", "plays": 9}]),
+ ScriptedResponse(json=[]),
+ ],
+ resume_state=resume_state,
+ )
+
+ assert result.raised is None
+ assert [row["flowId"] for row in result.rows] == ["flow-one", "flow-two"]
+ assert all(row["team_id"] == "team-example" for row in result.rows)
start_page = resume_page or 1
- assert [body(request)["page"] for request in requests] == list(range(start_page, start_page + 3))
expected_end = "2025-01-31T00:00:00+00:00" if resume_page else "2025-02-01T00:00:00+00:00"
- for request in requests:
+ assert [request.json()["page"] for request in result.requests] == list(range(start_page, start_page + 3))
+ for request in result.requests:
assert request.method == "POST"
assert request.url == "https://api.arcade.software/insights"
- assert request.headers["Authorization"] == "fake-arcade-key"
- assert body(request) == {
+ assert request.headers["authorization"] == "fake-arcade-key"
+ assert request.json() == {
"type": "overviewPlays",
"teamId": "team-example",
- "page": body(request)["page"],
+ "page": request.json()["page"],
"size": 100,
"from": "2025-01-01T00:00:00+00:00",
"to": expected_end,
}
- assert rows[0]["period_end"] == expected_end
- assert manager.save_state.call_args.args[0].completed
+ assert result.rows[0]["period_end"] == expected_end
+ assert result.saved_states[0].page == start_page + 1
+ assert result.committed_states[0].page == start_page + 1
+ assert result.saved_states[-1].completed
@pytest.mark.parametrize(
@@ -132,8 +95,6 @@ def test_flow_pages_and_resume(
)
def test_single_page_tables(
config: ArcadeSourceConfig,
- manager: MagicMock,
- transport: MagicMock,
name: str,
payload: object,
expected_rows: list[dict[str, Any]],
@@ -141,28 +102,32 @@ def test_single_page_tables(
path: str,
expected_body: dict[str, str] | None,
) -> None:
- transport.return_value = response(payload)
- source = arcade_source(config, name, 1, "job-example", manager)
- assert [row for page in sync_items(source) for row in page] == expected_rows
- transport.assert_called_once()
- request = transport.call_args.args[0]
+ result = SourceDriver(ArcadeSource(), config).run(name, [ScriptedResponse(json=payload)])
+
+ assert result.raised is None
+ assert result.rows == expected_rows
+ assert len(result.requests) == 1
+ request = result.requests[0]
assert request.method == method
assert request.url == f"https://api.arcade.software/{path}"
- assert request.headers["Authorization"] == "fake-arcade-key"
- assert (body(request) if request.body else None) == expected_body
- assert manager.save_state.call_args.args[0].completed
+ assert request.headers["authorization"] == "fake-arcade-key"
+ assert request.json() == expected_body
+ assert result.saved_states[-1].completed
@pytest.mark.parametrize("name", ["teams", "flow_engagement"])
-def test_completed_resume_does_not_repeat_rows(
- config: ArcadeSourceConfig, manager: MagicMock, transport: MagicMock, name: str
-) -> None:
- manager.can_resume.return_value = True
- manager.load_state.return_value = ArcadeResumeConfig(
- page=1, period_start="2025-01-01T00:00:00+00:00", period_end="2025-01-31T00:00:00+00:00", completed=True
+def test_completed_resume_does_not_repeat_rows(config: ArcadeSourceConfig, name: str) -> None:
+ result = SourceDriver(ArcadeSource(), config).run(
+ name,
+ [],
+ resume_state=ArcadeResumeConfig(
+ page=1, period_start="2025-01-01T00:00:00+00:00", period_end="2025-01-31T00:00:00+00:00", completed=True
+ ),
)
- assert list(sync_items(arcade_source(config, name, 1, "job-example", manager))) == []
- transport.assert_not_called()
+
+ assert result.raised is None
+ assert result.items == []
+ assert result.requests == []
@pytest.mark.parametrize(
@@ -176,65 +141,74 @@ def test_completed_resume_does_not_repeat_rows(
(403, "Forbidden", PERMISSION_ERROR),
],
)
-def test_auth_error_mapping(
- config: ArcadeSourceConfig, manager: MagicMock, transport: MagicMock, status: int, error: str, message: str
-) -> None:
- transport.return_value = response({"error": error}, status)
- assert validate_credentials(config, 1, "teams") == (False, message)
- transport.assert_called_once()
- with pytest.raises(ValueError) as raised:
- list(sync_items(arcade_source(config, "teams", 1, "job-example", manager)))
- assert str(raised.value) == message
- assert ArcadeSource().get_non_retryable_errors()[str(raised.value)] == message
- assert transport.call_count == 2
+def test_auth_error_mapping(config: ArcadeSourceConfig, status: int, error: str, message: str) -> None:
+ answer = ScriptedResponse(status=status, json={"error": error})
+ with scripted_network([answer]) as network:
+ assert validate_credentials(config, 1, "teams") == (False, message)
+ assert len(network.requests_log) == 1
+
+ result = SourceDriver(ArcadeSource(), config).run("teams", [answer])
+ assert isinstance(result.raised, ValueError)
+ assert str(result.raised) == message
+ assert ArcadeSource().get_non_retryable_errors()[str(result.raised)] == message
+ assert len(result.requests) == 1
@pytest.mark.parametrize("status", [401, 403])
-def test_create_accepts_missing_scope(config: ArcadeSourceConfig, transport: MagicMock, status: int) -> None:
- transport.return_value = response({"error": "This operation requires provisioning scope"}, status)
- valid, _ = validate_credentials(config, 1, None)
+def test_create_accepts_missing_scope(config: ArcadeSourceConfig, status: int) -> None:
+ with scripted_network(
+ [ScriptedResponse(status=status, json={"error": "This operation requires provisioning scope"})]
+ ) as network:
+ valid, _ = validate_credentials(config, 1, None)
+
assert valid == (status == 403)
- transport.assert_called_once()
+ assert len(network.requests_log) == 1
@pytest.mark.parametrize("status", [429, 500, 503])
-def test_transient_errors_retry(
- config: ArcadeSourceConfig, manager: MagicMock, transport: MagicMock, status: int
-) -> None:
- transport.side_effect = [response({"error": "Temporary failure"}, status), response({"teams": []})]
- assert list(sync_items(arcade_source(config, "teams", 1, "job-example", manager))) == []
- assert transport.call_count == 2
+def test_transient_errors_retry(config: ArcadeSourceConfig, status: int) -> None:
+ result = SourceDriver(ArcadeSource(), config).run(
+ "teams",
+ [ScriptedResponse(status=status, json={"error": "Temporary failure"}), ScriptedResponse(json={"teams": []})],
+ )
+
+ assert result.raised is None
+ assert result.rows == []
+ assert len(result.requests) == 2
@pytest.mark.parametrize("start_date", ["not-a-date", "2025-02-30", "2026-01-01"])
-def test_invalid_dates_do_not_send_requests(config: ArcadeSourceConfig, transport: MagicMock, start_date: str) -> None:
+def test_invalid_dates_do_not_send_requests(config: ArcadeSourceConfig, start_date: str) -> None:
config.start_date = start_date
- valid, message = validate_credentials(config, 1, None)
+ with scripted_network([]) as network:
+ valid, message = validate_credentials(config, 1, None)
+
assert not valid
assert message and "date" in message
- transport.assert_not_called()
+ assert network.requests_log == []
-def test_unknown_table_does_not_send_requests(
- config: ArcadeSourceConfig, manager: MagicMock, transport: MagicMock
-) -> None:
- assert validate_credentials(config, 1, "unknown")[0] is False
- with pytest.raises(ValueError, match="Unknown Arcade table"):
- arcade_source(config, "unknown", 1, "job-example", manager)
- transport.assert_not_called()
+def test_unknown_table_does_not_send_requests(config: ArcadeSourceConfig) -> None:
+ with scripted_network([]) as network:
+ assert validate_credentials(config, 1, "unknown")[0] is False
+ result = SourceDriver(ArcadeSource(), config).run("unknown", [])
+ assert isinstance(result.raised, ValueError)
+ assert "Unknown Arcade table" in str(result.raised)
+ assert network.requests_log == []
+ assert result.requests == []
-def test_validation_uses_one_small_insights_page(config: ArcadeSourceConfig, transport: MagicMock) -> None:
- transport.return_value = response([{"flowId": "flow-one"}])
- assert validate_credentials(config, 1, "flow_engagement") == (True, None)
- transport.assert_called_once()
- assert body(transport.call_args.args[0])["size"] == 1
+def test_validation_uses_one_small_insights_page(config: ArcadeSourceConfig) -> None:
+ with scripted_network([ScriptedResponse(json=[{"flowId": "flow-one"}])]) as network:
+ assert validate_credentials(config, 1, "flow_engagement") == (True, None)
-def test_missing_list_fails_instead_of_deleting_rows(
- config: ArcadeSourceConfig, manager: MagicMock, transport: MagicMock
-) -> None:
- transport.return_value = response({"unexpected": []})
- with pytest.raises(ValueError):
- list(sync_items(arcade_source(config, "teams", 1, "job-example", manager)))
- manager.save_state.assert_not_called()
+ assert len(network.requests_log) == 1
+ assert network.requests_log[0].json()["size"] == 1
+
+
+def test_missing_list_fails_instead_of_deleting_rows(config: ArcadeSourceConfig) -> None:
+ result = SourceDriver(ArcadeSource(), config).run("teams", [ScriptedResponse(json={"unexpected": []})])
+
+ assert isinstance(result.raised, ValueError)
+ assert result.saved_states == []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/tests/test_asaas.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/tests/test_asaas.py
index b7d372ffbbe2..bb8b00d16544 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/tests/test_asaas.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asaas/tests/test_asaas.py
@@ -1,5 +1,5 @@
from datetime import UTC, date, datetime
-from typing import cast
+from typing import Any, Literal, cast
from unittest import mock
@@ -9,7 +9,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.asaas.asaa
PRODUCTION_BASE_URL,
SANDBOX_BASE_URL,
AsaasResumeConfig,
- asaas_source,
base_url,
format_date_param,
get_resource,
@@ -17,7 +16,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.asaas.asaa
)
from products.warehouse_sources.backend.temporal.data_imports.sources.asaas.source import AsaasSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpoint
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.asaas import AsaasSourceConfig
_INCREMENTAL_ENDPOINTS = {"Payments", "Transfers"}
@@ -27,10 +30,14 @@ VALIDATE_PATCH = (
"products.warehouse_sources.backend.temporal.data_imports.sources.asaas.source.validate_asaas_credentials"
)
ASAAS_SOURCE_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.asaas.source.asaas_source"
-REST_API_RESOURCE_PATCH = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.asaas.asaas.rest_api_resource"
-)
-SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.asaas.asaas.make_tracked_session"
+
+
+def _driver(environment: Literal["production", "sandbox"] = "production") -> SourceDriver:
+ return SourceDriver(AsaasSource(), AsaasSourceConfig(api_key="test-key", environment=environment))
+
+
+def _page(rows: list[dict[str, Any]], total: int) -> ScriptedResponse:
+ return ScriptedResponse(json={"data": rows, "hasMore": len(rows) == 100, "totalCount": total})
class TestBaseUrl:
@@ -93,86 +100,56 @@ class TestGetResource:
class TestAsaasSourceResumeBehavior:
"""`asaas_source` plumbing: resume seeding and checkpoint persistence."""
- def _run(self, manager: mock.MagicMock, *, should_use_incremental_field: bool = False):
- with mock.patch(REST_API_RESOURCE_PATCH) as mock_rest_api_resource:
- mock_rest_api_resource.return_value = mock.MagicMock(name="Payments")
- asaas_source(
- api_key="test-key",
- environment="production",
- endpoint="Payments",
- team_id=123,
- job_id="job-1",
- resumable_source_manager=manager,
- db_incremental_field_last_value=None,
- should_use_incremental_field=should_use_incremental_field,
- )
- return mock_rest_api_resource
-
def test_does_not_load_state_when_cannot_resume(self) -> None:
- manager = mock.MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = False
-
- mock_rest_api_resource = self._run(manager)
+ result = _driver().run("Payments", [_page([{"id": "payment-1"}], 1)])
- manager.load_state.assert_not_called()
- assert mock_rest_api_resource.call_args.kwargs["initial_paginator_state"] is None
+ assert result.raised is None
+ assert result.params("offset") == ["0"]
def test_seeds_initial_offset_from_saved_state(self) -> None:
- manager = mock.MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = True
- manager.load_state.return_value = AsaasResumeConfig(offset=200)
+ result = _driver().run(
+ "Payments", [_page([{"id": "payment-201"}], 201)], resume_state=AsaasResumeConfig(offset=200)
+ )
- mock_rest_api_resource = self._run(manager)
-
- assert mock_rest_api_resource.call_args.kwargs["initial_paginator_state"] == {"offset": 200}
+ assert result.raised is None
+ assert result.params("offset") == ["200"]
def test_resume_hook_saves_offset_when_present(self) -> None:
- manager = mock.MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = False
-
- mock_rest_api_resource = self._run(manager)
- resume_hook = mock_rest_api_resource.call_args.kwargs["resume_hook"]
-
- resume_hook({"offset": 300})
-
- manager.save_state.assert_called_once_with(AsaasResumeConfig(offset=300))
+ result = _driver().run(
+ "Payments",
+ [
+ _page([{"id": f"payment-{index}"} for index in range(200, 300)], 301),
+ _page([{"id": "payment-300"}], 301),
+ ],
+ resume_state=AsaasResumeConfig(offset=200),
+ )
+
+ assert result.raised is None
+ assert result.params("offset") == ["200", "300"]
+ assert result.saved_states == [AsaasResumeConfig(offset=300)]
+ assert result.committed_states == [AsaasResumeConfig(offset=300)]
@parameterized.expand([("production", PRODUCTION_BASE_URL), ("sandbox", SANDBOX_BASE_URL)])
- def test_client_config_targets_the_selected_environment(self, environment: str, expected_base_url: str) -> None:
- manager = mock.MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = False
-
- with mock.patch(REST_API_RESOURCE_PATCH) as mock_rest_api_resource:
- mock_rest_api_resource.return_value = mock.MagicMock()
- asaas_source(
- api_key="test-key",
- environment=environment,
- endpoint="Payments",
- team_id=123,
- job_id="job-1",
- resumable_source_manager=manager,
- db_incremental_field_last_value=None,
- )
- config = mock_rest_api_resource.call_args.args[0]
- assert config["client"]["base_url"] == expected_base_url
- assert config["client"]["auth"] == {
- "type": "api_key",
- "name": "access_token",
- "api_key": "test-key",
- "location": "header",
- }
+ def test_client_config_targets_the_selected_environment(
+ self, environment: Literal["production", "sandbox"], expected_base_url: str
+ ) -> None:
+ result = _driver(environment).run("Payments", [_page([{"id": "payment-1"}], 1)])
+
+ assert result.raised is None
+ assert result.urls[0].startswith(f"{expected_base_url}/v3/payments?")
+ assert result.requests[0].headers["access_token"] == "test-key"
class TestValidateCredentials:
@parameterized.expand([(200, True), (401, False), (403, False)])
def test_status_code_maps_to_validity(self, status_code: int, expected: bool) -> None:
- with mock.patch(SESSION_PATCH) as mock_make_session:
- mock_response = mock.MagicMock()
- mock_response.status_code = status_code
- mock_make_session.return_value.get.return_value = mock_response
-
+ with scripted_network([ScriptedResponse(status=status_code)]) as network:
assert validate_credentials("test-key", "production") is expected
+ assert network.requests_log[0].path == "/v3/customers"
+ assert network.requests_log[0].param("limit") == "1"
+ assert network.requests_log[0].headers["access_token"] == "test-key"
+
class TestAsaasSource:
def setup_method(self) -> None:
@@ -194,22 +171,17 @@ class TestAsaasSource:
mock_validate.assert_called_once_with("test-key", "production")
def test_source_for_pipeline_plumbs_arguments(self) -> None:
- inputs = mock.MagicMock()
- inputs.schema_name = "Payments"
- inputs.should_use_incremental_field = True
- inputs.db_incremental_field_last_value = "2026-01-01"
- manager = mock.MagicMock()
-
- with mock.patch(ASAAS_SOURCE_PATCH) as mock_asaas_source:
- self.source.source_for_pipeline(self.config, manager, inputs)
-
- mock_asaas_source.assert_called_once()
- kwargs = mock_asaas_source.call_args.kwargs
- assert kwargs["api_key"] == "test-key"
- assert kwargs["environment"] == "production"
- assert kwargs["endpoint"] == "Payments"
- assert kwargs["resumable_source_manager"] is manager
- assert kwargs["db_incremental_field_last_value"] == "2026-01-01"
+ result = _driver().run(
+ "Payments",
+ [_page([{"id": "payment-1", "dateCreated": "2026-01-01"}], 1)],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01",
+ )
+
+ assert result.raised is None
+ assert result.paths == ["/v3/payments"]
+ assert result.requests[0].headers["access_token"] == "test-key"
+ assert result.requests[0].param("dateCreated[ge]") == "2026-01-01"
def test_source_for_pipeline_omits_cursor_when_not_incremental(self) -> None:
inputs = mock.MagicMock()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asana/tests/test_asana.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asana/tests/test_asana.py
index 16390ef737ba..74f08cc9cafe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/asana/tests/test_asana.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asana/tests/test_asana.py
@@ -1,174 +1,120 @@
-import json
-from typing import Any, Optional
+from typing import Any
import pytest
-from unittest import mock
-
-from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.asana.asana import (
ASANA_BASE_URL,
AsanaResumeConfig,
- asana_source,
validate_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.asana.settings import ASANA_ENDPOINTS, ENDPOINTS
-
-# RESTClient builds its session via make_tracked_session in the rest_client module.
-CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
-# validate_credentials builds its own tracked session in the asana module.
-ASANA_SESSION_PATCH = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.asana.asana.make_tracked_session"
+from products.warehouse_sources.backend.temporal.data_imports.sources.asana.settings import (
+ ASANA_ENDPOINTS,
+ ENDPOINTS,
+ AsanaEndpointConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.asana.source import AsanaSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.asana import AsanaSourceConfig
-def _page(items: list[dict[str, Any]], next_uri: Optional[str] = None) -> Response:
- body: dict[str, Any] = {"data": items, "next_page": {"uri": next_uri, "offset": "tok"} if next_uri else None}
- resp = Response()
- resp.status_code = 200
- resp._content = json.dumps(body).encode()
- return resp
-
-
-def _make_manager(resume_state: Optional[AsanaResumeConfig] = None) -> mock.MagicMock:
- manager = mock.MagicMock()
- manager.can_resume.return_value = resume_state is not None
- manager.load_state.return_value = resume_state
- return manager
-
-
-def _wire(session: mock.MagicMock, routes: list[tuple[str, Response]]) -> list[str]:
- """Wire a mock session that dispatches each request to the first still-unconsumed route whose
- substring appears in the fully-prepared URL. Returns the list of URLs sent, in order.
-
- Real ``Request.prepare()`` builds the URL (merging path-embedded query with the params dict and
- applying Bearer auth) so fan-out over parents and multi-page pagination route deterministically.
- """
- session.headers = {}
- sent_urls: list[str] = []
- remaining = list(routes)
-
- def _prepare(request: Any) -> Any:
- return request.prepare()
-
- def _send(prepared: Any, **kwargs: Any) -> Response:
- sent_urls.append(prepared.url)
- for i, (substr, response) in enumerate(remaining):
- if substr in prepared.url:
- remaining.pop(i)
- return response
- raise AssertionError(f"no route for {prepared.url}")
-
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = _send
- return sent_urls
-
-
-def _rows(source_response: Any) -> list[dict[str, Any]]:
- return [row for page in source_response.items() for row in page]
+def _page(items: list[dict[str, Any]], next_uri: str | None = None) -> ScriptedResponse:
+ return ScriptedResponse(json={"data": items, "next_page": {"uri": next_uri, "offset": "tok"} if next_uri else None})
-def _source(endpoint: str, manager: mock.MagicMock) -> Any:
- return asana_source("token", endpoint, team_id=1, job_id="j", resumable_source_manager=manager)
+def _driver() -> SourceDriver:
+ return SourceDriver(AsanaSource(), AsanaSourceConfig(access_token="token"))
class TestTopLevelPagination:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_paginates_via_next_page_uri_and_checkpoints(self, MockSession) -> None:
- session = MockSession.return_value
+ def test_paginates_via_next_page_uri_and_checkpoints(self) -> None:
next_uri = f"{ASANA_BASE_URL}/workspaces?offset=tok2"
- urls = _wire(
- session,
- [
- ("/workspaces?", _page([{"gid": "1"}, {"gid": "2"}], next_uri=next_uri)),
- ("offset=tok2", _page([{"gid": "3"}])),
- ],
+ result = _driver().run(
+ "workspaces",
+ [_page([{"gid": "1"}, {"gid": "2"}], next_uri=next_uri), _page([{"gid": "3"}])],
)
- manager = _make_manager()
- rows = _rows(_source("workspaces", manager))
-
- assert [r["gid"] for r in rows] == ["1", "2", "3"]
+ assert result.raised is None
+ assert [row["gid"] for row in result.rows] == ["1", "2", "3"]
# First request carries the page size and opted-in fields.
- assert "limit=100" in urls[0]
- assert "opt_fields=" in urls[0]
+ assert result.requests[0].param("limit") == "100"
+ assert result.requests[0].param("opt_fields") is not None
+ assert result.urls[1] == next_uri
# Checkpoint saved after the first page (points at the next link); the terminal page saves nothing.
- manager.save_state.assert_called_once()
- assert manager.save_state.call_args.args[0] == AsanaResumeConfig(paginator_state={"next_url": next_uri})
+ assert result.saved_states == [AsanaResumeConfig(paginator_state={"next_url": next_uri})]
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_resumes_from_saved_next_url(self, MockSession) -> None:
- session = MockSession.return_value
+ def test_resumes_from_saved_next_url(self) -> None:
resume_url = f"{ASANA_BASE_URL}/workspaces?offset=resume"
- urls = _wire(session, [("offset=resume", _page([{"gid": "9"}]))])
-
- manager = _make_manager(AsanaResumeConfig(paginator_state={"next_url": resume_url}))
- _rows(_source("workspaces", manager))
+ result = _driver().run(
+ "workspaces",
+ [_page([{"gid": "9"}])],
+ resume_state=AsanaResumeConfig(paginator_state={"next_url": resume_url}),
+ )
- assert urls[0] == resume_url
+ assert result.raised is None
+ assert result.urls == [resume_url]
class TestFanOut:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_workspace_fan_out_drains_every_parent(self, MockSession) -> None:
- session = MockSession.return_value
- _wire(
- session,
- [
- ("/workspaces?", _page([{"gid": "W1"}, {"gid": "W2"}])),
- ("workspace=W1", _page([{"gid": "a"}])),
- ("workspace=W2", _page([{"gid": "b"}])),
- ],
+ def test_workspace_fan_out_drains_every_parent(self) -> None:
+ result = _driver().run(
+ "projects",
+ [_page([{"gid": "W1"}, {"gid": "W2"}]), _page([{"gid": "a"}]), _page([{"gid": "b"}])],
)
- manager = _make_manager()
- rows = _rows(_source("projects", manager))
-
- assert [r["gid"] for r in rows] == ["a", "b"]
+ assert result.raised is None
+ assert [row["gid"] for row in result.rows] == ["a", "b"]
+ assert result.params("workspace") == [None, "W1", "W2"]
# Single-hop fan-out keeps resume: the dependent resource checkpoints per-parent progress.
- assert manager.save_state.called
- assert "completed" in manager.save_state.call_args.args[0].paginator_state
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_organization_fan_out_skips_non_org_workspaces(self, MockSession) -> None:
- session = MockSession.return_value
- sent = _wire(
- session,
+ assert result.saved_states
+ state = result.saved_states[-1].paginator_state
+ assert state is not None
+ assert "completed" in state
+
+ def test_organization_fan_out_skips_non_org_workspaces(self) -> None:
+ result = _driver().run(
+ "teams",
[
- (
- "/workspaces?",
- _page([{"gid": "W1", "is_organization": True}, {"gid": "W2", "is_organization": False}]),
- ),
- ("/organizations/W1/teams", _page([{"gid": "team1"}])),
+ _page([{"gid": "W1", "is_organization": True}, {"gid": "W2", "is_organization": False}]),
+ _page([{"gid": "team1"}]),
],
)
- manager = _make_manager()
- rows = _rows(_source("teams", manager))
-
- assert [r["gid"] for r in rows] == ["team1"]
+ assert result.raised is None
+ assert [row["gid"] for row in result.rows] == ["team1"]
+ assert result.paths == ["/api/1.0/workspaces", "/api/1.0/organizations/W1/teams"]
# The non-organization workspace never triggers a teams request.
- assert not any("/organizations/W2/" in url for url in sent)
+ assert not any("/organizations/W2/" in path for path in result.paths)
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_task_level_chain_yields_stories_per_task(self, MockSession) -> None:
- session = MockSession.return_value
- sent = _wire(
- session,
+ def test_task_level_chain_yields_stories_per_task(self) -> None:
+ result = _driver().run(
+ "stories",
[
- ("/workspaces?", _page([{"gid": "W1"}])),
- ("workspace=W1", _page([{"gid": "P1"}])),
- ("project=P1", _page([{"gid": "T1"}, {"gid": "T2"}])),
- ("/tasks/T1/stories", _page([{"gid": "s1"}])),
- ("/tasks/T2/stories", _page([{"gid": "s2"}])),
+ _page([{"gid": "W1"}]),
+ _page([{"gid": "P1"}]),
+ _page([{"gid": "T1"}, {"gid": "T2"}]),
+ _page([{"gid": "s1"}]),
+ _page([{"gid": "s2"}]),
],
)
- rows = _rows(_source("stories", _make_manager()))
-
- assert [r["gid"] for r in rows] == ["s1", "s2"]
+ assert result.raised is None
+ assert [row["gid"] for row in result.rows] == ["s1", "s2"]
+ assert result.paths == [
+ "/api/1.0/workspaces",
+ "/api/1.0/projects",
+ "/api/1.0/tasks",
+ "/api/1.0/tasks/T1/stories",
+ "/api/1.0/tasks/T2/stories",
+ ]
# The tasks level is fetched compact — story opt_fields must not leak onto the parent walk.
- assert not any("opt_fields" in url for url in sent if "project=P1" in url)
+ assert all(
+ request.param("opt_fields") is None for request in result.requests if request.param("project") == "P1"
+ )
@pytest.mark.parametrize(
"endpoint, child_routes, expected_gids",
@@ -177,149 +123,143 @@ class TestFanOut:
("time_tracking_entries", [("user=U1", [{"gid": "e1"}]), ("user=U2", [])], ["e1"]),
],
)
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_users_are_walked_per_workspace(self, MockSession, endpoint, child_routes, expected_gids) -> None:
- session = MockSession.return_value
- sent = _wire(
- session,
+ def test_users_are_walked_per_workspace(
+ self, endpoint: str, child_routes: list[tuple[str, list[dict[str, Any]]]], expected_gids: list[str]
+ ) -> None:
+ result = _driver().run(
+ endpoint,
[
- ("/workspaces?", _page([{"gid": "W1"}])),
- ("/users", _page([{"gid": "U1"}, {"gid": "U2"}])),
- *[(substr, _page(items)) for substr, items in child_routes],
+ _page([{"gid": "W1"}]),
+ _page([{"gid": "U1"}, {"gid": "U2"}]),
+ *[_page(items) for _, items in child_routes],
],
)
- rows = _rows(_source(endpoint, _make_manager()))
-
- assert [r["gid"] for r in rows] == expected_gids
+ assert result.raised is None
+ assert [row["gid"] for row in result.rows] == expected_gids
# Asana rejects an unscoped /users once the token can see more than one workspace.
- user_urls = [url for url in sent if "/users" in url]
- assert user_urls and all("workspace=W1" in url for url in user_urls)
+ user_requests = [request for request in result.requests if "/users" in request.path]
+ assert user_requests and all(request.param("workspace") == "W1" for request in user_requests)
+ if child_routes:
+ assert result.params("user")[-len(child_routes) :] == [route.split("=", 1)[1] for route, _ in child_routes]
# Every entry request is scoped to a user; an unfiltered request would be rejected.
- assert all("user=" in url for url in sent if "/time_tracking_entries" in url)
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_parent_goals_carry_the_child_gid_and_skip_pagination(self, MockSession) -> None:
- session = MockSession.return_value
- # parentGoals takes no limit/offset and returns no next_page — a `limit` param is rejected.
- sent = _wire(
- session,
+ assert all(
+ request.param("user") is not None for request in result.requests if "/time_tracking_entries" in request.path
+ )
+
+ def test_parent_goals_carry_the_child_gid_and_skip_pagination(self) -> None:
+ # parentGoals takes no limit/offset and returns no next_page — a limit param is rejected.
+ result = _driver().run(
+ "parent_goals",
[
- ("/workspaces?", _page([{"gid": "W1"}])),
- ("workspace=W1", _page([{"gid": "G1"}, {"gid": "G2"}])),
- ("/goals/G1/parentGoals", _page([{"gid": "P"}], next_uri="ignored")),
- ("/goals/G2/parentGoals", _page([{"gid": "P"}])),
+ _page([{"gid": "W1"}]),
+ _page([{"gid": "G1"}, {"gid": "G2"}]),
+ _page([{"gid": "P"}], next_uri="ignored"),
+ _page([{"gid": "P"}]),
],
)
- rows = _rows(_source("parent_goals", _make_manager()))
-
+ assert result.raised is None
# The same parent goal under two children — only the composite key keeps both rows.
- assert [(r["goal_gid"], r["gid"]) for r in rows] == [("G1", "P"), ("G2", "P")]
- assert not any(r for r in rows if "_goals_gid" in r)
- parent_goal_urls = [url for url in sent if "parentGoals" in url]
- assert len(parent_goal_urls) == 2
- assert not any("limit=" in url or "offset=" in url for url in parent_goal_urls)
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_team_memberships_walk_organizations_then_teams(self, MockSession) -> None:
- session = MockSession.return_value
- sent = _wire(
- session,
+ assert [(row["goal_gid"], row["gid"]) for row in result.rows] == [("G1", "P"), ("G2", "P")]
+ assert not any("_goals_gid" in row for row in result.rows)
+ parent_goal_requests = [request for request in result.requests if "parentGoals" in request.path]
+ assert len(parent_goal_requests) == 2
+ assert [request.path for request in parent_goal_requests] == [
+ "/api/1.0/goals/G1/parentGoals",
+ "/api/1.0/goals/G2/parentGoals",
+ ]
+ assert all(
+ request.param("limit") is None and request.param("offset") is None for request in parent_goal_requests
+ )
+
+ def test_team_memberships_walk_organizations_then_teams(self) -> None:
+ result = _driver().run(
+ "team_memberships",
[
- (
- "/workspaces?",
- _page([{"gid": "W1", "is_organization": True}, {"gid": "W2", "is_organization": False}]),
- ),
- ("/organizations/W1/teams", _page([{"gid": "TM1"}])),
- ("/teams/TM1/team_memberships", _page([{"gid": "m1"}])),
+ _page([{"gid": "W1", "is_organization": True}, {"gid": "W2", "is_organization": False}]),
+ _page([{"gid": "TM1"}]),
+ _page([{"gid": "m1"}]),
],
)
- rows = _rows(_source("team_memberships", _make_manager()))
-
- assert [r["gid"] for r in rows] == ["m1"]
+ assert result.raised is None
+ assert [row["gid"] for row in result.rows] == ["m1"]
+ assert result.paths == [
+ "/api/1.0/workspaces",
+ "/api/1.0/organizations/W1/teams",
+ "/api/1.0/teams/TM1/team_memberships",
+ ]
# Teams only exist under organizations, so the plain workspace is dropped before the walk.
- assert not any("/organizations/W2/" in url for url in sent)
+ assert not any("/organizations/W2/" in path for path in result.paths)
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_portfolio_items_carry_the_portfolio_gid(self, MockSession) -> None:
- session = MockSession.return_value
- sent = _wire(
- session,
+ def test_portfolio_items_carry_the_portfolio_gid(self) -> None:
+ result = _driver().run(
+ "portfolio_items",
[
- ("/workspaces?", _page([{"gid": "W1"}])),
- ("workspace=W1", _page([{"gid": "PF1"}, {"gid": "PF2"}])),
- ("/portfolios/PF1/items", _page([{"gid": "PR1"}])),
- ("/portfolios/PF2/items", _page([{"gid": "PR1"}])),
+ _page([{"gid": "W1"}]),
+ _page([{"gid": "PF1"}, {"gid": "PF2"}]),
+ _page([{"gid": "PR1"}]),
+ _page([{"gid": "PR1"}]),
],
)
- rows = _rows(_source("portfolio_items", _make_manager()))
-
+ assert result.raised is None
# The same project held by two portfolios — only the composite key keeps both rows.
- assert [(r["portfolio_gid"], r["gid"]) for r in rows] == [("PF1", "PR1"), ("PF2", "PR1")]
- assert not any(r for r in rows if "_portfolios_gid" in r)
- assert all("limit=" in url for url in sent if "/items" in url)
+ assert [(row["portfolio_gid"], row["gid"]) for row in result.rows] == [("PF1", "PR1"), ("PF2", "PR1")]
+ assert not any("_portfolios_gid" in row for row in result.rows)
+ assert result.paths[-2:] == ["/api/1.0/portfolios/PF1/items", "/api/1.0/portfolios/PF2/items"]
+ assert all(request.param("limit") == "100" for request in result.requests if "/items" in request.path)
# Asana 400s GET /portfolios for a non-service-account token without an explicit owner.
- assert all("owner=me" in url for url in sent if "/portfolios?" in url)
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_portfolios_scope_to_the_tokens_own_user(self, MockSession) -> None:
- session = MockSession.return_value
- sent = _wire(
- session,
- [
- ("/workspaces?", _page([{"gid": "W1"}])),
- ("workspace=W1", _page([{"gid": "PF1"}])),
- ],
+ assert all(
+ request.param("owner") == "me" for request in result.requests if request.path == "/api/1.0/portfolios"
)
- rows = _rows(_source("portfolios", _make_manager()))
+ def test_portfolios_scope_to_the_tokens_own_user(self) -> None:
+ result = _driver().run("portfolios", [_page([{"gid": "W1"}]), _page([{"gid": "PF1"}])])
- assert [r["gid"] for r in rows] == ["PF1"]
+ assert result.raised is None
+ assert [row["gid"] for row in result.rows] == ["PF1"]
# Asana 400s GET /portfolios for a non-service-account token without an explicit owner.
- assert all("owner=me" in url for url in sent if "/portfolios?" in url)
+ assert all(request.param("owner") == "me" for request in result.requests if "/portfolios" in request.path)
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_project_level_chain_yields_grandchild_rows(self, MockSession) -> None:
- session = MockSession.return_value
- _wire(
- session,
+ def test_project_level_chain_yields_grandchild_rows(self) -> None:
+ result = _driver().run(
+ "tasks",
[
- ("/workspaces?", _page([{"gid": "W1"}])),
- ("workspace=W1", _page([{"gid": "P1"}, {"gid": "P2"}])),
- ("project=P1", _page([{"gid": "t1"}])),
- ("project=P2", _page([{"gid": "t2"}])),
+ _page([{"gid": "W1"}]),
+ _page([{"gid": "P1"}, {"gid": "P2"}]),
+ _page([{"gid": "t1"}]),
+ _page([{"gid": "t2"}]),
],
)
- manager = _make_manager()
- rows = _rows(_source("tasks", manager))
-
- assert [r["gid"] for r in rows] == ["t1", "t2"]
+ assert result.raised is None
+ assert [row["gid"] for row in result.rows] == ["t1", "t2"]
+ assert result.params("project")[-2:] == ["P1", "P2"]
# Multi-level fan-out disables resume (one shared hook can't checkpoint two levels);
# retries re-fetch and the merge dedupes on gid.
- manager.save_state.assert_not_called()
+ assert result.saved_states == []
class TestValidateCredentials:
@pytest.mark.parametrize("status_code, expected", [(200, True), (401, False), (403, False), (500, False)])
- @mock.patch(ASANA_SESSION_PATCH)
- def test_status_mapping(self, mock_session, status_code, expected) -> None:
- response = mock.MagicMock()
- response.status_code = status_code
- mock_session.return_value.get.return_value = response
- assert validate_credentials("token") is expected
+ def test_status_mapping(self, status_code: int, expected: bool) -> None:
+ with scripted_network(always(ScriptedResponse(status=status_code))) as network:
+ assert validate_credentials("token") is expected
+
+ assert network.requests_log[0].path == "/api/1.0/users/me"
class TestAsanaSourceResponse:
@pytest.mark.parametrize("endpoint", list(ENDPOINTS))
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_response_metadata_per_endpoint(self, MockSession, endpoint) -> None:
+ def test_response_metadata_per_endpoint(self, endpoint: str) -> None:
config = ASANA_ENDPOINTS[endpoint]
- response = _source(endpoint, _make_manager())
+ result = _driver().run(endpoint, always(_page([])))
+ assert result.raised is None
+ response = result.response
+ assert response is not None
assert response.name == endpoint
assert response.primary_keys == config.primary_keys
if config.partition_key:
@@ -335,7 +275,7 @@ class TestAsanaSourceResponse:
STABLE_CREATION_FIELDS = {"created_at", "run_started_at"}
@pytest.mark.parametrize("config", list(ASANA_ENDPOINTS.values()))
- def test_partition_keys_are_stable_creation_fields(self, config) -> None:
+ def test_partition_keys_are_stable_creation_fields(self, config: AsanaEndpointConfig) -> None:
if config.partition_key:
assert config.partition_key in self.STABLE_CREATION_FIELDS
# The partition field must be opted into the response, else partitioning fails.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asana/tests/test_asana_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asana/tests/test_asana_source.py
index 1bf60b991cd0..e43788d13077 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/asana/tests/test_asana_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asana/tests/test_asana_source.py
@@ -1,12 +1,15 @@
import pytest
-from unittest import mock
from products.warehouse_sources.backend.temporal.data_imports.sources.asana.source import AsanaSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ scripted_network,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.asana import AsanaSourceConfig
class TestAsanaSource:
- def setup_method(self):
+ def setup_method(self) -> None:
self.source = AsanaSource()
self.team_id = 123
self.config = AsanaSourceConfig(access_token="1/abc")
@@ -18,14 +21,12 @@ class TestAsanaSource:
(False, False, "Invalid Asana personal access token"),
],
)
- @mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.asana.source.validate_asana_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)
+ def test_validate_credentials(self, mock_return: bool, expected_valid: bool, expected_message: str | None) -> None:
+ with scripted_network([ScriptedResponse(status=200 if mock_return else 401)]) as network:
+ 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(self.config.access_token)
+ assert len(network.requests_log) == 1
+ assert network.requests_log[0].path == "/api/1.0/users/me"
+ assert network.requests_log[0].headers["authorization"] == f"Bearer {self.config.access_token}"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/tests/test_ashby.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/tests/test_ashby.py
index 319e5790ebb6..9de12dbf33f8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/tests/test_ashby.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/tests/test_ashby.py
@@ -1,11 +1,8 @@
-import json
-from typing import Any, Optional
+from typing import Any
import pytest
-from unittest import mock
import requests
-from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.ashby.ashby import (
ASHBY_BASE_URL,
@@ -13,81 +10,26 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.ashby.ashb
AshbyAPIError,
AshbyResumeConfig,
_errors_from_payload,
- ashby_source,
check_access,
)
-
-# RESTClient builds its session via make_tracked_session in the rest_client module.
-CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
-# check_access builds its own tracked session in the ashby module.
-ASHBY_SESSION_PATCH = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.ashby.ashby.make_tracked_session"
+from products.warehouse_sources.backend.temporal.data_imports.sources.ashby.source import AshbySource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ scripted_network,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.ashby import AshbySourceConfig
-def _response(body: dict[str, Any], status_code: int = 200) -> Response:
- resp = Response()
- resp.status_code = status_code
- resp._content = json.dumps(body).encode()
- return resp
-
-
-def _page(
- items: list[dict[str, Any]],
- *,
- more: bool = False,
- next_cursor: Optional[str] = None,
-) -> Response:
+def _page(items: list[dict[str, Any]], *, more: bool = False, next_cursor: str | None = None) -> ScriptedResponse:
body: dict[str, Any] = {"success": True, "results": items, "moreDataAvailable": more}
if next_cursor is not None:
body["nextCursor"] = next_cursor
- return _response(body)
-
+ return ScriptedResponse(json=body)
-def _make_manager(resume_state: AshbyResumeConfig | None = None) -> mock.MagicMock:
- manager = mock.MagicMock()
- manager.can_resume.return_value = resume_state is not None
- manager.load_state.return_value = resume_state
- return manager
-
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
- """Wire a mock session and return snapshots of each request AT SEND TIME.
-
- ``request.json`` is a single dict mutated in place across pages, so inspecting it after the
- run shows only the final state — snapshot a copy when each request is prepared instead.
- """
- session.headers = {}
- snapshots: list[dict[str, Any]] = []
-
- def _prepare(request: Any) -> mock.MagicMock:
- snapshots.append(
- {
- "url": request.url,
- "method": request.method,
- "json": dict(request.json or {}),
- "auth": request.auth,
- }
- )
- return mock.MagicMock()
-
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = responses
- return snapshots
-
-
-def _rows(source_response) -> list[dict[str, Any]]:
- return [row for page in source_response.items() for row in page]
-
-
-def _source(endpoint: str = "candidates", manager: Optional[mock.MagicMock] = None, api_key: str = "dummy-key"):
- return ashby_source(
- api_key=api_key,
- endpoint=endpoint,
- team_id=1,
- job_id="j",
- resumable_source_manager=manager if manager is not None else _make_manager(),
- )
+def _driver() -> SourceDriver:
+ return SourceDriver(AshbySource(), AshbySourceConfig(api_key="dummy-key"))
class TestErrorsFromPayload:
@@ -105,264 +47,186 @@ class TestErrorsFromPayload:
class TestPagination:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_paginates_until_no_more_data(self, MockSession) -> None:
- session = MockSession.return_value
- snapshots = _wire(
- session,
- [
- _page([{"id": "1"}], more=True, next_cursor="c1"),
- _page([{"id": "2"}], more=False),
- ],
+ def test_paginates_until_no_more_data(self) -> None:
+ result = _driver().run(
+ "candidates",
+ [_page([{"id": "1"}], more=True, next_cursor="c1"), _page([{"id": "2"}])],
)
- rows = _rows(_source("candidates"))
-
- assert rows == [{"id": "1"}, {"id": "2"}]
+ assert result.raised is None
+ assert result.rows == [{"id": "1"}, {"id": "2"}]
# First call has no cursor, second forwards nextCursor; limit is sent in the JSON body.
- assert "cursor" not in snapshots[0]["json"]
- assert snapshots[1]["json"]["cursor"] == "c1"
- assert snapshots[0]["json"]["limit"] == 100
- assert snapshots[0]["url"] == f"{ASHBY_BASE_URL}/candidate.list"
- assert snapshots[0]["method"] == "POST"
+ assert "cursor" not in result.requests[0].json()
+ assert result.requests[1].json()["cursor"] == "c1"
+ assert result.requests[0].json()["limit"] == 100
+ assert result.urls[0] == f"{ASHBY_BASE_URL}/candidate.list"
+ assert result.requests[0].method == "POST"
# Ashby authenticates via HTTP Basic: API key as username, empty password.
- assert snapshots[0]["auth"].username == "dummy-key"
- assert snapshots[0]["auth"].password == ""
+ assert result.requests[0].headers["authorization"] == "Basic ZHVtbXkta2V5Og=="
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_saves_state_after_yielding_each_page(self, MockSession) -> None:
- session = MockSession.return_value
- _wire(
- session,
- [
- _page([{"id": "1"}], more=True, next_cursor="c1"),
- _page([{"id": "2"}], more=False),
- ],
+ def test_saves_state_after_yielding_each_page(self) -> None:
+ result = _driver().run(
+ "candidates",
+ [_page([{"id": "1"}], more=True, next_cursor="c1"), _page([{"id": "2"}])],
)
- manager = _make_manager()
-
- _rows(_source("candidates", manager))
-
- manager.save_state.assert_called_once_with(AshbyResumeConfig(cursor="c1"))
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_resumes_from_saved_cursor(self, MockSession) -> None:
- session = MockSession.return_value
- snapshots = _wire(session, [_page([{"id": "9"}], more=False)])
- manager = _make_manager(AshbyResumeConfig(cursor="resume-cursor"))
-
- rows = _rows(_source("candidates", manager))
-
- assert rows == [{"id": "9"}]
- assert snapshots[0]["json"]["cursor"] == "resume-cursor"
+ assert result.raised is None
+ assert result.saved_states == [AshbyResumeConfig(cursor="c1")]
+
+ def test_resumes_from_saved_cursor(self) -> None:
+ result = _driver().run(
+ "candidates",
+ [_page([{"id": "9"}])],
+ resume_state=AshbyResumeConfig(cursor="resume-cursor"),
+ )
+ assert result.raised is None
+ assert result.rows == [{"id": "9"}]
+ assert result.requests[0].json()["cursor"] == "resume-cursor"
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_stops_when_more_data_unavailable_even_with_cursor(self, MockSession) -> None:
+ def test_stops_when_more_data_unavailable_even_with_cursor(self) -> None:
# Ashby can return a nextCursor alongside moreDataAvailable=false — that must terminate.
- session = MockSession.return_value
- _wire(session, [_page([{"id": "1"}], more=False, next_cursor="c9")])
- manager = _make_manager()
-
- rows = _rows(_source("candidates", manager))
-
- assert rows == [{"id": "1"}]
- assert session.send.call_count == 1
- manager.save_state.assert_not_called()
+ result = _driver().run("candidates", [_page([{"id": "1"}], next_cursor="c9")])
+ assert result.raised is None
+ assert result.rows == [{"id": "1"}]
+ assert len(result.requests) == 1
+ assert result.saved_states == []
@pytest.mark.parametrize("status_code", [401, 403])
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_http_auth_errors_raise_matchable_error(self, MockSession, status_code: int) -> None:
- session = MockSession.return_value
- _wire(session, [_response({}, status_code=status_code)])
-
- with pytest.raises(requests.HTTPError) as exc:
- _rows(_source("candidates"))
- assert f"{status_code} Client Error" in str(exc.value)
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_success_false_auth_error_raises_matchable_api_error(self, MockSession) -> None:
- session = MockSession.return_value
- _wire(session, [_response({"success": False, "errors": ["Missing permission: candidatesRead"]})])
-
- with pytest.raises(AshbyAPIError) as exc:
- _rows(_source("candidates"))
- assert AUTH_ERROR_HINT in str(exc.value)
- assert "Missing permission: candidatesRead" in str(exc.value)
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_success_false_non_auth_error_raises_without_auth_hint(self, MockSession) -> None:
- session = MockSession.return_value
- _wire(session, [_response({"success": False, "errors": ["validation failed"]})])
-
- with pytest.raises(AshbyAPIError) as exc:
- _rows(_source("candidates"))
- assert AUTH_ERROR_HINT not in str(exc.value)
- assert "validation failed" in str(exc.value)
-
-
-class FakeResponse:
- def __init__(
- self, status_code: int = 200, json_data: Optional[dict[str, Any]] = None, raise_json: bool = False
- ) -> None:
- self.status_code = status_code
- self._json = json_data if json_data is not None else {}
- self.text = str(self._json)
- self._raise_json = raise_json
-
- @property
- def ok(self) -> bool:
- return 200 <= self.status_code < 300
+ def test_http_auth_errors_raise_matchable_error(self, status_code: int) -> None:
+ result = _driver().run("candidates", [ScriptedResponse(status=status_code, json={})])
+ assert isinstance(result.raised, requests.HTTPError)
+ assert f"{status_code} Client Error" in str(result.raised)
+
+ def test_success_false_auth_error_raises_matchable_api_error(self) -> None:
+ result = _driver().run(
+ "candidates",
+ [ScriptedResponse(json={"success": False, "errors": ["Missing permission: candidatesRead"]})],
+ )
+ assert isinstance(result.raised, AshbyAPIError)
+ assert AUTH_ERROR_HINT in str(result.raised)
+ assert "Missing permission: candidatesRead" in str(result.raised)
- def json(self) -> dict[str, Any]:
- if self._raise_json:
- raise ValueError("no json")
- return self._json
+ def test_success_false_non_auth_error_raises_without_auth_hint(self) -> None:
+ result = _driver().run(
+ "candidates", [ScriptedResponse(json={"success": False, "errors": ["validation failed"]})]
+ )
+ assert isinstance(result.raised, AshbyAPIError)
+ assert AUTH_ERROR_HINT not in str(result.raised)
+ assert "validation failed" in str(result.raised)
class TestCheckAccess:
@pytest.mark.parametrize(
"response, expected_status",
[
- (FakeResponse(json_data={"success": True, "results": []}), 200),
- (FakeResponse(status_code=401), 401),
- (FakeResponse(status_code=403), 403),
- (FakeResponse(json_data={"success": False, "errors": ["Missing permission"]}), 403),
- (FakeResponse(json_data={"success": False, "errors": ["bad request"]}), 400),
- (FakeResponse(status_code=500), 500),
- (FakeResponse(raise_json=True), 0),
+ (ScriptedResponse(json={"success": True, "results": []}), 200),
+ (ScriptedResponse(status=401), 401),
+ (ScriptedResponse(status=403), 403),
+ (ScriptedResponse(json={"success": False, "errors": ["Missing permission"]}), 403),
+ (ScriptedResponse(json={"success": False, "errors": ["bad request"]}), 400),
+ (ScriptedResponse(status=500), 500),
+ (ScriptedResponse(body=b"not json"), 0),
],
)
- def test_status_mapping(self, response: FakeResponse, expected_status: int) -> None:
- session = mock.MagicMock()
- session.post.return_value = response
- with mock.patch(ASHBY_SESSION_PATCH, return_value=session):
+ def test_status_mapping(self, response: ScriptedResponse, expected_status: int) -> None:
+ with scripted_network([response]):
status, _message = check_access("k", "department.list")
assert status == expected_status
def test_probes_endpoint_with_basic_auth(self) -> None:
- session = mock.MagicMock()
- session.post.return_value = FakeResponse(json_data={"success": True, "results": []})
- with mock.patch(ASHBY_SESSION_PATCH, return_value=session):
+ with scripted_network([_page([])]) as network:
check_access("k", "department.list")
- call = session.post.call_args
- assert call.args[0] == f"{ASHBY_BASE_URL}/department.list"
- assert call.kwargs["auth"] == ("k", "")
- assert call.kwargs["json"] == {"limit": 1}
+ request = network.requests_log[0]
+ assert request.url == f"{ASHBY_BASE_URL}/department.list"
+ assert request.headers["authorization"] == "Basic azo="
+ assert request.json() == {"limit": 1}
def test_connection_error_returns_zero(self) -> None:
- session = mock.MagicMock()
- session.post.side_effect = Exception("boom")
- with mock.patch(ASHBY_SESSION_PATCH, return_value=session):
+ with scripted_network([ConnectionResetError("boom")]):
status, message = check_access("k", "department.list")
assert status == 0
assert message is not None
class TestFanOut:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_calls_the_child_once_per_parent_and_injects_the_parent_id(self, MockSession) -> None:
- session = MockSession.return_value
- snapshots = _wire(
- session,
+ def test_calls_the_child_once_per_parent_and_injects_the_parent_id(self) -> None:
+ result = _driver().run(
+ "application_history",
[
- _page([{"id": "app-1"}, {"id": "app-2"}], more=False),
- _page([{"id": "h-1", "stageNumber": 0}], more=False),
- _page([{"id": "h-2", "stageNumber": 0}], more=False),
+ _page([{"id": "app-1"}, {"id": "app-2"}]),
+ _page([{"id": "h-1", "stageNumber": 0}]),
+ _page([{"id": "h-2", "stageNumber": 0}]),
],
)
-
- rows = _rows(_source("application_history"))
-
+ assert result.raised is None
# application.listHistory rows carry no applicationId, so the fan-out has to add it —
# without it the table can't be joined back to applications and its key isn't unique.
- assert rows == [
+ assert result.rows == [
{"id": "h-1", "stageNumber": 0, "applicationId": "app-1"},
{"id": "h-2", "stageNumber": 0, "applicationId": "app-2"},
]
- assert [snapshot["url"] for snapshot in snapshots] == [
+ assert result.urls == [
f"{ASHBY_BASE_URL}/application.list",
f"{ASHBY_BASE_URL}/application.listHistory",
f"{ASHBY_BASE_URL}/application.listHistory",
]
- assert snapshots[1]["json"] == {"applicationId": "app-1", "limit": 100}
- assert snapshots[2]["json"] == {"applicationId": "app-2", "limit": 100}
+ assert result.requests[1].json() == {"applicationId": "app-1", "limit": 100}
+ assert result.requests[2].json() == {"applicationId": "app-2", "limit": 100}
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_unpaginated_child_sends_only_the_resolve_param(self, MockSession) -> None:
+ def test_unpaginated_child_sends_only_the_resolve_param(self) -> None:
# interviewStage.list takes interviewPlanId and nothing else — Ashby rejects a `limit`.
- session = MockSession.return_value
- snapshots = _wire(
- session,
+ result = _driver().run(
+ "interview_stages",
[
- _page([{"id": "plan-1"}], more=False),
- _page([{"id": "stage-1", "interviewPlanId": "plan-1"}], more=False),
+ _page([{"id": "plan-1"}]),
+ _page([{"id": "stage-1", "interviewPlanId": "plan-1"}]),
],
)
-
- rows = _rows(_source("interview_stages"))
-
- assert rows == [{"id": "stage-1", "interviewPlanId": "plan-1"}]
- assert snapshots[1]["json"] == {"interviewPlanId": "plan-1"}
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_resumes_at_the_parent_that_was_in_progress(self, MockSession) -> None:
- session = MockSession.return_value
- snapshots = _wire(
- session,
- [
- _page([{"id": "app-1"}, {"id": "app-2"}], more=False),
- _page([{"id": "h-2"}], more=False),
- ],
+ assert result.raised is None
+ assert result.rows == [{"id": "stage-1", "interviewPlanId": "plan-1"}]
+ assert result.requests[1].json() == {"interviewPlanId": "plan-1"}
+
+ def test_resumes_at_the_parent_that_was_in_progress(self) -> None:
+ result = _driver().run(
+ "application_history",
+ [_page([{"id": "app-1"}, {"id": "app-2"}]), _page([{"id": "h-2"}])],
+ resume_state=AshbyResumeConfig(parent_index=1, child_cursor="half-way"),
)
- manager = _make_manager(AshbyResumeConfig(parent_index=1, child_cursor="half-way"))
+ assert result.raised is None
+ assert result.rows == [{"id": "h-2", "applicationId": "app-2"}]
+ assert result.requests[1].json()["cursor"] == "half-way"
- rows = _rows(_source("application_history", manager))
-
- assert rows == [{"id": "h-2", "applicationId": "app-2"}]
- assert snapshots[1]["json"]["cursor"] == "half-way"
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_checkpoints_each_finished_parent_against_its_page_cursor(self, MockSession) -> None:
- session = MockSession.return_value
- _wire(
- session,
+ def test_checkpoints_each_finished_parent_against_its_page_cursor(self) -> None:
+ result = _driver().run(
+ "application_history",
[
_page([{"id": "app-1"}], more=True, next_cursor="p2"),
- _page([{"id": "h-1"}], more=False),
- _page([{"id": "app-2"}], more=False),
- _page([{"id": "h-2"}], more=False),
+ _page([{"id": "h-1"}]),
+ _page([{"id": "app-2"}]),
+ _page([{"id": "h-2"}]),
],
)
- manager = _make_manager()
-
- _rows(_source("application_history", manager))
-
+ assert result.raised is None
# The second parent is recorded against "p2" — the cursor that fetched the page it is on,
# not the one that fetched the page before it.
- assert manager.save_state.call_args_list == [
- mock.call(AshbyResumeConfig(parent_cursor=None, parent_index=1)),
- mock.call(AshbyResumeConfig(parent_cursor="p2", parent_index=1)),
+ assert result.saved_states == [
+ AshbyResumeConfig(parent_cursor=None, parent_index=1),
+ AshbyResumeConfig(parent_cursor="p2", parent_index=1),
]
class TestNestedRows:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_interview_events_are_read_from_the_schedule_listing(self, MockSession) -> None:
- session = MockSession.return_value
- snapshots = _wire(
- session,
+ def test_interview_events_are_read_from_the_schedule_listing(self) -> None:
+ result = _driver().run(
+ "interview_events",
[
_page(
[
{"id": "sched-1", "interviewEvents": [{"id": "ev-1"}, {"id": "ev-2"}]},
{"id": "sched-2", "interviewEvents": []},
- ],
- more=False,
+ ]
)
],
)
-
- rows = _rows(_source("interview_events"))
-
- assert rows == [{"id": "ev-1"}, {"id": "ev-2"}]
- assert snapshots[0]["url"] == f"{ASHBY_BASE_URL}/interviewSchedule.list"
+ assert result.raised is None
+ assert result.rows == [{"id": "ev-1"}, {"id": "ev-2"}]
+ assert result.urls[0] == f"{ASHBY_BASE_URL}/interviewSchedule.list"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/tests/test_ashby_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/tests/test_ashby_source.py
index d7c34222cb25..cbbbc83f59de 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/tests/test_ashby_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ashby/tests/test_ashby_source.py
@@ -1,7 +1,10 @@
import pytest
-from unittest import mock
from products.warehouse_sources.backend.temporal.data_imports.sources.ashby.source import AshbySource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ scripted_network,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.ashby import AshbySourceConfig
@@ -23,48 +26,49 @@ class TestAshbySource:
(400, None, False, "boom"),
],
)
- @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.ashby.source.check_access")
def test_validate_credentials(
self,
- mock_check: mock.MagicMock,
status: int,
schema_name: str | None,
expected_valid: bool,
expected_message: str | None,
) -> None:
- mock_check.return_value = (status, "boom")
- is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+ response = (
+ ScriptedResponse(json={"success": False, "errors": ["boom"]})
+ if status == 400
+ else ScriptedResponse(status=status, json={"success": True})
+ )
+ with scripted_network([response]):
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
assert is_valid is expected_valid
assert message == expected_message
- @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.ashby.source.check_access")
- def test_validate_credentials_probes_schema_path_when_given(self, mock_check: mock.MagicMock) -> None:
- mock_check.return_value = (200, None)
- self.source.validate_credentials(self.config, self.team_id, schema_name="candidates")
- mock_check.assert_called_once_with("ashby-key", "candidate.list")
+ def test_validate_credentials_probes_schema_path_when_given(self) -> None:
+ with scripted_network([ScriptedResponse(json={"success": True})]) as network:
+ self.source.validate_credentials(self.config, self.team_id, schema_name="candidates")
+ assert network.requests_log[0].path == "/candidate.list"
+ assert network.requests_log[0].headers["authorization"] == "Basic YXNoYnkta2V5Og=="
@pytest.mark.parametrize(
"schema_name, expected_path",
- [("application_history", "application.list"), ("interview_stages", "interviewPlan.list")],
+ [("application_history", "/application.list"), ("interview_stages", "/interviewPlan.list")],
)
- @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.ashby.source.check_access")
def test_validate_credentials_probes_the_parent_of_a_fanned_out_schema(
- self, mock_check: mock.MagicMock, schema_name: str, expected_path: str
+ self, schema_name: str, expected_path: str
) -> None:
# The child methods need a parent id, so probing them directly always fails.
- mock_check.return_value = (200, None)
- self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
- mock_check.assert_called_once_with("ashby-key", expected_path)
+ with scripted_network([ScriptedResponse(json={"success": True})]) as network:
+ self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+ assert network.requests_log[0].path == expected_path
- @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.ashby.source.check_access")
- def test_validate_credentials_uses_default_probe_without_schema(self, mock_check: mock.MagicMock) -> None:
- mock_check.return_value = (200, None)
- self.source.validate_credentials(self.config, self.team_id)
- mock_check.assert_called_once_with("ashby-key", "department.list")
+ def test_validate_credentials_uses_default_probe_without_schema(self) -> None:
+ with scripted_network([ScriptedResponse(json={"success": True})]) as network:
+ self.source.validate_credentials(self.config, self.team_id)
+ assert network.requests_log[0].path == "/department.list"
- @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.ashby.source.check_access")
- def test_validate_credentials_rejects_unknown_schema_without_probing(self, mock_check: mock.MagicMock) -> None:
- is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name="not_a_table")
+ def test_validate_credentials_rejects_unknown_schema_without_probing(self) -> None:
+ with scripted_network([]) as network:
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name="not_a_table")
assert is_valid is False
assert message == "Unknown Ashby schema 'not_a_table'"
- mock_check.assert_not_called()
+ assert network.requests_log == []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/tests/test_asknicely.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/tests/test_asknicely.py
index 21796f67f977..3a9758edf883 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/tests/test_asknicely.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/tests/test_asknicely.py
@@ -1,71 +1,36 @@
-import json
from datetime import UTC, date, datetime
-from typing import Any, Optional
+from typing import Any
import pytest
-from unittest import mock
-
-from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.asknicely import (
AskNicelyResumeConfig,
_to_unix_timestamp,
- asknicely_source,
build_responses_url,
build_stats_url,
- build_unsubscribed_url,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.settings import (
RESPONSES_PAGE_SIZE,
UNSUBSCRIBED_PAGE_SIZE,
)
-
-MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.asknicely"
+from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.source import AsknicelySource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.asknicely import (
+ AsknicelySourceConfig,
+)
-def _response(rows: list[dict[str, Any]], total_pages: Optional[int] = None) -> Response:
+def _response(rows: list[dict[str, Any]], total_pages: int | None = None) -> ScriptedResponse:
body: dict[str, Any] = {"success": True, "data": rows}
if total_pages is not None:
body["totalpages"] = str(total_pages)
- resp = Response()
- resp.status_code = 200
- resp._content = json.dumps(body).encode()
- return resp
-
-
-def _manager(resume: Optional[AskNicelyResumeConfig] = None) -> mock.MagicMock:
- manager = mock.MagicMock()
- manager.can_resume.return_value = resume is not None
- manager.load_state.return_value = resume
- return manager
-
-
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[tuple[str, dict[str, Any]]]:
- """Wire a mock session and capture each request's URL and params AT PREPARE TIME.
-
- The paginators mutate ``request.url`` and ``request.params`` in place across pages, so
- inspecting them after the run shows only the final page — snapshot each request as it is
- prepared instead.
- """
- session.headers = {}
- snapshots: list[tuple[str, dict[str, Any]]] = []
-
- def _prepare(request: Any) -> mock.MagicMock:
- snapshots.append((request.url, dict(request.params or {})))
- return mock.MagicMock()
-
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = responses
- return snapshots
-
-
-def _urls(calls: list[tuple[str, dict[str, Any]]]) -> list[str]:
- return [url for url, _ in calls]
-
-
-def _rows(source_response) -> list[dict[str, Any]]:
- return [row for page in source_response.items() for row in page]
+ return ScriptedResponse(json=body)
class TestAsknicely:
@@ -93,49 +58,28 @@ class TestAsknicely:
with pytest.raises(ValueError):
_to_unix_timestamp(value)
- def _run(
- self,
- responses: list[Response],
- manager: mock.MagicMock,
- should_use_incremental_field: bool = False,
- db_incremental_field_last_value: Any = None,
- endpoint: str = "responses",
- ) -> tuple[list[dict[str, Any]], list[tuple[str, dict[str, Any]]]]:
- session = mock.MagicMock()
- calls = _wire(session, responses)
- with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
- rows = _rows(
- asknicely_source(
- subdomain="acme",
- api_key="key",
- endpoint=endpoint,
- team_id=1,
- job_id="job-1",
- resumable_source_manager=manager,
- should_use_incremental_field=should_use_incremental_field,
- db_incremental_field_last_value=db_incremental_field_last_value,
- )
- )
- return rows, calls
+ @staticmethod
+ def _driver() -> SourceDriver:
+ return SourceDriver(AsknicelySource(), AsknicelySourceConfig(subdomain="acme", api_key="key"))
def test_paginates_until_totalpages_and_normalizes_rows(self) -> None:
- manager = _manager()
responses = [
_response([{"response_id": "r1", "responded": "100"}], total_pages=2),
_response([{"response_id": "r2", "responded": "200"}], total_pages=2),
]
- rows, calls = self._run(responses, manager)
+ result = self._driver().run("responses", responses)
- assert [row["response_id"] for row in rows] == ["r1", "r2"]
+ assert result.raised is None
+ assert [row["response_id"] for row in result.rows] == ["r1", "r2"]
# String timestamps are coerced to ints via the data_map.
- assert rows[0]["responded"] == 100
- assert _urls(calls) == [
+ assert result.rows[0]["responded"] == 100
+ assert result.urls == [
build_responses_url("acme", page_number=1, since_time=0),
build_responses_url("acme", page_number=2, since_time=0),
]
# Only the intermediate page boundary is checkpointed — never past the final page.
- manager.save_state.assert_called_once_with(AskNicelyResumeConfig(page_number=2, since_time=0))
+ assert result.saved_states == [AskNicelyResumeConfig(page_number=2, since_time=0)]
def test_stops_on_empty_page_when_totalpages_missing(self) -> None:
responses = [
@@ -143,128 +87,113 @@ class TestAsknicely:
_response([]),
]
- rows, calls = self._run(responses, _manager())
+ result = self._driver().run("responses", responses)
- assert len(rows) == RESPONSES_PAGE_SIZE
- assert len(calls) == 2
+ assert result.raised is None
+ assert len(result.rows) == RESPONSES_PAGE_SIZE
+ assert len(result.requests) == 2
def test_incremental_since_time_steps_back_one_second(self) -> None:
- _, calls = self._run(
+ result = self._driver().run(
+ "responses",
[_response([])],
- _manager(),
should_use_incremental_field=True,
db_incremental_field_last_value=1700000000,
)
- assert _urls(calls) == [build_responses_url("acme", page_number=1, since_time=1699999999)]
+ assert result.raised is None
+ assert result.urls == [build_responses_url("acme", page_number=1, since_time=1699999999)]
def test_incremental_since_time_clamps_at_zero(self) -> None:
- _, calls = self._run(
+ result = self._driver().run(
+ "responses",
[_response([])],
- _manager(),
should_use_incremental_field=True,
db_incremental_field_last_value=0,
)
- assert _urls(calls) == [build_responses_url("acme", page_number=1, since_time=0)]
+ assert result.raised is None
+ assert result.urls == [build_responses_url("acme", page_number=1, since_time=0)]
def test_resumes_from_saved_page_and_cutoff(self) -> None:
# The saved since_time must win over a freshly derived one: page numbering is only
# stable against the cutoff the interrupted run used.
- manager = _manager(AskNicelyResumeConfig(page_number=3, since_time=500))
-
- _, calls = self._run(
+ result = self._driver().run(
+ "responses",
[_response([])],
- manager,
+ resume_state=AskNicelyResumeConfig(page_number=3, since_time=500),
should_use_incremental_field=True,
db_incremental_field_last_value=1700000000,
)
- assert _urls(calls) == [build_responses_url("acme", page_number=3, since_time=500)]
+ assert result.raised is None
+ assert result.urls == [build_responses_url("acme", page_number=3, since_time=500)]
def test_no_checkpoint_on_single_short_page(self) -> None:
# A run that finishes on its first page must never checkpoint — there is no next page.
- manager = _manager()
- self._run([_response([{"response_id": "r1", "responded": "100"}])], manager)
- manager.save_state.assert_not_called()
+ result = self._driver().run("responses", [_response([{"response_id": "r1", "responded": "100"}])])
+ assert result.raised is None
+ assert result.saved_states == []
def test_unsubscribed_paginates_by_page_number_and_normalizes_rows(self) -> None:
- manager = _manager()
first = [
{"id": str(i), "unsubscribetime": "1452219376", "email": f"c{i}@example.com"}
for i in range(UNSUBSCRIBED_PAGE_SIZE)
]
responses = [_response(first), _response([{"id": "last", "unsubscribetime": "1452219999"}])]
- rows, calls = self._run(responses, manager, endpoint="contacts_unsubscribed")
+ result = self._driver().run("contacts_unsubscribed", responses)
- assert len(rows) == UNSUBSCRIBED_PAGE_SIZE + 1
+ assert result.raised is None
+ assert len(result.rows) == UNSUBSCRIBED_PAGE_SIZE + 1
# The unix timestamp arrives as a string; it has to be an int to partition on and to
# compare against the responses table's timestamps.
- assert rows[0]["unsubscribetime"] == 1452219376
- assert _urls(calls) == [build_unsubscribed_url("acme")] * 2
- assert [params["pagenumber"] for _, params in calls] == [1, 2]
- assert {params["pagesize"] for _, params in calls} == {UNSUBSCRIBED_PAGE_SIZE}
+ assert result.rows[0]["unsubscribetime"] == 1452219376
+ assert result.paths == ["/api/v1/contacts/unsubscribed"] * 2
+ assert [request.origin for request in result.requests] == ["https://acme.asknice.ly"] * 2
+ assert result.params("pagenumber") == ["1", "2"]
+ assert result.params("pagesize") == [str(UNSUBSCRIBED_PAGE_SIZE)] * 2
# The short second page ends the walk, so only the one page boundary is checkpointed.
- manager.save_state.assert_called_once_with(AskNicelyResumeConfig(page_number=2, since_time=0))
+ assert result.saved_states == [AskNicelyResumeConfig(page_number=2, since_time=0)]
def test_unsubscribed_resumes_from_saved_page(self) -> None:
- manager = _manager(AskNicelyResumeConfig(page_number=3, since_time=0))
-
- _, calls = self._run([_response([])], manager, endpoint="contacts_unsubscribed")
+ result = self._driver().run(
+ "contacts_unsubscribed", [_response([])], resume_state=AskNicelyResumeConfig(page_number=3, since_time=0)
+ )
- assert [params["pagenumber"] for _, params in calls] == [3]
+ assert result.raised is None
+ assert result.params("pagenumber") == ["3"]
def test_stats_fetches_one_page_and_never_checkpoints(self) -> None:
# The stats series comes back whole, so a second request would re-read the same rows
# and a saved checkpoint would leave a later run resuming a page that never existed.
- manager = _manager()
-
- rows, calls = self._run(
+ result = self._driver().run(
+ "stats",
[_response([{"year": "2023", "month": "8", "day": "16", "nps": "50.0"}])],
- manager,
- endpoint="stats",
)
- assert [row["day"] for row in rows] == ["16"]
- assert _urls(calls) == [build_stats_url("acme")]
- manager.save_state.assert_not_called()
+ assert result.raised is None
+ assert [row["day"] for row in result.rows] == ["16"]
+ assert result.urls == [build_stats_url("acme")]
+ assert result.saved_states == []
def test_unknown_endpoint_raises(self) -> None:
- with pytest.raises(ValueError, match="Unknown AskNicely endpoint"):
- asknicely_source(
- subdomain="acme",
- api_key="key",
- endpoint="nope",
- team_id=1,
- job_id="job-1",
- resumable_source_manager=_manager(),
- )
+ result = self._driver().run("nope", [])
+ assert isinstance(result.raised, ValueError)
+ assert "Unknown AskNicely endpoint" in str(result.raised)
+ assert result.requests == []
def test_sync_session_disables_capture_and_redirects(self) -> None:
# Survey bodies stay out of HTTP sample capture, and the X-apikey header must never be
# replayed to a redirect target.
- session = mock.MagicMock()
- _wire(session, [_response([])])
- with mock.patch(f"{MODULE}.make_tracked_session", return_value=session) as make_session:
- _rows(
- asknicely_source(
- subdomain="acme",
- api_key="key",
- endpoint="responses",
- team_id=1,
- job_id="job-1",
- resumable_source_manager=_manager(),
- )
- )
- assert make_session.call_args.kwargs["capture"] is False
- assert make_session.call_args.kwargs["allow_redirects"] is False
+ result = self._driver().run("responses", [_response([])])
+ assert result.raised is None
+ assert result.session_options[0]["capture"] is False
+ assert result.session_options[0]["allow_redirects"] is False
def test_validate_credentials_session_disables_redirects(self) -> None:
- session = mock.MagicMock()
- session.get.return_value = mock.MagicMock(status_code=200)
- with mock.patch(f"{MODULE}.make_tracked_session", return_value=session) as make_session:
- validate_credentials("acme", "key")
- assert make_session.call_args.kwargs["allow_redirects"] is False
- assert make_session.call_args.kwargs["capture"] is False
+ with scripted_network([ScriptedResponse(status=200)]) as network:
+ assert validate_credentials("acme", "key") == (True, None)
+ assert network.session_options[0]["allow_redirects"] is False
+ assert network.session_options[0]["capture"] is False
@pytest.mark.parametrize(
("status_code", "expected_valid", "expected_message_fragment"),
@@ -278,10 +207,9 @@ class TestAsknicely:
def test_validate_credentials_status_mapping(
self, status_code: int, expected_valid: bool, expected_message_fragment: str | None
) -> None:
- session = mock.MagicMock()
- session.get.return_value = mock.MagicMock(status_code=status_code)
-
- with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ response = ScriptedResponse(status=status_code)
+ script = always(response) if status_code == 500 else [response]
+ with scripted_network(script):
is_valid, error_message = validate_credentials("acme", "key")
assert is_valid is expected_valid
@@ -291,11 +219,11 @@ class TestAsknicely:
assert error_message is not None and expected_message_fragment in error_message
def test_validate_credentials_rejects_invalid_subdomain(self) -> None:
- with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ with scripted_network([]) as network:
# An invalid subdomain raises inside build_responses_url before any request is made,
# and validate_credentials swallows it into a (False, message) result.
is_valid, error_message = validate_credentials("bad domain", "key")
assert is_valid is False
assert error_message is not None
- mock_session.return_value.get.assert_not_called()
+ assert network.requests_log == []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/tests/test_asknicely_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/tests/test_asknicely_source.py
index fbb2c2c9749c..a58abcaa5250 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/tests/test_asknicely_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/asknicely/tests/test_asknicely_source.py
@@ -3,8 +3,13 @@ from typing import Any
import pytest
from unittest import mock
+from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.asknicely import build_responses_url
from products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.source import AsknicelySource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.asknicely import (
AsknicelySourceConfig,
@@ -104,12 +109,15 @@ class TestAsknicelySource:
db_incremental_field_last_value=1700000000,
)
- @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.asknicely.source.asknicely_source")
- def test_source_for_pipeline_drops_last_value_on_full_refresh(self, mock_source: mock.MagicMock) -> None:
+ def test_source_for_pipeline_drops_last_value_on_full_refresh(self) -> None:
# A stale watermark left over from a previous incremental run must not leak into a
# full-refresh sync, or the refresh would silently skip older responses.
- inputs = _make_inputs(should_use_incremental_field=False, db_incremental_field_last_value=1700000000)
-
- self.source.source_for_pipeline(self.config, mock.MagicMock(spec=ResumableSourceManager), inputs)
+ result = SourceDriver(self.source, self.config).run(
+ "responses",
+ [ScriptedResponse(json={"success": True, "data": []})],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=1700000000,
+ )
- assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+ assert result.raised is None
+ assert result.urls == [build_responses_url("acme", page_number=1, since_time=0)]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/assemblyai/tests/test_assemblyai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/assemblyai/tests/test_assemblyai.py
index 6e5a14f32b5f..cfd20fb48429 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/assemblyai/tests/test_assemblyai.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/assemblyai/tests/test_assemblyai.py
@@ -1,77 +1,34 @@
-import json
-from collections.abc import Iterable
-from typing import Any, cast
-from urllib.parse import urlencode
+from typing import Any
import pytest
-from unittest import mock
-
-from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.assemblyai.assemblyai import (
AssemblyAIResumeConfig,
_pinned_url,
- assemblyai_source,
base_url_for_region,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.assemblyai.settings import ENDPOINTS
-
-# RESTClient (list pagination and per-transcript hydration) builds its session via
-# make_tracked_session in the rest_client module.
-CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
-# validate_credentials builds its own tracked session in the assemblyai module.
-ASSEMBLYAI_SESSION_PATCH = (
- "products.warehouse_sources.backend.temporal.data_imports.sources.assemblyai.assemblyai.make_tracked_session"
+from products.warehouse_sources.backend.temporal.data_imports.sources.assemblyai.source import AssemblyAISource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.assemblyai import (
+ AssemblyAISourceConfig,
)
US_LIST_URL = "https://api.assemblyai.com/v2/transcript?limit=200"
-def _make_manager(resume_state: AssemblyAIResumeConfig | None = None) -> mock.MagicMock:
- manager = mock.MagicMock()
- manager.can_resume.return_value = resume_state is not None
- manager.load_state.return_value = resume_state
- return manager
-
-
-def _list_page(items: list[dict[str, Any]], next_url: str | None) -> dict[str, Any]:
- return {"transcripts": items, "page_details": {"next_url": next_url}}
-
-
-def _wire(session: mock.MagicMock, responses: dict[str, dict[str, Any]]) -> list[str]:
- """Wire a mock session that routes each request to a response body by its full URL.
-
- URLs are snapshotted at prepare_request time (the params dict is mutated in place across
- pages, so inspecting it after the run would only show the final state).
- """
- session.headers = {}
- requested: list[str] = []
-
- def _prepare(request: Any) -> mock.MagicMock:
- url = request.url
- if request.params:
- url = f"{url}?{urlencode(request.params)}"
- requested.append(url)
- prepared = mock.MagicMock()
- prepared.url = url
- return prepared
-
- def _send(prepared: Any, **kwargs) -> Response:
- resp = Response()
- resp.status_code = 200
- resp.url = prepared.url
- resp._content = json.dumps(responses[prepared.url]).encode()
- return resp
+def _driver() -> SourceDriver:
+ return SourceDriver(AssemblyAISource(), AssemblyAISourceConfig(api_key="key", region="us"))
- session.prepare_request.side_effect = _prepare
- session.send.side_effect = _send
- return requested
-
-def _batches(api_key: str, region: str | None, endpoint: str, manager: mock.MagicMock) -> list[list[dict[str, Any]]]:
- response = assemblyai_source(api_key, region, endpoint, team_id=1, job_id="j", resumable_source_manager=manager)
- return list(cast("Iterable[list[dict[str, Any]]]", response.items()))
+def _list_page(items: list[dict[str, Any]], next_url: str | None) -> ScriptedResponse:
+ return ScriptedResponse(json={"transcripts": items, "page_details": {"next_url": next_url}})
class TestBaseUrlForRegion:
@@ -119,134 +76,119 @@ class TestPinnedUrl:
class TestValidateCredentials:
@pytest.mark.parametrize("status_code, expected", [(200, True), (401, False), (403, False), (500, False)])
- @mock.patch(ASSEMBLYAI_SESSION_PATCH)
- def test_status_mapping(self, mock_session: mock.MagicMock, status_code: int, expected: bool) -> None:
- mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)
- assert validate_credentials("key", "us") is expected
-
- @mock.patch(ASSEMBLYAI_SESSION_PATCH)
- def test_swallows_exceptions(self, mock_session: mock.MagicMock) -> None:
- mock_session.return_value.get.side_effect = Exception("boom")
- assert validate_credentials("key", "us") is False
-
- @mock.patch(ASSEMBLYAI_SESSION_PATCH)
- def test_eu_region_probes_eu_host_with_raw_key(self, mock_session: mock.MagicMock) -> None:
- mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
- validate_credentials("key", "eu")
- call = mock_session.return_value.get.call_args
- assert call.args[0].startswith("https://api.eu.assemblyai.com/v2/transcript")
+ def test_status_mapping(self, status_code: int, expected: bool) -> None:
+ with scripted_network(always(ScriptedResponse(status=status_code))):
+ assert validate_credentials("key", "us") is expected
+
+ def test_swallows_exceptions(self) -> None:
+ with scripted_network([ConnectionResetError("boom")]):
+ assert validate_credentials("key", "us") is False
+
+ def test_eu_region_probes_eu_host_with_raw_key(self) -> None:
+ with scripted_network([ScriptedResponse()]) as network:
+ validate_credentials("key", "eu")
+
+ assert network.requests_log[0].url.startswith("https://api.eu.assemblyai.com/v2/transcript")
# AssemblyAI takes the raw API key in Authorization — no "Bearer" prefix.
- assert call.kwargs["headers"]["Authorization"] == "key"
+ assert network.requests_log[0].headers["authorization"] == "key"
class TestAssemblyAIRows:
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_lists_then_hydrates_each_transcript(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
+ def test_lists_then_hydrates_each_transcript(self) -> None:
next_url = "https://api.assemblyai.com/v2/transcript?limit=200&before_id=t2"
- requested = _wire(
- session,
- {
- US_LIST_URL: _list_page([{"id": "t1"}, {"id": "t2"}], next_url),
- "https://api.assemblyai.com/v2/transcript/t1": {"id": "t1", "text": "hello", "status": "completed"},
- "https://api.assemblyai.com/v2/transcript/t2": {"id": "t2", "text": "world", "status": "completed"},
- next_url: _list_page([{"id": "t3"}], None),
- "https://api.assemblyai.com/v2/transcript/t3": {"id": "t3", "text": "again", "status": "completed"},
- },
+ result = _driver().run(
+ "transcripts",
+ [
+ _list_page([{"id": "t1"}, {"id": "t2"}], next_url),
+ ScriptedResponse(json={"id": "t1", "text": "hello", "status": "completed"}),
+ ScriptedResponse(json={"id": "t2", "text": "world", "status": "completed"}),
+ _list_page([{"id": "t3"}], None),
+ ScriptedResponse(json={"id": "t3", "text": "again", "status": "completed"}),
+ ],
)
- batches = _batches("key", "us", "transcripts", _make_manager())
-
- rows = [row for batch in batches for row in batch]
+ assert result.raised is None
# Rows are the hydrated full objects, not the list summaries.
- assert [r["id"] for r in rows] == ["t1", "t2", "t3"]
- assert all("text" in r for r in rows)
- assert requested[0] == US_LIST_URL
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_saves_state_after_each_page_only_when_more_remain(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
+ assert [row["id"] for row in result.rows] == ["t1", "t2", "t3"]
+ assert all("text" in row for row in result.rows)
+ assert result.urls == [
+ US_LIST_URL,
+ "https://api.assemblyai.com/v2/transcript/t1",
+ "https://api.assemblyai.com/v2/transcript/t2",
+ next_url,
+ "https://api.assemblyai.com/v2/transcript/t3",
+ ]
+
+ def test_saves_state_after_each_page_only_when_more_remain(self) -> None:
next_url = "https://api.assemblyai.com/v2/transcript?limit=200&before_id=t1"
- _wire(
- session,
- {
- US_LIST_URL: _list_page([{"id": "t1"}], next_url),
- "https://api.assemblyai.com/v2/transcript/t1": {"id": "t1", "text": "hello"},
- next_url: _list_page([{"id": "t2"}], None),
- "https://api.assemblyai.com/v2/transcript/t2": {"id": "t2", "text": "world"},
- },
+ result = _driver().run(
+ "transcripts",
+ [
+ _list_page([{"id": "t1"}], next_url),
+ ScriptedResponse(json={"id": "t1", "text": "hello"}),
+ _list_page([{"id": "t2"}], None),
+ ScriptedResponse(json={"id": "t2", "text": "world"}),
+ ],
)
- manager = _make_manager()
- _batches("key", "us", "transcripts", manager)
-
+ assert result.raised is None
# Only the first page has a next_url, so state is saved exactly once, pointing at page two.
- manager.save_state.assert_called_once()
- assert manager.save_state.call_args.args[0] == AssemblyAIResumeConfig(next_url=next_url)
+ assert result.saved_states == [AssemblyAIResumeConfig(next_url=next_url)]
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_resumes_from_saved_state(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
+ def test_resumes_from_saved_state(self) -> None:
resume_url = "https://api.assemblyai.com/v2/transcript?limit=200&before_id=resume"
- requested = _wire(
- session,
- {
- resume_url: _list_page([{"id": "r1"}], None),
- "https://api.assemblyai.com/v2/transcript/r1": {"id": "r1", "text": "resumed"},
- },
+ result = _driver().run(
+ "transcripts",
+ [
+ _list_page([{"id": "r1"}], None),
+ ScriptedResponse(json={"id": "r1", "text": "resumed"}),
+ ],
+ resume_state=AssemblyAIResumeConfig(next_url=resume_url),
)
- manager = _make_manager(AssemblyAIResumeConfig(next_url=resume_url))
- batches = _batches("key", "us", "transcripts", manager)
-
- rows = [row for batch in batches for row in batch]
- assert [r["id"] for r in rows] == ["r1"]
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == ["r1"]
# The initial list URL must never be requested when resuming.
- assert US_LIST_URL not in requested
- assert requested[0] == resume_url
+ assert US_LIST_URL not in result.urls
+ assert result.urls[0] == resume_url
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_empty_list_yields_nothing(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- _wire(session, {US_LIST_URL: _list_page([], None)})
+ def test_empty_list_yields_nothing(self) -> None:
+ result = _driver().run("transcripts", [_list_page([], None)])
- manager = _make_manager()
- assert _batches("key", "us", "transcripts", manager) == []
- manager.save_state.assert_not_called()
+ assert result.raised is None
+ assert result.rows == []
+ assert result.saved_states == []
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_empty_page_stops_even_with_next_url(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- _wire(session, {US_LIST_URL: _list_page([], "https://api.assemblyai.com/v2/transcript?before_id=x")})
+ def test_empty_page_stops_even_with_next_url(self) -> None:
+ result = _driver().run("transcripts", [_list_page([], "https://api.assemblyai.com/v2/transcript?before_id=x")])
- manager = _make_manager()
- assert _batches("key", "us", "transcripts", manager) == []
+ assert result.raised is None
+ assert result.rows == []
# The walk ends on the empty page — the advertised next page is never fetched.
- assert session.send.call_count == 1
- manager.save_state.assert_not_called()
-
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_tampered_next_url_is_rejected(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- _wire(
- session,
- {
- US_LIST_URL: _list_page([{"id": "t1"}], "https://evil.example.com/v2/transcript"),
- "https://api.assemblyai.com/v2/transcript/t1": {"id": "t1", "text": "hello"},
- },
+ assert result.urls == [US_LIST_URL]
+ assert result.saved_states == []
+
+ def test_tampered_next_url_is_rejected(self) -> None:
+ result = _driver().run(
+ "transcripts",
+ [
+ _list_page([{"id": "t1"}], "https://evil.example.com/v2/transcript"),
+ ScriptedResponse(json={"id": "t1", "text": "hello"}),
+ ],
)
- with pytest.raises(ValueError, match="not on the selected host"):
- _batches("key", "us", "transcripts", _make_manager())
+ assert isinstance(result.raised, ValueError)
+ assert "not on the selected host" in str(result.raised)
- @mock.patch(CLIENT_SESSION_PATCH)
- def test_tampered_saved_state_is_rejected(self, MockSession: mock.MagicMock) -> None:
- session = MockSession.return_value
- _wire(session, {})
+ def test_tampered_saved_state_is_rejected(self) -> None:
+ result = _driver().run(
+ "transcripts",
+ [],
+ resume_state=AssemblyAIResumeConfig(next_url="https://evil.example.com/v2/transcript"),
+ )
- manager = _make_manager(AssemblyAIResumeConfig(next_url="https://evil.example.com/v2/transcript"))
- with pytest.raises(ValueError, match="not on the selected host"):
- _batches("key", "us", "transcripts", manager)
+ assert isinstance(result.raised, ValueError)
+ assert "not on the selected host" in str(result.raised)
class TestAssemblyAISource:
@@ -254,12 +196,13 @@ class TestAssemblyAISource:
assert ENDPOINTS == ("transcripts",)
def test_source_response_shape(self) -> None:
- response = assemblyai_source(
- "key", "us", "transcripts", team_id=1, job_id="j", resumable_source_manager=_make_manager()
- )
- assert response.name == "transcripts"
- assert response.primary_keys == ["id"]
- assert response.partition_mode == "datetime"
- assert response.partition_keys == ["created"]
+ result = _driver().run("transcripts", [_list_page([], None)])
+
+ assert result.raised is None
+ assert result.response is not None
+ assert result.response.name == "transcripts"
+ assert result.response.primary_keys == ["id"]
+ assert result.response.partition_mode == "datetime"
+ assert result.response.partition_keys == ["created"]
# The list endpoint returns newest-first and exposes no ascending sort.
- assert response.sort_mode == "desc"
+ assert result.response.sort_mode == "desc"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/tests/test_astronomer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/tests/test_astronomer.py
index ab6f0899d51a..53d7909f753e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/tests/test_astronomer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/astronomer/tests/test_astronomer.py
@@ -1,25 +1,22 @@
-from collections.abc import Iterable
-from typing import Any, cast
-from urllib.parse import parse_qs, urlparse
-
import pytest
-from unittest.mock import MagicMock, patch
-import responses
from requests.exceptions import HTTPError
from products.warehouse_sources.backend.temporal.data_imports.sources.astronomer.astronomer import (
AstronomerResumeConfig,
- astronomer_source,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.astronomer.source import AstronomerSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
RESTClientRetryableError,
)
-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 UnknownResourceError
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ scripted_network,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.astronomer import (
AstronomerSourceConfig,
)
@@ -28,65 +25,80 @@ BASE = "https://api.astronomer.io/v1/organizations/example-org"
CONFIG = AstronomerSourceConfig(api_token="test-token", organization_id="example-org")
-def manager(state: dict[str, Any] | None = None) -> MagicMock:
- result = MagicMock(spec=ResumableSourceManager)
- result.can_resume.return_value = state is not None
- result.load_state.return_value = AstronomerResumeConfig(paginator_state=state) if state is not None else None
- return result
-
-
-def items(response: SourceResponse) -> Iterable[Any]:
- return cast(Iterable[Any], response.items())
+def driver(config: AstronomerSourceConfig = CONFIG) -> SourceDriver:
+ return SourceDriver(AstronomerSource(), config)
@pytest.mark.parametrize("table", ["deployments", "workspaces", "clusters"])
@pytest.mark.parametrize("last_page_size", [0, 1, 100])
def test_list_pagination_auth_and_terminal_page(table: str, last_page_size: int) -> None:
rows = [{"id": f"row-{index}"} for index in range(100 + last_page_size)]
- responses.get(f"{BASE}/{table}", json={table: rows[:100], "totalCount": 200})
- responses.get(f"{BASE}/{table}", json={table: rows[100:], "totalCount": len(rows)})
- checkpoint = manager()
- result = astronomer_source(CONFIG, table, 1, "test-job", checkpoint)
-
- assert [row for page in items(result) for row in page] == rows
- assert len(responses.calls) == 2
- for offset, call in zip([0, 100], responses.calls):
- assert call.request.headers["Authorization"] == "Bearer test-token"
- assert parse_qs(urlparse(call.request.url).query) == {
- "offset": [str(offset)],
- "limit": ["100"],
- "sorts": ["createdAt:asc"],
- }
- checkpoint.save_state.assert_called_once_with(AstronomerResumeConfig(paginator_state={"offset": 100}))
-
-
+ result = driver().run(
+ table,
+ [
+ ScriptedResponse(json={table: rows[:100], "totalCount": 200}),
+ ScriptedResponse(json={table: rows[100:], "totalCount": len(rows)}),
+ ],
+ )
+
+ assert result.raised is None
+ assert result.rows == rows
+ assert result.paths == [f"/v1/organizations/example-org/{table}"] * 2
+ assert result.params("offset") == ["0", "100"]
+ assert result.params("limit") == ["100", "100"]
+ assert result.params("sorts") == ["createdAt:asc", "createdAt:asc"]
+ assert result.queries == [
+ {"offset": ("0",), "limit": ("100",), "sorts": ("createdAt:asc",)},
+ {"offset": ("100",), "limit": ("100",), "sorts": ("createdAt:asc",)},
+ ]
+ assert all(request.headers["authorization"] == "Bearer test-token" for request in result.requests)
+ assert result.saved_states == [AstronomerResumeConfig(paginator_state={"offset": 100})]
+
+
def test_resume_starts_at_saved_offset() -> None:
- responses.get(f"{BASE}/workspaces", json={"workspaces": [{"id": "last"}], "totalCount": 201})
- result = astronomer_source(CONFIG, "workspaces", 1, "test-job", manager({"offset": 200}))
- assert [row for page in items(result) for row in page] == [{"id": "last"}]
- assert parse_qs(urlparse(responses.calls[0].request.url).query)["offset"] == ["200"]
+ result = driver().run(
+ "workspaces",
+ [ScriptedResponse(json={"workspaces": [{"id": "last"}], "totalCount": 201})],
+ resume_state=AstronomerResumeConfig(paginator_state={"offset": 200}),
+ )
+
+ assert result.raised is None
+ assert result.rows == [{"id": "last"}]
+ assert result.params("offset") == ["200"]
def test_deploy_history_paginates_each_parent_and_preserves_unique_keys() -> None:
- responses.get(f"{BASE}/deployments", json={"deployments": [{"id": "first"}, {"id": "second"}], "totalCount": 2})
first_page = [{"id": f"deploy-{index}"} for index in range(100)]
- responses.get(f"{BASE}/deployments/first/deploys", json={"deploys": first_page, "totalCount": 101})
- responses.get(f"{BASE}/deployments/first/deploys", json={"deploys": [{"id": "last"}], "totalCount": 101})
- responses.get(f"{BASE}/deployments/second/deploys", json={"deploys": [{"id": "last"}], "totalCount": 1})
- checkpoint = manager()
- result = astronomer_source(CONFIG, "deploys", 1, "test-job", checkpoint)
- rows = [row for page in items(result) for row in page]
-
- assert len(rows) == 102
- assert rows[-2:] == [{"id": "last", "deploymentId": "first"}, {"id": "last", "deploymentId": "second"}]
- assert len({tuple(row[key] for key in result.primary_keys or []) for row in rows}) == 102
- for offset, call in zip([0, 100, 0], responses.calls[1:]):
- assert parse_qs(urlparse(call.request.url).query) == {"offset": [str(offset)], "limit": ["100"]}
- assert call.request.headers["Authorization"] == "Bearer test-token"
- states = [call.args[0].paginator_state for call in checkpoint.save_state.call_args_list]
+ result = driver().run(
+ "deploys",
+ [
+ ScriptedResponse(json={"deployments": [{"id": "first"}, {"id": "second"}], "totalCount": 2}),
+ ScriptedResponse(json={"deploys": first_page, "totalCount": 101}),
+ ScriptedResponse(json={"deploys": [{"id": "last"}], "totalCount": 101}),
+ ScriptedResponse(json={"deploys": [{"id": "last"}], "totalCount": 1}),
+ ],
+ )
+
+ assert result.raised is None
+ assert len(result.rows) == 102
+ assert result.rows[-2:] == [{"id": "last", "deploymentId": "first"}, {"id": "last", "deploymentId": "second"}]
+ assert result.response is not None
+ assert len({tuple(row[key] for key in result.response.primary_keys or []) for row in result.rows}) == 102
+ assert result.paths == [
+ "/v1/organizations/example-org/deployments",
+ "/v1/organizations/example-org/deployments/first/deploys",
+ "/v1/organizations/example-org/deployments/first/deploys",
+ "/v1/organizations/example-org/deployments/second/deploys",
+ ]
+ assert result.params("offset")[1:] == ["0", "100", "0"]
+ assert result.params("limit")[1:] == ["100", "100", "100"]
+ assert result.queries[1:] == [
+ {"offset": ("0",), "limit": ("100",)},
+ {"offset": ("100",), "limit": ("100",)},
+ {"offset": ("0",), "limit": ("100",)},
+ ]
+ assert all(request.headers["authorization"] == "Bearer test-token" for request in result.requests[1:])
+ states = [state.paginator_state for state in result.saved_states]
assert any(state["child_state"] == {"offset": 100} for state in states)
assert states[-1]["completed"] == [
"organizations/example-org/deployments/first/deploys",
@@ -94,21 +106,29 @@ def test_deploy_history_paginates_each_parent_and_preserves_unique_keys() -> Non
]
def test_deploy_resume_skips_completed_parents_and_continues_child_page() -> None:
- responses.get(f"{BASE}/deployments", json={"deployments": [{"id": "first"}, {"id": "second"}], "totalCount": 2})
- responses.get(f"{BASE}/deployments/second/deploys", json={"deploys": [{"id": "last"}], "totalCount": 101})
- checkpoint = manager(
- {
- "completed": ["organizations/example-org/deployments/first/deploys"],
- "current": "organizations/example-org/deployments/second/deploys",
- "child_state": {"offset": 100},
- }
+ result = driver().run(
+ "deploys",
+ [
+ ScriptedResponse(json={"deployments": [{"id": "first"}, {"id": "second"}], "totalCount": 2}),
+ ScriptedResponse(json={"deploys": [{"id": "last"}], "totalCount": 101}),
+ ],
+ resume_state=AstronomerResumeConfig(
+ paginator_state={
+ "completed": ["organizations/example-org/deployments/first/deploys"],
+ "current": "organizations/example-org/deployments/second/deploys",
+ "child_state": {"offset": 100},
+ }
+ ),
)
- result = astronomer_source(CONFIG, "deploys", 1, "test-job", checkpoint)
- assert [row for page in items(result) for row in page] == [{"id": "last", "deploymentId": "second"}]
- assert len(responses.calls) == 2
- assert parse_qs(urlparse(responses.calls[1].request.url).query)["offset"] == ["100"]
+
+ assert result.raised is None
+ assert result.rows == [{"id": "last", "deploymentId": "second"}]
+ assert result.paths == [
+ "/v1/organizations/example-org/deployments",
+ "/v1/organizations/example-org/deployments/second/deploys",
+ ]
+ assert result.params("offset")[1] == "100"
@pytest.mark.parametrize(
@@ -121,32 +141,33 @@ def test_deploy_resume_skips_completed_parents_and_continues_child_page() -> Non
(404, None, False, "organization ID"),
],
)
def test_credential_probe_status_mapping(status: int, schema: str | None, valid: bool, message: str | None) -> None:
table = schema or "deployments"
- responses.get(f"{BASE}/{table}", json={table: []}, status=status)
- actual_valid, actual_message = validate_credentials(CONFIG, schema)
+ with scripted_network([ScriptedResponse(json={table: []}, status=status)]) as network:
+ actual_valid, actual_message = validate_credentials(CONFIG, schema)
+
assert actual_valid is valid
if message:
assert actual_message and message in actual_message
else:
assert actual_message is None
- assert len(responses.calls) == 1
- assert parse_qs(urlparse(responses.calls[0].request.url).query) == {"limit": ["1"]}
- assert responses.calls[0].request.headers["Authorization"] == "Bearer test-token"
+ assert len(network.requests_log) == 1
+ assert network.requests_log[0].url.startswith(f"{BASE}/{table}?")
+ assert network.requests_log[0].param("limit") == "1"
+ assert network.requests_log[0].query == {"limit": ("1",)}
+ assert network.requests_log[0].headers["authorization"] == "Bearer test-token"
@pytest.mark.parametrize("parent_status, child_status", [(403, None), (200, 403), (200, 200), (200, None)])
def test_deploy_permission_probe(parent_status: int, child_status: int | None) -> None:
- responses.get(
- f"{BASE}/deployments",
- json={"deployments": [] if child_status is None else [{"id": "first"}]},
- status=parent_status,
- )
+ script = [
+ ScriptedResponse(json={"deployments": [] if child_status is None else [{"id": "first"}]}, status=parent_status)
+ ]
if child_status is not None:
- responses.get(f"{BASE}/deployments/first/deploys", json={"deploys": []}, status=child_status)
- valid, message = validate_credentials(CONFIG, "deploys")
+ script.append(ScriptedResponse(json={"deploys": []}, status=child_status))
+ with scripted_network(script):
+ valid, message = validate_credentials(CONFIG, "deploys")
+
assert valid is (parent_status == 200 and child_status != 403)
if parent_status == 403:
assert message and "organization.deployments.get" in message
@@ -157,87 +178,88 @@ def test_deploy_permission_probe(parent_status: int, child_status: int | None) -
@pytest.mark.parametrize("organization_id", ["", "../example", "https://example.com", "a?b", "a#b", "a/b"])
def test_invalid_organization_never_sends_token(organization_id: str) -> None:
config = AstronomerSourceConfig(api_token="test-token", organization_id=organization_id)
- valid, message = validate_credentials(config)
+ with scripted_network([]) as network:
+ valid, message = validate_credentials(config)
+ result = driver(config).run("deployments", [])
+
assert not valid
assert message and "organization ID" in message
- with pytest.raises(ValueError, match="organization ID"):
- astronomer_source(config, "deployments", 1, "test-job", manager())
- assert not responses.calls
+ assert isinstance(result.raised, ValueError)
+ assert "organization ID" in str(result.raised)
+ assert not network.requests_log
+ assert not result.requests
@pytest.mark.parametrize("status", [401, 403, 400, 429, 500])
def test_sync_errors_and_retry_classification(status: int) -> None:
- responses.get(f"{BASE}/deployments", json={"error": "test_error"}, status=status)
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.RESTClient._send_request.retry.sleep"
- ):
- result = astronomer_source(CONFIG, "deployments", 1, "test-job", manager())
- expected = RESTClientRetryableError if status in (429, 500) else HTTPError
- with pytest.raises(expected) as caught:
- list(items(result))
+ response = ScriptedResponse(json={"error": "test_error"}, status=status)
+ script = always(response) if status in (429, 500) else [response]
+ result = driver().run("deployments", script)
+
+ expected = RESTClientRetryableError if status in (429, 500) else HTTPError
+ assert isinstance(result.raised, expected)
mapped = [
message
for pattern, message in AstronomerSource().get_non_retryable_errors().items()
- if pattern in str(caught.value)
+ if pattern in str(result.raised)
]
assert bool(mapped) is (status in (401, 403))
- assert (len(responses.calls) > 1) is (status in (429, 500))
+ assert (len(result.requests) > 1) is (status in (429, 500))
def test_validation_does_not_hide_unexpected_http_errors() -> None:
- responses.get(f"{BASE}/deployments", json={"error": "bad_request"}, status=400)
- with pytest.raises(HTTPError):
- validate_credentials(CONFIG)
+ with scripted_network([ScriptedResponse(json={"error": "bad_request"}, status=400)]):
+ with pytest.raises(HTTPError):
+ validate_credentials(CONFIG)
@pytest.mark.parametrize("operation", ["validate", "sync"])
def test_unknown_table(operation: str) -> None:
- with pytest.raises(UnknownResourceError):
- if operation == "validate":
- validate_credentials(CONFIG, "unknown")
- else:
- astronomer_source(CONFIG, "unknown", 1, "test-job", manager())
- assert not responses.calls
+ if operation == "validate":
+ with scripted_network([]) as network:
+ with pytest.raises(UnknownResourceError):
+ validate_credentials(CONFIG, "unknown")
+ assert not network.requests_log
+ else:
+ result = driver().run("unknown", [])
+ assert isinstance(result.raised, UnknownResourceError)
+ assert not result.requests
@pytest.mark.parametrize("table", ["deployments", "deploys"])
def test_warehouse_rows_exclude_environment_values_and_upload_urls(table: str) -> None:
- path = table
+ script: list[ScriptedResponse] = []
if table == "deploys":
- responses.get(f"{BASE}/deployments", json={"deployments": [{"id": "first"}], "totalCount": 1})
- path = "deployments/first/deploys"
- responses.get(
- f"{BASE}/{path}",
- json={
- table: [
- {
- "id": "row-1",
- "status": "DEPLOYED",
- "environmentVariables": [{"key": "SECRET", "value": "fake-secret", "isSecret": True}],
- "bundleUploadUrl": "https://example.com/upload?token=fake",
- "dagsUploadUrl": "https://example.com/upload?token=fake",
- }
- ],
- "totalCount": 1,
- },
+ script.append(ScriptedResponse(json={"deployments": [{"id": "first"}], "totalCount": 1}))
+ script.append(
+ ScriptedResponse(
+ json={
+ table: [
+ {
+ "id": "row-1",
+ "status": "DEPLOYED",
+ "environmentVariables": [{"key": "SECRET", "value": "fake-secret", "isSecret": True}],
+ "bundleUploadUrl": "https://example.com/upload?token=fake",
+ "dagsUploadUrl": "https://example.com/upload?token=fake",
+ }
+ ],
+ "totalCount": 1,
+ }
+ )
)
- result = astronomer_source(CONFIG, table, 1, "test-job", manager())
+ result = driver().run(table, script)
+
expected = {"id": "row-1", "status": "DEPLOYED"}
if table == "deploys":
expected["deploymentId"] = "first"
- assert [row for page in items(result) for row in page] == [expected]
+ assert result.raised is None
+ assert result.rows == [expected]
def test_missing_collection_fails_instead_of_replacing_table_with_no_rows() -> None:
- responses.get(f"{BASE}/deployments", json={"unexpected": []})
- result = astronomer_source(CONFIG, "deployments", 1, "test-job", manager())
- with pytest.raises(ValueError, match="Required data_selector"):
- list(items(result))
+ result = driver().run("deployments", [ScriptedResponse(json={"unexpected": []})])
+
+ assert isinstance(result.raised, ValueError)
+ assert "Required data_selector" in str(result.raised)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/attio/tests/test_attio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/attio/tests/test_attio.py
index cc84820e932e..6ed2e29d99e2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/attio/tests/test_attio.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/attio/tests/test_attio.py
@@ -1,20 +1,16 @@
-import copy
-import json
-from collections.abc import Iterable
-from typing import Any, cast
-
import pytest
-from unittest.mock import MagicMock, patch
-
-from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.attio.attio import (
AttioResumeConfig,
- attio_source,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.attio.settings import ATTIO_ENDPOINTS
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.attio.source import AttioSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.attio import AttioSourceConfig
class TestValidateCredentials:
@@ -30,90 +26,65 @@ class TestValidateCredentials:
assert "ordinal not in range" not in (msg or "")
-def _page(endpoint: str, start: int, count: int) -> Response:
+def _page(endpoint: str, start: int, count: int) -> ScriptedResponse:
primary_key = ATTIO_ENDPOINTS[endpoint].primary_key
rows = [
{"id": {"workspace_id": "ws", primary_key: f"row-{i}"}, "created_at": "2024-01-01"}
for i in range(start, start + count)
]
- resp = Response()
- resp.status_code = 200
- resp._content = json.dumps({"data": rows}).encode()
- resp.headers["Content-Type"] = "application/json"
- return resp
-
-
-def _make_manager(resume: AttioResumeConfig | None = None) -> MagicMock:
- manager = MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = resume is not None
- manager.load_state.return_value = resume
- return manager
+ return ScriptedResponse(json={"data": rows})
class TestAttioResume:
- def _drive(
- self, endpoint: str, manager: MagicMock, responses: list[Response]
- ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
- sent: list[dict[str, Any]] = []
- response_iter = iter(responses)
-
- def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
- # The paginator mutates one request object across pages, so copy what each send carries.
- sent.append(copy.deepcopy(request.json if request.method == "POST" else request.params))
- return next(response_iter)
-
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
- ) as MockSession:
- mock_session = MockSession.return_value
- mock_session.headers = {}
- mock_session.prepare_request.side_effect = lambda req: req
- mock_session.send.side_effect = fake_send
-
- response = attio_source(
- api_key="key",
- endpoint=endpoint,
- team_id=1,
- job_id="job",
- resumable_source_manager=manager,
- )
- rows = [row for page in cast(Iterable[list[dict[str, Any]]], response.items()) for row in page]
- return sent, rows
+ @staticmethod
+ def _driver() -> SourceDriver:
+ return SourceDriver(AttioSource(), AttioSourceConfig(api_key="key"))
@pytest.mark.parametrize("endpoint", ["companies", "people", "deals", "notes", "tasks"])
def test_fresh_run_stages_next_offset_after_each_page(self, endpoint: str) -> None:
limit = ATTIO_ENDPOINTS[endpoint].page_size
- manager = _make_manager()
responses = [_page(endpoint, 0, limit), _page(endpoint, limit, limit), _page(endpoint, 2 * limit, 3)]
- sent, rows = self._drive(endpoint, manager, responses)
+ result = self._driver().run(endpoint, responses)
+ is_post = ATTIO_ENDPOINTS[endpoint].method == "POST"
- assert [request["offset"] for request in sent] == [0, limit, 2 * limit]
- assert all(request["limit"] == limit for request in sent)
- assert len(rows) == 2 * limit + 3
- assert rows[-1][ATTIO_ENDPOINTS[endpoint].primary_key] == f"row-{2 * limit + 2}"
- assert [call.args[0] for call in manager.save_state.call_args_list] == [
+ assert result.raised is None
+ assert [request.json()["offset"] if is_post else request.param("offset") for request in result.requests] == [
+ offset if is_post else str(offset) for offset in (0, limit, 2 * limit)
+ ]
+ assert all(
+ (request.json()["limit"] if is_post else request.param("limit")) == (limit if is_post else str(limit))
+ for request in result.requests
+ )
+ assert len(result.rows) == 2 * limit + 3
+ assert result.rows[-1][ATTIO_ENDPOINTS[endpoint].primary_key] == f"row-{2 * limit + 2}"
+ assert result.saved_states == [
AttioResumeConfig(offset=limit),
AttioResumeConfig(offset=2 * limit),
]
- manager.load_state.assert_not_called()
@pytest.mark.parametrize("endpoint", ["companies", "people", "lists", "notes", "tasks", "workspace_members"])
def test_resumed_run_starts_from_saved_offset(self, endpoint: str) -> None:
limit = ATTIO_ENDPOINTS[endpoint].page_size
- manager = _make_manager(AttioResumeConfig(offset=2 * limit))
responses = [_page(endpoint, 2 * limit, limit), _page(endpoint, 3 * limit, 1)]
- sent, rows = self._drive(endpoint, manager, responses)
+ result = self._driver().run(endpoint, responses, resume_state=AttioResumeConfig(offset=2 * limit))
+ is_post = ATTIO_ENDPOINTS[endpoint].method == "POST"
- assert [request["offset"] for request in sent] == [2 * limit, 3 * limit]
- assert rows[0][ATTIO_ENDPOINTS[endpoint].primary_key] == f"row-{2 * limit}"
- assert [call.args[0] for call in manager.save_state.call_args_list] == [AttioResumeConfig(offset=3 * limit)]
+ assert result.raised is None
+ assert [request.json()["offset"] if is_post else request.param("offset") for request in result.requests] == [
+ offset if is_post else str(offset) for offset in (2 * limit, 3 * limit)
+ ]
+ assert result.rows[0][ATTIO_ENDPOINTS[endpoint].primary_key] == f"row-{2 * limit}"
+ assert result.saved_states == [AttioResumeConfig(offset=3 * limit)]
def test_resumed_query_keeps_sort_order_in_body(self) -> None:
# Offsets only line up across runs when every run asks for the same order.
- manager = _make_manager(AttioResumeConfig(offset=500))
+ result = self._driver().run(
+ "companies", [_page("companies", 500, 1)], resume_state=AttioResumeConfig(offset=500)
+ )
- sent, _ = self._drive("companies", manager, [_page("companies", 500, 1)])
-
- assert sent == [{"sorts": [{"attribute": "created_at", "direction": "asc"}], "offset": 500, "limit": 500}]
+ assert result.raised is None
+ assert [request.json() for request in result.requests] == [
+ {"sorts": [{"attribute": "created_at", "direction": "asc"}], "offset": 500, "limit": 500}
+ ]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/responders.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/responders.py
index 3959093a1ce0..37f2eb84d176 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/responders.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/responders.py
@@ -94,12 +94,19 @@ class ScriptedResponder:
return answer.to_bytes()
-def always(response: ScriptedResponse) -> Callable[[RecordedRequest], ScriptedResponse]:
- """Give every request the same answer.
+def always(answer: ScriptedResponse | BaseException) -> Callable[[RecordedRequest], ScriptedResponse]:
+ """Give every request the same answer, or fail every request with the same error.
- The real stack retries a 429 and a 5xx, so a list with one such answer runs out on the first retry.
+ The real stack retries a 429, a 5xx and a dropped connection, so a list with one such answer runs
+ out on the first retry.
"""
- return lambda _request: response
+
+ def respond(_request: RecordedRequest) -> ScriptedResponse:
+ if isinstance(answer, BaseException):
+ raise answer
+ return answer
+
+ return respond
def route(table: Mapping[str, Sequence[ScriptedResponse]]) -> Callable[[RecordedRequest], ScriptedResponse]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/tests/test_driver.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/tests/test_driver.py
index 989d9e895031..badb4df10adf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/tests/test_driver.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/tests/test_driver.py
@@ -155,6 +155,12 @@ class TestSourceDriver:
assert len(every_time.requests) > 1
assert not isinstance(every_time.raised, UnexpectedRequest)
+ def test_a_dropped_connection_is_retried_and_always_repeats_it(self) -> None:
+ result = _driver().run("rows", always(ConnectionResetError("reset by peer")))
+
+ assert len(result.requests) > 1
+ assert isinstance(result.raised, requests.ConnectionError)
+
class TestScriptedResponse:
@pytest.mark.parametrize(