Skip to content

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

feat(data-warehouse): add a shared driver for source tests (#114350)

Tom Owers63d4fc93bbfe
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/attentive/tests/test_attentive_api_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/attentive/tests/test_attentive_api_client.py
index 4b1e27b55a77..ed352c3c59e9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/attentive/tests/test_attentive_api_client.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/attentive/tests/test_attentive_api_client.py
@@ -6,6 +6,10 @@ from unittest import mock
import requests
from products.warehouse_sources.backend.temporal.data_imports.sources.attentive import api_client
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ scripted_network,
+)
_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.attentive.api_client"
@@ -22,6 +26,10 @@ def _response(status_code: int = 200, body: Any = None) -> mock.MagicMock:
return resp
+URL = "https://ph.example/webhook"
+WEBHOOKS = "/v1/webhooks"
+
+
class TestEventsForResources:
def test_maps_resources_to_event_types(self):
events = api_client._events_for_resources(["sms_sent", "email_opened"])
@@ -56,225 +64,193 @@ class TestValidateCredentials:
class TestCreateWebhook:
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_creates_then_disables_until_signing_key_provided(self, mock_session):
- mock_session.return_value.get.return_value = _response(200, {"webhooks": []})
- mock_session.return_value.post.return_value = _response(201, {"id": "wh-1"})
- mock_session.return_value.put.return_value = _response(200, {"id": "wh-1"})
-
- result = api_client.create_webhook("key", "https://ph.example/webhook", ["sms_sent", "email_opened"])
+ def test_creates_then_disables_until_signing_key_provided(self):
+ with scripted_network(
+ [
+ ScriptedResponse(json={"webhooks": []}),
+ ScriptedResponse(status=201, json={"id": "wh-1"}),
+ ScriptedResponse(json={"id": "wh-1"}),
+ ]
+ ) as network:
+ result = api_client.create_webhook("key", URL, ["sms_sent", "email_opened"])
assert result.success is True
assert result.pending_inputs == ["signing_secret"]
- post_body = mock_session.return_value.post.call_args.kwargs["json"]
- assert post_body == {"url": "https://ph.example/webhook", "events": ["sms.sent", "email.opened"]}
- put_body = mock_session.return_value.put.call_args.kwargs["json"]
- assert put_body["disabled"] is True
+ get, post, put = network.requests_log
+ assert [r.method for r in network.requests_log] == ["GET", "POST", "PUT"]
+ assert get.headers["authorization"] == "Bearer key"
+ assert post.json() == {"url": URL, "events": ["sms.sent", "email.opened"]}
+ assert put.path == f"{WEBHOOKS}/wh-1"
+ assert put.json()["disabled"] is True
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_existing_webhook_short_circuits(self, mock_session):
- mock_session.return_value.get.return_value = _response(
- 200, {"webhooks": [{"id": "wh-1", "url": "https://ph.example/webhook"}]}
- )
-
- result = api_client.create_webhook("key", "https://ph.example/webhook", ["sms_sent"])
+ def test_existing_webhook_short_circuits(self):
+ with scripted_network([ScriptedResponse(json={"webhooks": [{"id": "wh-1", "url": URL}]})]) as network:
+ result = api_client.create_webhook("key", URL, ["sms_sent"])
assert result.success is True
assert result.pending_inputs == ["signing_secret"]
- mock_session.return_value.post.assert_not_called()
+ assert [r.method for r in network.requests_log] == ["GET"]
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_looks_up_id_when_create_response_omits_it(self, mock_session):
+ def test_looks_up_id_when_create_response_omits_it(self):
# First GET checks for an existing webhook (none); second GET is the
# fallback lookup after the create response omits the id.
- mock_session.return_value.get.side_effect = [
- _response(200, {"webhooks": []}),
- _response(200, {"webhooks": [{"id": "wh-9", "url": "https://ph.example/webhook"}]}),
- ]
- mock_session.return_value.post.return_value = _response(201, {})
- mock_session.return_value.put.return_value = _response(200)
-
- result = api_client.create_webhook("key", "https://ph.example/webhook", ["sms_sent"])
+ with scripted_network(
+ [
+ ScriptedResponse(json={"webhooks": []}),
+ ScriptedResponse(status=201, json={}),
+ ScriptedResponse(json={"webhooks": [{"id": "wh-9", "url": URL}]}),
+ ScriptedResponse(),
+ ]
+ ) as network:
+ result = api_client.create_webhook("key", URL, ["sms_sent"])
assert result.success is True
- put_url = mock_session.return_value.put.call_args.args[0]
- assert put_url.endswith("/wh-9")
- assert mock_session.return_value.put.call_args.kwargs["json"]["disabled"] is True
-
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_fails_when_created_webhook_cannot_be_disabled(self, mock_session):
- mock_session.return_value.get.side_effect = [
- _response(200, {"webhooks": []}),
- _response(200, {"webhooks": []}),
- ]
- mock_session.return_value.post.return_value = _response(201, {})
-
- result = api_client.create_webhook("key", "https://ph.example/webhook", ["sms_sent"])
+ put = network.requests_log[-1]
+ assert put.method == "PUT"
+ assert put.path.endswith("/wh-9")
+ assert put.json()["disabled"] is True
+
+ def test_fails_when_created_webhook_cannot_be_disabled(self):
+ with scripted_network(
+ [
+ ScriptedResponse(json={"webhooks": []}),
+ ScriptedResponse(status=201, json={}),
+ ScriptedResponse(json={"webhooks": []}),
+ ]
+ ) as network:
+ result = api_client.create_webhook("key", URL, ["sms_sent"])
assert result.success is False
assert "could not be disabled" in (result.error or "")
- mock_session.return_value.put.assert_not_called()
+ assert "PUT" not in [r.method for r in network.requests_log]
def test_no_mappable_resources_fails(self):
- result = api_client.create_webhook("key", "https://ph.example/webhook", ["unknown_table"])
+ result = api_client.create_webhook("key", URL, ["unknown_table"])
assert result.success is False
assert "None of the selected tables" in (result.error or "")
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_http_error_surfaces_friendly_message(self, mock_session):
- mock_session.return_value.get.return_value = _response(200, {"webhooks": []})
- mock_session.return_value.post.return_value = _response(403)
-
- result = api_client.create_webhook("key", "https://ph.example/webhook", ["sms_sent"])
+ def test_http_error_surfaces_friendly_message(self):
+ with scripted_network([ScriptedResponse(json={"webhooks": []}), ScriptedResponse(status=403)]):
+ result = api_client.create_webhook("key", URL, ["sms_sent"])
assert result.success is False
assert "Webhooks permission" in (result.error or "")
class TestEnableWebhook:
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_enables_matching_webhook(self, mock_session):
- mock_session.return_value.get.return_value = _response(
- 200, {"webhooks": [{"id": "wh-1", "url": "https://ph.example/webhook", "events": ["sms.sent"]}]}
- )
- mock_session.return_value.put.return_value = _response(200)
-
- ok, error = api_client.enable_webhook("key", "https://ph.example/webhook")
+ def test_enables_matching_webhook(self):
+ with scripted_network(
+ [
+ ScriptedResponse(json={"webhooks": [{"id": "wh-1", "url": URL, "events": ["sms.sent"]}]}),
+ ScriptedResponse(),
+ ]
+ ) as network:
+ ok, error = api_client.enable_webhook("key", URL)
assert ok is True
assert error is None
- put_body = mock_session.return_value.put.call_args.kwargs["json"]
- assert put_body == {"url": "https://ph.example/webhook", "events": ["sms.sent"], "disabled": False}
-
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_missing_webhook_fails(self, mock_session):
- mock_session.return_value.get.return_value = _response(200, {"webhooks": []})
+ put = network.requests_log[-1]
+ assert put.method == "PUT"
+ assert put.json() == {"url": URL, "events": ["sms.sent"], "disabled": False}
- ok, error = api_client.enable_webhook("key", "https://ph.example/webhook")
+ def test_missing_webhook_fails(self):
+ with scripted_network([ScriptedResponse(json={"webhooks": []})]):
+ ok, error = api_client.enable_webhook("key", URL)
assert ok is False
assert "No webhook found" in (error or "")
class TestSyncWebhookEvents:
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_noop_when_events_already_match(self, mock_session):
- mock_session.return_value.get.return_value = _response(
- 200, {"webhooks": [{"id": "wh-1", "url": "https://ph.example/webhook", "events": ["sms.sent"]}]}
- )
-
- result = api_client.sync_webhook_events("key", "https://ph.example/webhook", ["sms_sent"])
+ def test_noop_when_events_already_match(self):
+ with scripted_network(
+ [ScriptedResponse(json={"webhooks": [{"id": "wh-1", "url": URL, "events": ["sms.sent"]}]})]
+ ) as network:
+ result = api_client.sync_webhook_events("key", URL, ["sms_sent"])
assert result.success is True
- mock_session.return_value.put.assert_not_called()
-
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_updates_events_when_drifted(self, mock_session):
- mock_session.return_value.get.return_value = _response(
- 200, {"webhooks": [{"id": "wh-1", "url": "https://ph.example/webhook", "events": ["sms.sent"]}]}
- )
- mock_session.return_value.put.return_value = _response(200)
+ assert [r.method for r in network.requests_log] == ["GET"]
- result = api_client.sync_webhook_events("key", "https://ph.example/webhook", ["sms_sent", "email_opened"])
+ def test_updates_events_when_drifted(self):
+ with scripted_network(
+ [
+ ScriptedResponse(json={"webhooks": [{"id": "wh-1", "url": URL, "events": ["sms.sent"]}]}),
+ ScriptedResponse(),
+ ]
+ ) as network:
+ result = api_client.sync_webhook_events("key", URL, ["sms_sent", "email_opened"])
assert result.success is True
- put_body = mock_session.return_value.put.call_args.kwargs["json"]
- assert put_body == {
- "url": "https://ph.example/webhook",
+ assert network.requests_log[-1].json() == {
+ "url": URL,
"events": ["sms.sent", "email.opened"],
"disabled": False,
}
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_preserves_disabled_state_when_drifted(self, mock_session):
- mock_session.return_value.get.return_value = _response(
- 200,
- {
- "webhooks": [
- {
- "id": "wh-1",
- "url": "https://ph.example/webhook",
- "events": ["sms.sent"],
- "disabledAt": "2024-01-01 00:00:00",
- }
- ]
- },
- )
- mock_session.return_value.put.return_value = _response(200)
-
- result = api_client.sync_webhook_events("key", "https://ph.example/webhook", ["sms_sent", "email_opened"])
+ def test_preserves_disabled_state_when_drifted(self):
+ webhook = {"id": "wh-1", "url": URL, "events": ["sms.sent"], "disabledAt": "2024-01-01 00:00:00"}
+ with scripted_network([ScriptedResponse(json={"webhooks": [webhook]}), ScriptedResponse()]) as network:
+ result = api_client.sync_webhook_events("key", URL, ["sms_sent", "email_opened"])
assert result.success is True
- assert mock_session.return_value.put.call_args.kwargs["json"]["disabled"] is True
+ assert network.requests_log[-1].json()["disabled"] is True
def test_no_mappable_schemas_fails(self):
- result = api_client.sync_webhook_events("key", "https://ph.example/webhook", [])
+ result = api_client.sync_webhook_events("key", URL, [])
assert result.success is False
class TestDeleteWebhook:
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_deletes_matching_webhook(self, mock_session):
- mock_session.return_value.get.return_value = _response(
- 200, {"webhooks": [{"id": "wh-1", "url": "https://ph.example/webhook"}]}
- )
- mock_session.return_value.delete.return_value = _response(204)
-
- result = api_client.delete_webhook("key", "https://ph.example/webhook")
+ def test_deletes_matching_webhook(self):
+ with scripted_network(
+ [
+ ScriptedResponse(json={"webhooks": [{"id": "wh-1", "url": URL}]}),
+ ScriptedResponse(status=204),
+ ]
+ ) as network:
+ result = api_client.delete_webhook("key", URL)
assert result.success is True
- delete_url = mock_session.return_value.delete.call_args.args[0]
- assert delete_url == "https://api.attentivemobile.com/v1/webhooks/wh-1"
+ delete = network.requests_log[-1]
+ assert delete.method == "DELETE"
+ assert delete.url == "https://api.attentivemobile.com/v1/webhooks/wh-1"
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_missing_webhook_is_success(self, mock_session):
- mock_session.return_value.get.return_value = _response(200, {"webhooks": []})
-
- assert api_client.delete_webhook("key", "https://ph.example/webhook").success is True
-
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_404_on_delete_is_success(self, mock_session):
- mock_session.return_value.get.return_value = _response(
- 200, {"webhooks": [{"id": "wh-1", "url": "https://ph.example/webhook"}]}
- )
- delete_resp = mock.MagicMock()
- delete_resp.status_code = 404
- mock_session.return_value.delete.return_value = delete_resp
+ def test_missing_webhook_is_success(self):
+ with scripted_network([ScriptedResponse(json={"webhooks": []})]):
+ assert api_client.delete_webhook("key", URL).success is True
- assert api_client.delete_webhook("key", "https://ph.example/webhook").success is True
+ def test_404_on_delete_is_success(self):
+ with scripted_network(
+ [
+ ScriptedResponse(json={"webhooks": [{"id": "wh-1", "url": URL}]}),
+ ScriptedResponse(status=404),
+ ]
+ ):
+ assert api_client.delete_webhook("key", URL).success is True
class TestGetExternalWebhookInfo:
@pytest.mark.parametrize(
"webhook, expected_status",
[
- ({"id": "wh-1", "url": "https://ph.example/webhook", "events": ["sms.sent"]}, "enabled"),
+ ({"id": "wh-1", "url": URL, "events": ["sms.sent"]}, "enabled"),
(
- {
- "id": "wh-1",
- "url": "https://ph.example/webhook",
- "events": ["sms.sent"],
- "disabledAt": "2024-01-01 00:00:00",
- },
+ {"id": "wh-1", "url": URL, "events": ["sms.sent"], "disabledAt": "2024-01-01 00:00:00"},
"disabled",
),
],
)
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_reports_status(self, mock_session, webhook, expected_status):
- mock_session.return_value.get.return_value = _response(200, {"webhooks": [webhook]})
-
- info = api_client.get_external_webhook_info("key", "https://ph.example/webhook")
+ def test_reports_status(self, webhook, expected_status):
+ with scripted_network([ScriptedResponse(json={"webhooks": [webhook]})]):
+ info = api_client.get_external_webhook_info("key", URL)
assert info.exists is True
assert info.status == expected_status
assert info.enabled_events == ["sms.sent"]
- @mock.patch(f"{_MODULE}.make_tracked_session")
- def test_missing_webhook(self, mock_session):
- mock_session.return_value.get.return_value = _response(200, {"webhooks": []})
-
- info = api_client.get_external_webhook_info("key", "https://ph.example/webhook")
+ def test_missing_webhook(self):
+ with scripted_network([ScriptedResponse(json={"webhooks": []})]):
+ info = api_client.get_external_webhook_info("key", URL)
assert info.exists is False
assert info.error is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/__init__.py
new file mode 100644
index 000000000000..6018ce25aef2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/__init__.py
@@ -0,0 +1,33 @@
+from .driver import DriveResult, SourceDriver
+from .fake_network import (
+ DatabaseBlockedError,
+ FakeNetwork,
+ NetworkBlockedError,
+ RecordedRequest,
+ Responder,
+ RunStopped,
+ fake_environment,
+ http_response,
+)
+from .inputs import source_inputs
+from .responders import Script, ScriptedResponder, ScriptedResponse, UnexpectedRequest, route, scripted_network
+
+__all__ = [
+ "DatabaseBlockedError",
+ "DriveResult",
+ "FakeNetwork",
+ "NetworkBlockedError",
+ "RecordedRequest",
+ "Responder",
+ "RunStopped",
+ "Script",
+ "ScriptedResponder",
+ "ScriptedResponse",
+ "SourceDriver",
+ "UnexpectedRequest",
+ "fake_environment",
+ "http_response",
+ "route",
+ "scripted_network",
+ "source_inputs",
+]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/driver.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/driver.py
new file mode 100644
index 000000000000..60cbb42fe104
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/driver.py
@@ -0,0 +1,199 @@
+import asyncio
+import contextlib
+from collections.abc import Callable, Iterator
+from typing import Any
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ ResumableSource,
+ SimpleSource,
+ _BaseSource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+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.testing.fake_network import (
+ RecordedRequest,
+ RunStopped,
+ fake_environment,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing.inputs import source_inputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing.responders import (
+ Script,
+ ScriptedResponder,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+
+
+@frozen
+class DriveResult:
+ """What one extraction did, as a test can assert on it."""
+
+ # Each row the source handed the pipeline, with a page of rows flattened into its rows.
+ rows: list[Any]
+ # What the source yielded, unflattened, for a test that cares about page boundaries.
+ items: list[Any]
+ requests: list[RecordedRequest]
+ # Every cursor the source saved, in order, whether or not it persisted.
+ saved_states: list[Any]
+ # Each cursor that reached storage, so a cursor saved after the last row does not appear.
+ committed_states: list[Any]
+ raised: BaseException | None
+
+ @property
+ def urls(self) -> list[str]:
+ return [request.url for request in self.requests]
+
+ @property
+ def queries(self) -> list[dict[str, tuple[str, ...]]]:
+ return [dict(request.query) for request in self.requests]
+
+ @property
+ def paths(self) -> list[str]:
+ """Each request's path, without the origin or the query string."""
+ return [request.path for request in self.requests]
+
+ def params(self, name: str) -> list[str | None]:
+ """The value of one query parameter across the requests, in order."""
+ return [request.param(name) for request in self.requests]
+
+
+class SourceDriver:
+ """Runs a source against scripted vendor answers, with no network and no database.
+
+ It drives `source_for_pipeline`, the entry point the pipeline itself calls, so a run covers the
+ source's config and inputs plumbing as well as its fetching. It also stands in for the pipeline
+ around the run: it commits the resume cursor when the source hands over a row or reaches a safe
+ point, which is what makes a cursor saved after the last row fail to persist, as in production.
+ """
+
+ def __init__(self, source: _BaseSource[Any], config: Any) -> None:
+ self._source = source
+ self._config = config
+
+ def run(
+ self,
+ schema_name: str,
+ script: Script,
+ *,
+ resume_state: Any = None,
+ **inputs: Any,
+ ) -> DriveResult:
+ """Run one extraction to its end or its first error.
+
+ `script` answers the requests, in order or by request. `resume_state` is a cursor a previous
+ attempt left behind, so the source resumes from it. Other keywords go to `source_inputs`.
+ """
+ with fake_environment(ScriptedResponder(script)) as network:
+ built = source_inputs(schema_name, **inputs)
+ saved: list[Any] = []
+ committed: list[Any] = []
+ rows: list[Any] = []
+ items: list[Any] = []
+ raised: BaseException | None = None
+
+ with self._recording_saves(saved):
+ manager = self._manager(built)
+ if manager is not None and resume_state is not None:
+ manager.save_state(resume_state)
+ manager.confirm()
+ manager.commit()
+ saved.clear()
+
+ def hand_over() -> None:
+ """Stand in for the pipeline after a write: stage the cursor and persist it."""
+ network.note_progress()
+ if manager is None:
+ return
+ manager.confirm()
+ manager.commit()
+ state = manager.load_state()
+ if state is not None and (not committed or committed[-1] != state):
+ committed.append(state)
+
+ try:
+ response = self._start(built, manager)
+ emitted = response.items()
+ with contextlib.ExitStack() as stack:
+ if manager is not None:
+ stack.enter_context(
+ activate_safe_point(
+ hand_over, covers_framework_checkpoints=isinstance(emitted, Resource)
+ )
+ )
+
+ def take(item: Any) -> None:
+ items.append(item)
+ if isinstance(item, list | tuple):
+ rows.extend(item)
+ else:
+ rows.append(item)
+ hand_over()
+
+ _consume(emitted, take)
+ except (Exception, RunStopped) as error:
+ raised = error
+
+ return DriveResult(
+ rows=rows,
+ items=items,
+ requests=list(network.requests_log),
+ saved_states=saved,
+ committed_states=committed,
+ raised=raised,
+ )
+
+ def _manager(self, inputs: SourceInputs) -> ResumableSourceManager[Any] | None:
+ if isinstance(self._source, ResumableSource):
+ return self._source.get_resumable_source_manager(inputs)
+ return None
+
+ def _start(self, inputs: SourceInputs, manager: ResumableSourceManager[Any] | None) -> Any:
+ if manager is not None:
+ assert isinstance(self._source, ResumableSource)
+ return self._source.source_for_pipeline(self._config, manager, inputs)
+ assert isinstance(self._source, SimpleSource)
+ return self._source.source_for_pipeline(self._config, inputs)
+
+ @staticmethod
+ @contextlib.contextmanager
+ def _recording_saves(saved: list[Any]) -> Iterator[None]:
+ """Record every cursor a source saves, including on a sibling from `with_namespace`."""
+ original = ResumableSourceManager.save_state
+
+ def save_state(self: ResumableSourceManager[Any], data: Any) -> None:
+ saved.append(data)
+ original(self, data)
+
+ with contextlib.ExitStack() as stack:
+ stack.enter_context(_patched(ResumableSourceManager, "save_state", save_state))
+ yield
+
+
+def _patched(target: type, name: str, value: Any) -> Iterator[None]:
+ original = getattr(target, name)
+ setattr(target, name, value)
+ try:
+ yield
+ finally:
+ setattr(target, name, original)
+
+
+def _consume(emitted: Any, take: Callable[[Any], None]) -> None:
+ """Hand each item to `take` as the source yields it, for a sync or an async iterable.
+
+ The items pass one at a time rather than being collected first, so the cursor is committed
+ between two rows exactly as the pipeline commits it.
+ """
+ if not hasattr(emitted, "__aiter__"):
+ for item in emitted:
+ take(item)
+ return
+
+ async def drain() -> None:
+ async for item in emitted:
+ take(item)
+
+ asyncio.run(drain())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/fake_network.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/fake_network.py
new file mode 100644
index 000000000000..fc96ef559d58
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/fake_network.py
@@ -0,0 +1,346 @@
+import io
+import sys
+import json
+import time
+import types
+import socket
+import asyncio
+import inspect
+import functools
+import ipaddress
+import contextlib
+import urllib.parse
+from collections.abc import Callable, Iterator, Mapping
+from typing import Any, Protocol
+
+from unittest import mock
+
+from django.db.backends.base.base import BaseDatabaseWrapper
+
+import tenacity
+from urllib3.connection import HTTPConnection, HTTPSConnection
+
+from posthog.dataclasses import frozen
+from posthog.security import url_validation
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+# A run stops at one of these limits, because the source would not stop by itself.
+_CLOCK_LIMIT_SECONDS = 4 * 3600.0
+_REQUEST_LIMIT = 40
+
+_SOURCES_PACKAGE = "products.warehouse_sources.backend.temporal.data_imports.sources"
+_UNSET = object()
+_PUBLIC_ADDRESS = "93.184.216.34"
+_REAL_SLEEP = time.sleep
+_REAL_MONOTONIC = time.monotonic
+_REAL_TIME = time.time
+_REAL_ASYNC_SLEEP = asyncio.sleep
+
+
+class RunStopped(BaseException):
+ """Ends a run that passed a harness limit. A `BaseException`, so that `except Exception` in a source cannot hide it."""
+
+
+class NetworkBlockedError(OSError):
+ """The source opened a connection that does not go through `requests`, so the fake cannot answer it."""
+
+
+class DatabaseBlockedError(RuntimeError):
+ """The source read the application database, which the contract tests do not have."""
+
+
+@frozen
+class RecordedRequest:
+ method: str
+ origin: str
+ # The path without the query string.
+ path: str
+ # The origin and the request target, with the query string.
+ url: str
+ query: Mapping[str, tuple[str, ...]]
+ # The names are lowercase.
+ headers: Mapping[str, str]
+ body: bytes | None
+ read_timeout: float | None
+
+ def param(self, name: str) -> str | None:
+ """The single value of a query parameter, or None when the request carries none."""
+ values = self.query.get(name)
+ return values[0] if values else None
+
+ def json(self) -> Any:
+ """The request body, parsed as JSON."""
+ return json.loads(self.body or b"null")
+
+
+class Responder(Protocol):
+ def respond(self, request: RecordedRequest, network: "FakeNetwork") -> bytes: ...
+
+
+def _parse_request(origin: str, sent: bytes, read_timeout: Any) -> RecordedRequest:
+ head, _, body = sent.partition(b"\r\n\r\n")
+ request_line, *header_lines = head.split(b"\r\n")
+ method, _, target = request_line.partition(b" ")
+ target_text = target.rsplit(b" ", 1)[0].decode("latin-1") or "/"
+ path, _, query_text = target_text.partition("?")
+ headers: dict[str, str] = {}
+ for line in header_lines:
+ name, _, value = line.decode("latin-1").partition(":")
+ headers[name.strip().lower()] = value.strip()
+ return RecordedRequest(
+ method=method.decode("latin-1"),
+ origin=origin,
+ path=path,
+ url=f"{origin}{target_text}",
+ query={key: tuple(values) for key, values in urllib.parse.parse_qs(query_text).items()},
+ headers=headers,
+ body=body or None,
+ read_timeout=None if read_timeout is None or read_timeout is _UNSET else float(read_timeout),
+ )
+
+
+class FakeNetwork:
+ """Answers every HTTP request through its responder, and records what the source did."""
+
+ def __init__(self, responder: Responder) -> None:
+ self.responder = responder
+ self.requests_log: list[RecordedRequest] = []
+ self.elapsed = 0.0
+ self.requests = 0
+ self.unbounded_requests = 0
+ self.blocked_connections = 0
+ self.blocked_database_reads = 0
+ self.longest_request_seconds = 0.0
+ self.longest_run_without_progress = 0
+ self.error: BaseException | None = None
+ self._request_key: bytes | None = None
+ self._request_started = 0.0
+ self._run_without_progress = 0
+
+ def advance(self, seconds: float | None) -> None:
+ if seconds is not None and seconds > 0:
+ self.elapsed += seconds
+ self.longest_request_seconds = max(self.longest_request_seconds, self.elapsed - self._request_started)
+ if self.elapsed > _CLOCK_LIMIT_SECONDS:
+ raise RunStopped("clock limit")
+
+ def note_progress(self) -> None:
+ """The source yielded an item or reached a safe point, so the pipeline could act."""
+ self._run_without_progress = 0
+
+ def respond(self, origin: str, sent: bytes, read_timeout: Any) -> io.BytesIO:
+ request_line = sent.split(b"\r\n", 1)[0]
+
+ # Attempts for the same method and URL, one after the other, are one request with its retries.
+ if request_line != self._request_key:
+ self._request_key = request_line
+ self._request_started = self.elapsed
+ self.requests += 1
+ self._run_without_progress += 1
+ self.longest_run_without_progress = max(self.longest_run_without_progress, self._run_without_progress)
+ if self.requests > _REQUEST_LIMIT:
+ raise RunStopped("request limit")
+
+ request = _parse_request(origin, sent, read_timeout)
+ self.requests_log.append(request)
+ return io.BytesIO(self.responder.respond(request, self))
+
+
+def http_response(status: bytes, body: bytes, headers: list[bytes]) -> bytes:
+ lines = [
+ b"HTTP/1.1 " + status,
+ b"Content-Type: application/json",
+ b"Content-Length: " + str(len(body)).encode(),
+ b"Connection: close",
+ *headers,
+ ]
+ return b"\r\n".join(lines) + b"\r\n\r\n" + body
+
+
+class _FailingStream(io.RawIOBase):
+ def __init__(self, error: BaseException) -> None:
+ super().__init__()
+ self._error = error
+
+ def readable(self) -> bool:
+ return True
+
+ def readline(self, size: int | None = -1) -> bytes:
+ raise self._error
+
+ def readinto(self, buffer: Any) -> int:
+ raise self._error
+
+
+class _FakeSocket:
+ def __init__(self, network: FakeNetwork, origin: str) -> None:
+ self._network = network
+ self._origin = origin
+ self._sent = b""
+ self._read_timeout: Any = _UNSET
+
+ def settimeout(self, value: Any) -> None:
+ self._read_timeout = value
+
+ def gettimeout(self) -> Any:
+ return None if self._read_timeout is _UNSET else self._read_timeout
+
+ def sendall(self, data: Any, *args: Any) -> None:
+ self._sent += bytes(data)
+
+ def send(self, data: Any, *args: Any) -> int:
+ self._sent += bytes(data)
+ return len(data)
+
+ def makefile(self, *args: Any, **kwargs: Any) -> io.IOBase:
+ sent, self._sent = self._sent, b""
+ try:
+ return self._network.respond(self._origin, sent, self._read_timeout)
+ except (TimeoutError, RunStopped) as error:
+ # A real socket fails at the first read, and not when `http.client` wraps it.
+ return _FailingStream(error)
+
+ def setsockopt(self, *args: Any) -> None:
+ pass
+
+ def shutdown(self, *args: Any) -> None:
+ pass
+
+ def close(self) -> None:
+ pass
+
+
+class _MemoryRedis:
+ def __init__(self) -> None:
+ self._data: dict[str, Any] = {}
+
+ def ping(self) -> bool:
+ return True
+
+ def set(self, key: str, value: Any, **kwargs: Any) -> None:
+ self._data[key] = value
+
+ def get(self, key: str) -> Any:
+ return self._data.get(key)
+
+ def exists(self, key: str) -> int:
+ return int(key in self._data)
+
+ def delete(self, key: str) -> None:
+ self._data.pop(key, None)
+
+
+def _sleep_aliases() -> list[tuple[Any, str]]:
+ """Each `from time import sleep` binding in a loaded source module. A patch of `time.sleep` does not reach them."""
+ aliases: list[tuple[Any, str]] = []
+ for module_name, module in list(sys.modules.items()):
+ if not module_name.startswith(_SOURCES_PACKAGE):
+ continue
+ aliases.extend((module, name) for name, value in list(vars(module).items()) if value is _REAL_SLEEP)
+ return aliases
+
+
+def _controller_of(value: Any) -> tenacity.Retrying | None:
+ if isinstance(value, staticmethod | classmethod):
+ value = value.__func__
+ if not isinstance(value, types.FunctionType):
+ return None
+ controller = value.__dict__.get("retry")
+ return controller if isinstance(controller, tenacity.Retrying) else None
+
+
+def _retry_controllers() -> list[tenacity.Retrying]:
+ """Each synchronous tenacity controller that a `@retry` decorator put on a function or a method.
+
+ A test can replace the `sleep` of one for the rest of the process, for example
+ `RESTClient._send_request.retry.sleep = lambda *_: None`. That wait then never reaches the fake
+ clock, and the verdict of every later source depends on which tests ran before.
+ """
+ controllers: dict[int, tenacity.Retrying] = {}
+ for module in list(sys.modules.values()):
+ for value in list(getattr(module, "__dict__", {}).values()):
+ candidates = list(vars(value).values()) if inspect.isclass(value) else []
+ for candidate in [value, *candidates]:
+ if (controller := _controller_of(candidate)) is not None:
+ controllers[id(controller)] = controller
+ return list(controllers.values())
+
+
+def _waits_on_the_fake_clock(sleep: Callable[[float], None]) -> Iterator[None]:
+ """Give each retry controller the fake `sleep`, and put back what each one had. This is cheaper than `mock.patch`."""
+ controllers = _retry_controllers()
+ originals = [controller.sleep for controller in controllers]
+ for controller in controllers:
+ controller.sleep = sleep
+ try:
+ yield
+ finally:
+ for controller, original in zip(controllers, originals):
+ controller.sleep = original
+
+
+def fake_environment(responder: Responder) -> Iterator[FakeNetwork]:
+ """Route HTTP to a `FakeNetwork`, block every other connection, and make each wait advance a fake clock."""
+ network = FakeNetwork(responder)
+ redis = _MemoryRedis()
+
+ def connect(connection: Any) -> None:
+ scheme = "https" if isinstance(connection, HTTPSConnection) else "http"
+ default_port = 443 if scheme == "https" else 80
+ port = "" if connection.port in (None, default_port) else f":{connection.port}"
+ connection.sock = _FakeSocket(network, f"{scheme}://{connection.host}{port}")
+ connection.is_verified = True
+
+ def blocked_connection(*args: Any, **kwargs: Any) -> Any:
+ network.blocked_connections += 1
+ raise NetworkBlockedError("the contract tests allow no real connection")
+
+ def blocked_database(*args: Any, **kwargs: Any) -> Any:
+ network.blocked_database_reads += 1
+ raise DatabaseBlockedError("the contract tests have no database")
+
+ # A source that checks its host before it connects gets a public address. Nothing connects to it.
+ def resolve(host: Any, port: Any, *args: Any, **kwargs: Any) -> list[Any]:
+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (_PUBLIC_ADDRESS, int(port or 0)))]
+
+ def resolve_host_ips(host: str) -> set[Any]:
+ return {ipaddress.ip_address(_PUBLIC_ADDRESS)}
+
+ def sleep(seconds: float) -> None:
+ network.advance(seconds)
+
+ async def async_sleep(seconds: float, result: Any = None) -> Any:
+ network.advance(seconds)
+ return await _REAL_ASYNC_SLEEP(0, result)
+
+ @contextlib.contextmanager
+ def memory_redis(_manager: Any) -> Iterator[_MemoryRedis]:
+ yield redis
+
+ patches: list[Any] = [
+ mock.patch.object(HTTPConnection, "connect", connect),
+ mock.patch.object(HTTPSConnection, "connect", connect),
+ mock.patch.object(socket.socket, "connect", blocked_connection),
+ mock.patch.object(socket.socket, "connect_ex", blocked_connection),
+ mock.patch.object(socket.socket, "sendto", blocked_connection),
+ mock.patch.object(socket, "create_connection", blocked_connection),
+ mock.patch.object(socket, "getaddrinfo", resolve),
+ mock.patch.object(url_validation, "resolve_host_ips", resolve_host_ips),
+ mock.patch.object(BaseDatabaseWrapper, "ensure_connection", blocked_database),
+ mock.patch.object(time, "sleep", sleep),
+ mock.patch.object(time, "monotonic", lambda: _REAL_MONOTONIC() + network.elapsed),
+ mock.patch.object(time, "time", lambda: _REAL_TIME() + network.elapsed),
+ mock.patch.object(asyncio, "sleep", async_sleep),
+ mock.patch.object(ResumableSourceManager, "_get_redis", memory_redis),
+ *(mock.patch.object(module, name, sleep) for module, name in _sleep_aliases()),
+ _waits_on_the_fake_clock(sleep),
+ ]
+ with contextlib.ExitStack() as stack:
+ for patch in patches:
+ stack.enter_context(patch)
+ yield network
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/inputs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/inputs.py
new file mode 100644
index 000000000000..b05a83fa1819
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/inputs.py
@@ -0,0 +1,39 @@
+import structlog
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.types import IncrementalFieldType
+
+_LOGGER_NAME = "source_testing"
+
+
+def source_inputs(
+ schema_name: str,
+ *,
+ team_id: int = 1,
+ job_id: str = "00000000-0000-4000-8000-000000000003",
+ should_use_incremental_field: bool = False,
+ incremental_field: str | None = None,
+ incremental_field_type: IncrementalFieldType | None = None,
+ db_incremental_field_last_value: object | None = None,
+ db_incremental_field_earliest_value: object | None = None,
+ reset_pipeline: bool = False,
+) -> SourceInputs:
+ """The `SourceInputs` the pipeline hands a source, with the fields a test varies.
+
+ `should_use_incremental_field` follows `incremental_field` unless it is set, because a test that
+ names a field always means to sync incrementally on it.
+ """
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="00000000-0000-4000-8000-000000000001",
+ source_id="00000000-0000-4000-8000-000000000002",
+ team_id=team_id,
+ should_use_incremental_field=should_use_incremental_field or incremental_field is not None,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ db_incremental_field_earliest_value=db_incremental_field_earliest_value,
+ incremental_field=incremental_field,
+ incremental_field_type=incremental_field_type,
+ job_id=job_id,
+ logger=structlog.get_logger(_LOGGER_NAME),
+ reset_pipeline=reset_pipeline,
+ )
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
new file mode 100644
index 000000000000..fe0082dfd2f0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/responders.py
@@ -0,0 +1,120 @@
+import json
+import contextlib
+import dataclasses
+from collections.abc import Callable, Iterator, Mapping, Sequence
+from typing import Any
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing.fake_network import (
+ FakeNetwork,
+ RecordedRequest,
+ fake_environment,
+ http_response,
+)
+
+_REASONS = {
+ 200: "OK",
+ 201: "Created",
+ 204: "No Content",
+ 301: "Moved Permanently",
+ 302: "Found",
+ 400: "Bad Request",
+ 401: "Unauthorized",
+ 403: "Forbidden",
+ 404: "Not Found",
+ 409: "Conflict",
+ 422: "Unprocessable Entity",
+ 429: "Too Many Requests",
+ 500: "Internal Server Error",
+ 502: "Bad Gateway",
+ 503: "Service Unavailable",
+ 504: "Gateway Timeout",
+}
+
+
+@frozen
+class ScriptedResponse:
+ """One answer a scripted vendor gives.
+
+ `json` is the body for the common case. `body` sends raw bytes instead, for a payload that is not
+ JSON or is deliberately malformed.
+ """
+
+ status: int = 200
+ json: Any = None
+ headers: Mapping[str, str] = dataclasses.field(default_factory=dict)
+ body: bytes | None = None
+
+ def to_bytes(self) -> bytes:
+ if self.body is not None:
+ payload = self.body
+ elif self.json is None:
+ payload = b""
+ else:
+ payload = json.dumps(self.json).encode()
+ reason = _REASONS.get(self.status, "Unknown")
+ status_line = f"{self.status} {reason}".encode()
+ headers = [f"{name}: {value}".encode() for name, value in self.headers.items()]
+ return http_response(status_line, payload, headers)
+
+
+# A script answers each request in turn, or decides from the request itself.
+Script = Sequence[ScriptedResponse] | Callable[[RecordedRequest], ScriptedResponse]
+
+
+class UnexpectedRequest(AssertionError):
+ """The source made a request the script does not answer.
+
+ Raised rather than answered, because a source that keeps asking is the failure a pagination test
+ looks for. An empty answer would hide it.
+ """
+
+
+class ScriptedResponder:
+ """Answers each request from a script, and fails on a request the script does not cover."""
+
+ def __init__(self, script: Script) -> None:
+ self._script = script
+ self._queue = None if callable(script) else list(script)
+
+ def respond(self, request: RecordedRequest, network: FakeNetwork) -> bytes:
+ if self._queue is None:
+ assert callable(self._script)
+ return self._script(request).to_bytes()
+ if not self._queue:
+ raise UnexpectedRequest(
+ f"the script has no answer left for {request.method} {request.url}"
+ f" (request {network.requests} of this run)"
+ )
+ return self._queue.pop(0).to_bytes()
+
+
+def route(table: Mapping[str, Sequence[ScriptedResponse]]) -> Callable[[RecordedRequest], ScriptedResponse]:
+ """Answer each path from its own queue, for a source that interleaves endpoints or a token exchange.
+
+ A key matches a request whose path equals it, or ends with it, so a caller can name `/surveys`
+ without the API's version prefix.
+ """
+ queues = {path: list(responses) for path, responses in table.items()}
+
+ def respond(request: RecordedRequest) -> ScriptedResponse:
+ for path, queue in queues.items():
+ if request.path == path or request.path.endswith(path):
+ if not queue:
+ raise UnexpectedRequest(f"the script has no answer left for {request.method} {request.url}")
+ return queue.pop(0)
+ raise UnexpectedRequest(f"the script covers no path matching {request.method} {request.url}")
+
+ return respond
+
+
+def scripted_network(script: Script) -> Iterator[FakeNetwork]:
+ """Answer every request in the block from `script`, and yield the network that records them.
+
+ For code a source runs outside an extraction, such as a credential probe or a webhook call. An
+ extraction goes through `SourceDriver`, which also stands in for the pipeline.
+ """
+ with fake_environment(ScriptedResponder(script)) as network:
+ yield network
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/tests/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
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
new file mode 100644
index 000000000000..1bee4a4b2ed6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/testing/tests/test_driver.py
@@ -0,0 +1,133 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+
+import pytest
+
+from products.warehouse_sources.backend.facade.source_config import SourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config as source_config
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.transport import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+ UnexpectedRequest,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_BASE_URL = "https://double.example.com"
+# The cursor the double saves once it has no rows left. Nothing is yielded after it, so the pipeline
+# never confirms it and it must not persist.
+_AFTER_THE_LAST_ROW = 999
+
+
+@source_config.config
+class _DoubleConfig(source_config.Config):
+ token: str
+
+
[email protected](frozen=True)
+class _Cursor:
+ page: int = 0
+
+
+class _DoubleSource(ResumableSource[_DoubleConfig, _Cursor]):
+ """A source with just enough behaviour to show what the driver records."""
+
+ @property
+ def source_type(self) -> ExternalDataSourceType:
+ return ExternalDataSourceType.ZYLO
+
+ @property
+ def get_source_config(self) -> SourceConfig:
+ return SourceConfig(name="Double", label="Double", iconPath="/static/double.png", fields=[])
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[_Cursor]:
+ return ResumableSourceManager(inputs, _Cursor)
+
+ def source_for_pipeline(
+ self,
+ config: _DoubleConfig,
+ resumable_source_manager: ResumableSourceManager[_Cursor],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ def items() -> Iterator[Any]:
+ start = 0
+ if resumable_source_manager.can_resume():
+ saved = resumable_source_manager.load_state()
+ start = saved.page if saved is not None else 0
+ session = make_tracked_session()
+ page = start
+ while True:
+ answer = session.get(f"{_BASE_URL}/rows", params={"page": str(page)}, timeout=(5, 5))
+ rows = answer.json()["rows"]
+ if not rows:
+ break
+ page += 1
+ resumable_source_manager.save_state(_Cursor(page=page))
+ yield rows
+ resumable_source_manager.save_state(_Cursor(page=_AFTER_THE_LAST_ROW))
+
+ return SourceResponse(name=inputs.schema_name, items=items, primary_keys=["id"])
+
+
+def _driver() -> SourceDriver:
+ return SourceDriver(_DoubleSource(), _DoubleConfig(token="t"))
+
+
+def _page(*ids: int) -> ScriptedResponse:
+ return ScriptedResponse(json={"rows": [{"id": i} for i in ids]})
+
+
+class TestSourceDriver:
+ def test_a_cursor_saved_after_the_last_row_does_not_persist(self) -> None:
+ result = _driver().run("rows", [_page(1), _page(2), _page()])
+
+ assert result.rows == [{"id": 1}, {"id": 2}]
+ assert [cursor.page for cursor in result.saved_states] == [1, 2, _AFTER_THE_LAST_ROW]
+ # The pipeline confirms a cursor when it takes a row, so the last save never reaches storage.
+ assert [cursor.page for cursor in result.committed_states] == [1, 2]
+
+ def test_a_resume_state_is_what_the_source_loads(self) -> None:
+ result = _driver().run("rows", [_page(7), _page()], resume_state=_Cursor(page=4))
+
+ assert result.params("page") == ["4", "5"]
+ assert result.rows == [{"id": 7}]
+
+ def test_a_run_with_no_resume_state_starts_from_the_beginning(self) -> None:
+ result = _driver().run("rows", [_page()])
+
+ assert result.params("page") == ["0"]
+
+ def test_a_request_the_script_does_not_answer_fails_the_run(self) -> None:
+ # A source that keeps paging is the failure a pagination test looks for, so the driver must
+ # raise rather than answer an empty page and let the loop end quietly.
+ result = _driver().run("rows", [_page(1)])
+
+ assert isinstance(result.raised, UnexpectedRequest)
+ assert "page=1" in str(result.raised)
+
+ def test_the_recorded_request_carries_the_url_query_and_headers(self) -> None:
+ result = _driver().run("rows", [_page()])
+
+ request = result.requests[0]
+ assert request.method == "GET"
+ assert request.path == "/rows"
+ assert request.url == f"{_BASE_URL}/rows?page=0"
+ assert request.param("page") == "0"
+ assert request.headers["host"] == "double.example.com"
+
+
+class TestScriptedResponse:
+ @pytest.mark.parametrize(
+ ("response", "expected"),
+ [
+ (ScriptedResponse(), b""),
+ (ScriptedResponse(json={"a": 1}), b'{"a": 1}'),
+ (ScriptedResponse(body=b"not json"), b"not json"),
+ ],
+ )
+ def test_the_body_is_what_the_answer_declares(self, response: ScriptedResponse, expected: bytes) -> None:
+ assert response.to_bytes().endswith(expected)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/contract_harness.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/contract_harness.py
index 6efe856a25f4..3891a552b8af 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/contract_harness.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/contract_harness.py
@@ -5,33 +5,18 @@ retry layers of the adapter, the REST client and the source all run as they do i
waits add to a fake clock and take no real time.
"""
-import io
import ast
-import sys
import json
-import time
-import types
-import socket
import asyncio
import inspect
import functools
-import ipaddress
import contextlib
import dataclasses
from collections.abc import Callable, Iterator
from pathlib import Path
from typing import Any, Literal
-from unittest import mock
-
-from django.db.backends.base.base import BaseDatabaseWrapper
-
-import tenacity
-import structlog
-from urllib3.connection import HTTPConnection, HTTPSConnection
-
from posthog.dataclasses import frozen
-from posthog.security import url_validation
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
ResumableSource,
@@ -42,6 +27,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.con
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
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.testing.fake_network import (
+ _SOURCES_PACKAGE,
+ FakeNetwork,
+ RecordedRequest,
+ RunStopped,
+ fake_environment,
+ http_response,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing.inputs import source_inputs
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
# The longest time one request, with all of its retries and waits, may hold a worker.
@@ -56,10 +50,6 @@ STALL_BUDGET = "stall-budget"
RATE_LIMIT_BUDGET = "rate-limit-budget"
SAFE_POINT = "safe-point"
-# A run stops at one of these limits, because the source would not stop by itself.
-_CLOCK_LIMIT_SECONDS = 4 * 3600.0
-_REQUEST_LIMIT = 40
-_EMPTY_PAGE_COUNT = 8
# Modules that open connections outside Python sockets, or from background threads. The fake network
# cannot see or stop those connections, so a source that imports one of them is never run.
@@ -81,13 +71,7 @@ NATIVE_DRIVER_MODULES = (
)
_SOURCES_ROOT = Path(__file__).parents[1]
-_SOURCES_PACKAGE = "products.warehouse_sources.backend.temporal.data_imports.sources"
-_UNSET = object()
-_PUBLIC_ADDRESS = "93.184.216.34"
-_REAL_SLEEP = time.sleep
-_REAL_MONOTONIC = time.monotonic
-_REAL_TIME = time.time
-_REAL_ASYNC_SLEEP = asyncio.sleep
+_EMPTY_PAGE_COUNT = 8
Mode = Literal["stall", "rate_limit", "empty_pages"]
# Starts one extraction. The manager is None for a source that the pipeline treats as not resumable.
@@ -113,18 +97,6 @@ BOUNDED_CALL_SCENARIOS = (
SAFE_POINT_SCENARIOS = (Scenario(mode="empty_pages"), Scenario(mode="empty_pages", list_bodies=True))
-class RunStopped(BaseException):
- """Ends a run that passed a harness limit. A `BaseException`, so that `except Exception` in a source cannot hide it."""
-
-
-class NetworkBlockedError(OSError):
- """The source opened a connection that does not go through `requests`, so the fake cannot answer it."""
-
-
-class DatabaseBlockedError(RuntimeError):
- """The source read the application database, which the contract tests do not have."""
-
-
def empty_page_body(next_url: str | None, page: int) -> dict[str, Any]:
"""A page with no rows, in the shapes that most paginators and token exchanges read.
@@ -159,268 +131,34 @@ def empty_page_body(next_url: str | None, page: int) -> dict[str, Any]:
return body
-class FakeNetwork:
- """Answers every HTTP request as the scenario says, and records what the source did."""
+class ScenarioResponder:
+ """Answers every HTTP request as the scenario says."""
def __init__(self, scenario: Scenario) -> None:
self.scenario = scenario
- self.elapsed = 0.0
- self.requests = 0
- self.unbounded_requests = 0
- self.blocked_connections = 0
- self.blocked_database_reads = 0
- self.longest_request_seconds = 0.0
- self.longest_run_without_progress = 0
- self.error: BaseException | None = None
- self._request_key: bytes | None = None
- self._request_started = 0.0
- self._run_without_progress = 0
-
- def advance(self, seconds: float | None) -> None:
- if seconds is not None and seconds > 0:
- self.elapsed += seconds
- self.longest_request_seconds = max(self.longest_request_seconds, self.elapsed - self._request_started)
- if self.elapsed > _CLOCK_LIMIT_SECONDS:
- raise RunStopped("clock limit")
-
- def note_progress(self) -> None:
- """The source yielded an item or reached a safe point, so the pipeline could act."""
- self._run_without_progress = 0
-
- def respond(self, origin: str, sent: bytes, read_timeout: Any) -> io.BytesIO:
- request_line = sent.split(b"\r\n", 1)[0]
- method, _, target = request_line.partition(b" ")
- path = target.rsplit(b" ", 1)[0].decode("latin-1") or "/"
-
- # Attempts for the same method and URL, one after the other, are one request with its retries.
- if request_line != self._request_key:
- self._request_key = request_line
- self._request_started = self.elapsed
- self.requests += 1
- self._run_without_progress += 1
- self.longest_run_without_progress = max(self.longest_run_without_progress, self._run_without_progress)
- if self.requests > _REQUEST_LIMIT:
- raise RunStopped("request limit")
+ def respond(self, request: RecordedRequest, network: FakeNetwork) -> bytes:
mode = self.scenario.mode
- answered = self.requests <= self.scenario.answered_first
+ answered = network.requests <= self.scenario.answered_first
if mode == "stall" and not answered:
- if read_timeout is None or read_timeout is _UNSET:
- self.unbounded_requests += 1
+ read_timeout = request.read_timeout
+ if read_timeout is None:
+ network.unbounded_requests += 1
raise RunStopped("request with no read timeout")
- self.advance(float(read_timeout))
+ network.advance(float(read_timeout))
raise TimeoutError("timed out")
if mode == "rate_limit" and not answered:
- return _http_response(
+ return http_response(
b"429 Too Many Requests", b"{}", [b"Retry-After: " + str(HOSTILE_RETRY_AFTER_SECONDS).encode()]
)
- last = mode == "empty_pages" and self.requests >= _EMPTY_PAGE_COUNT
- next_url = None if last else f"{origin}{path.split('?', 1)[0]}?contract_page={self.requests + 1}"
+ last = mode == "empty_pages" and network.requests >= _EMPTY_PAGE_COUNT
+ next_url = None if last else f"{request.origin}{request.path}?contract_page={network.requests + 1}"
headers = [] if next_url is None else [b"Link: <" + next_url.encode() + b'>; rel="next"']
- if self.scenario.list_bodies and method == b"GET":
- return _http_response(b"200 OK", b"[]", headers)
- return _http_response(b"200 OK", json.dumps(empty_page_body(next_url, self.requests)).encode(), headers)
-
-
-def _http_response(status: bytes, body: bytes, headers: list[bytes]) -> io.BytesIO:
- lines = [
- b"HTTP/1.1 " + status,
- b"Content-Type: application/json",
- b"Content-Length: " + str(len(body)).encode(),
- b"Connection: close",
- *headers,
- ]
- return io.BytesIO(b"\r\n".join(lines) + b"\r\n\r\n" + body)
-
-
-class _FailingStream(io.RawIOBase):
- def __init__(self, error: BaseException) -> None:
- super().__init__()
- self._error = error
-
- def readable(self) -> bool:
- return True
-
- def readline(self, size: int | None = -1) -> bytes:
- raise self._error
-
- def readinto(self, buffer: Any) -> int:
- raise self._error
-
-
-class _FakeSocket:
- def __init__(self, network: FakeNetwork, origin: str) -> None:
- self._network = network
- self._origin = origin
- self._sent = b""
- self._read_timeout: Any = _UNSET
-
- def settimeout(self, value: Any) -> None:
- self._read_timeout = value
-
- def gettimeout(self) -> Any:
- return None if self._read_timeout is _UNSET else self._read_timeout
-
- def sendall(self, data: Any, *args: Any) -> None:
- self._sent += bytes(data)
-
- def send(self, data: Any, *args: Any) -> int:
- self._sent += bytes(data)
- return len(data)
-
- def makefile(self, *args: Any, **kwargs: Any) -> io.IOBase:
- sent, self._sent = self._sent, b""
- try:
- return self._network.respond(self._origin, sent, self._read_timeout)
- except (TimeoutError, RunStopped) as error:
- # A real socket fails at the first read, and not when `http.client` wraps it.
- return _FailingStream(error)
-
- def setsockopt(self, *args: Any) -> None:
- pass
-
- def shutdown(self, *args: Any) -> None:
- pass
-
- def close(self) -> None:
- pass
-
-
-class _MemoryRedis:
- def __init__(self) -> None:
- self._data: dict[str, Any] = {}
-
- def ping(self) -> bool:
- return True
-
- def set(self, key: str, value: Any, **kwargs: Any) -> None:
- self._data[key] = value
-
- def get(self, key: str) -> Any:
- return self._data.get(key)
-
- def exists(self, key: str) -> int:
- return int(key in self._data)
-
- def delete(self, key: str) -> None:
- self._data.pop(key, None)
-
-
-def _sleep_aliases() -> list[tuple[Any, str]]:
- """Each `from time import sleep` binding in a loaded source module. A patch of `time.sleep` does not reach them."""
- aliases: list[tuple[Any, str]] = []
- for module_name, module in list(sys.modules.items()):
- if not module_name.startswith(_SOURCES_PACKAGE):
- continue
- aliases.extend((module, name) for name, value in list(vars(module).items()) if value is _REAL_SLEEP)
- return aliases
-
-
-def _controller_of(value: Any) -> tenacity.Retrying | None:
- if isinstance(value, staticmethod | classmethod):
- value = value.__func__
- if not isinstance(value, types.FunctionType):
- return None
- controller = value.__dict__.get("retry")
- return controller if isinstance(controller, tenacity.Retrying) else None
-
-
-def _retry_controllers() -> list[tenacity.Retrying]:
- """Each synchronous tenacity controller that a `@retry` decorator put on a function or a method.
-
- A test can replace the `sleep` of one for the rest of the process, for example
- `RESTClient._send_request.retry.sleep = lambda *_: None`. That wait then never reaches the fake
- clock, and the verdict of every later source depends on which tests ran before.
- """
- controllers: dict[int, tenacity.Retrying] = {}
- for module in list(sys.modules.values()):
- for value in list(getattr(module, "__dict__", {}).values()):
- candidates = list(vars(value).values()) if inspect.isclass(value) else []
- for candidate in [value, *candidates]:
- if (controller := _controller_of(candidate)) is not None:
- controllers[id(controller)] = controller
- return list(controllers.values())
-
-
-def _waits_on_the_fake_clock(sleep: Callable[[float], None]) -> Iterator[None]:
- """Give each retry controller the fake `sleep`, and put back what each one had. This is cheaper than `mock.patch`."""
- controllers = _retry_controllers()
- originals = [controller.sleep for controller in controllers]
- for controller in controllers:
- controller.sleep = sleep
- try:
- yield
- finally:
- for controller, original in zip(controllers, originals):
- controller.sleep = original
-
-
-def fake_environment(scenario: Scenario) -> Iterator[FakeNetwork]:
- """Route HTTP to a `FakeNetwork`, block every other connection, and make each wait advance a fake clock."""
- network = FakeNetwork(scenario)
- redis = _MemoryRedis()
-
- def connect(connection: Any) -> None:
- scheme = "https" if isinstance(connection, HTTPSConnection) else "http"
- default_port = 443 if scheme == "https" else 80
- port = "" if connection.port in (None, default_port) else f":{connection.port}"
- connection.sock = _FakeSocket(network, f"{scheme}://{connection.host}{port}")
- connection.is_verified = True
-
- def blocked_connection(*args: Any, **kwargs: Any) -> Any:
- network.blocked_connections += 1
- raise NetworkBlockedError("the contract tests allow no real connection")
-
- def blocked_database(*args: Any, **kwargs: Any) -> Any:
- network.blocked_database_reads += 1
- raise DatabaseBlockedError("the contract tests have no database")
-
- # A source that checks its host before it connects gets a public address. Nothing connects to it.
- def resolve(host: Any, port: Any, *args: Any, **kwargs: Any) -> list[Any]:
- return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (_PUBLIC_ADDRESS, int(port or 0)))]
-
- def resolve_host_ips(host: str) -> set[Any]:
- return {ipaddress.ip_address(_PUBLIC_ADDRESS)}
-
- def sleep(seconds: float) -> None:
- network.advance(seconds)
-
- async def async_sleep(seconds: float, result: Any = None) -> Any:
- network.advance(seconds)
- return await _REAL_ASYNC_SLEEP(0, result)
-
- @contextlib.contextmanager
- def memory_redis(_manager: Any) -> Iterator[_MemoryRedis]:
- yield redis
-
- patches: list[Any] = [
- mock.patch.object(HTTPConnection, "connect", connect),
- mock.patch.object(HTTPSConnection, "connect", connect),
- mock.patch.object(socket.socket, "connect", blocked_connection),
- mock.patch.object(socket.socket, "connect_ex", blocked_connection),
- mock.patch.object(socket.socket, "sendto", blocked_connection),
- mock.patch.object(socket, "create_connection", blocked_connection),
- mock.patch.object(socket, "getaddrinfo", resolve),
- mock.patch.object(url_validation, "resolve_host_ips", resolve_host_ips),
- mock.patch.object(BaseDatabaseWrapper, "ensure_connection", blocked_database),
- mock.patch.object(time, "sleep", sleep),
- mock.patch.object(time, "monotonic", lambda: _REAL_MONOTONIC() + network.elapsed),
- mock.patch.object(time, "time", lambda: _REAL_TIME() + network.elapsed),
- mock.patch.object(asyncio, "sleep", async_sleep),
- mock.patch.object(ResumableSourceManager, "_get_redis", memory_redis),
- *(mock.patch.object(module, name, sleep) for module, name in _sleep_aliases()),
- _waits_on_the_fake_clock(sleep),
- ]
- with contextlib.ExitStack() as stack:
- for patch in patches:
- stack.enter_context(patch)
- yield network
+ if self.scenario.list_bodies and request.method == "GET":
+ return http_response(b"200 OK", b"[]", headers)
+ return http_response(b"200 OK", json.dumps(empty_page_body(next_url, network.requests)).encode(), headers)
def is_stub(source: _BaseSource[Any]) -> bool:
@@ -512,23 +250,6 @@ def placeholder_configs(config_class: type) -> Iterator[Any]:
continue
-def source_inputs(schema_name: str) -> SourceInputs:
- return SourceInputs(
- schema_name=schema_name,
- schema_id="00000000-0000-4000-8000-000000000001",
- source_id="00000000-0000-4000-8000-000000000002",
- 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="00000000-0000-4000-8000-000000000003",
- logger=structlog.get_logger("source_contract"),
- reset_pipeline=False,
- )
-
-
def start_source(source: _BaseSource[Any], config: Any) -> StartExtraction:
def start(inputs: SourceInputs) -> tuple[SourceResponse, ResumableSourceManager[Any] | None]:
if isinstance(source, ResumableSource):
@@ -547,7 +268,7 @@ async def _drain_async(items: Any, on_item: Callable[[], None]) -> None:
def run_extraction(start: StartExtraction, schema_name: str, scenario: Scenario) -> FakeNetwork:
"""Run one extraction to its end, or to its first error, and return what the fake network recorded."""
- with fake_environment(scenario) as network:
+ with fake_environment(ScenarioResponder(scenario)) as network:
try:
response, manager = start(source_inputs(schema_name))
items = response.items()
@@ -646,7 +367,7 @@ def check_source(source: _BaseSource[Any]) -> SourceStatus:
def _check_source_with_config(source: _BaseSource[Any], config: Any) -> SourceStatus:
- with fake_environment(Scenario(mode="empty_pages")) as discovery:
+ with fake_environment(ScenarioResponder(Scenario(mode="empty_pages"))) as discovery:
try:
schema_names = [schema.name for schema in source.get_schemas(config, team_id=1)]
except (Exception, RunStopped) as error:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_contract.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_contract.py
index d545303790bd..25bff5864fe6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_contract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_contract.py
@@ -44,6 +44,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.tests.cont
STALL_BUDGET,
TIMEOUT,
Scenario,
+ ScenarioResponder,
SourceStatus,
StartExtraction,
check_extraction,
@@ -238,7 +239,7 @@ def test_retry_waits_reach_the_fake_clock_after_a_test_replaced_them(monkeypatch
# verdict of a source must not depend on whether such a test ran earlier in the same process.
controller = cast(Any, _retried_call).retry
monkeypatch.setattr(controller, "sleep", lambda *_: None)
- with fake_environment(Scenario(mode="stall")):
+ with fake_environment(ScenarioResponder(Scenario(mode="stall"))):
assert controller.sleep is time.sleep
assert controller.sleep is not time.sleep
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/tests/test_zylo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/tests/test_zylo.py
index 875357e54741..e74af2af8c8d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/tests/test_zylo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zylo/tests/test_zylo.py
@@ -1,21 +1,21 @@
-import json
-from collections.abc import Iterable
from datetime import UTC, date, datetime
-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.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.generated_configs.zylo import ZyloSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.zylo.source import ZyloSource
from products.warehouse_sources.backend.temporal.data_imports.sources.zylo.zylo import (
INITIAL_INCREMENTAL_VALUE,
ZyloResumeConfig,
_format_zylo_filter_date,
probe_endpoint_status,
validate_credentials,
- zylo_source,
)
@@ -36,170 +36,95 @@ class TestFormatZyloFilterDate:
assert _format_zylo_filter_date("not-a-date") == "not-a-date,gte"
-def _make_http_response(body: list[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 TestZyloSourceResumeBehavior:
- """End-to-end resume behaviour of ``zylo_source`` via ``rest_api_resource``."""
-
- def _drive(
- self,
- endpoint: str,
- manager: MagicMock,
- responses: list[Response],
- should_use_incremental_field: bool = False,
- incremental_field: str | None = None,
- db_incremental_field_last_value: Any = None,
- sent_urls: list[str] | None = None,
- rows: list[dict[str, Any]] | None = None,
- ) -> 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 {}))
- if sent_urls is not None:
- sent_urls.append(request.url)
- 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
-
- resource = zylo_source(
- token_id="tok_id",
- token_secret="tok_secret",
- endpoint=endpoint,
- team_id=123,
- job_id="test_job",
- resumable_source_manager=manager,
- db_incremental_field_last_value=db_incremental_field_last_value,
- should_use_incremental_field=should_use_incremental_field,
- incremental_field=incremental_field,
- )
- for item in cast(Iterable[Any], resource.items()):
- if rows is not None:
- rows.extend(item if isinstance(item, list) else [item])
- return sent_params
+ """End-to-end resume behaviour of ``ZyloSource``, driven through ``source_for_pipeline``."""
- def test_fresh_run_saves_skip_after_each_non_terminal_page(self) -> None:
- manager = MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = False
+ @staticmethod
+ def _driver() -> SourceDriver:
+ return SourceDriver(ZyloSource(), ZyloSourceConfig(token_id="tok_id", token_secret="tok_secret"))
- responses = [
- _make_http_response([{"id": f"app_{i}"} for i in range(1000)]),
- _make_http_response([{"id": f"app_{i}"} for i in range(1000, 2000)]),
- _make_http_response([{"id": "app_last"}]),
- ]
- sent_params = self._drive("Applications", manager, responses)
+ @staticmethod
+ def _page(rows: list[dict[str, Any]]) -> ScriptedResponse:
+ return ScriptedResponse(json=rows)
- assert [p.get("skip") for p in sent_params] == [0, 1000, 2000]
- assert all(p.get("limit") == 1000 for p in sent_params)
+ def test_fresh_run_saves_skip_after_each_non_terminal_page(self) -> None:
+ result = self._driver().run(
+ "Applications",
+ [
+ self._page([{"id": f"app_{i}"} for i in range(1000)]),
+ self._page([{"id": f"app_{i}"} for i in range(1000, 2000)]),
+ self._page([{"id": "app_last"}]),
+ ],
+ )
- saved = [call.args[0] for call in manager.save_state.call_args_list]
- assert saved == [ZyloResumeConfig(next_skip=1000), ZyloResumeConfig(next_skip=2000)]
+ assert result.params("skip") == ["0", "1000", "2000"]
+ assert result.params("limit") == ["1000", "1000", "1000"]
+ assert result.saved_states == [ZyloResumeConfig(next_skip=1000), ZyloResumeConfig(next_skip=2000)]
def test_resume_seeds_paginator_with_saved_skip(self) -> None:
- manager = MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = True
- manager.load_state.return_value = ZyloResumeConfig(next_skip=2000)
-
- responses = [_make_http_response([{"id": "app_last"}])]
- sent_params = self._drive("Applications", manager, responses)
-
- assert [p.get("skip") for p in sent_params] == [2000]
- manager.load_state.assert_called_once()
+ result = self._driver().run(
+ "Applications",
+ [self._page([{"id": "app_last"}])],
+ resume_state=ZyloResumeConfig(next_skip=2000),
+ )
- def test_does_not_load_state_when_cannot_resume(self) -> None:
- manager = MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = False
+ assert result.params("skip") == ["2000"]
- responses = [_make_http_response([{"id": "a"}])]
- self._drive("Applications", manager, responses)
+ def test_a_run_with_no_saved_state_starts_from_the_first_page(self) -> None:
+ result = self._driver().run("Applications", [self._page([{"id": "a"}])])
- manager.load_state.assert_not_called()
+ assert result.params("skip") == ["0"]
def test_incremental_request_carries_gte_filter_and_sort(self) -> None:
- manager = MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = False
-
- responses = [_make_http_response([{"id": "contract_1"}])]
- sent_params = self._drive(
+ result = self._driver().run(
"Contracts",
- manager,
- responses,
- should_use_incremental_field=True,
+ [self._page([{"id": "contract_1"}])],
incremental_field="zylo_created_at",
- db_incremental_field_last_value=None,
)
- assert sent_params[0]["zylo_created_at"] == f"{INITIAL_INCREMENTAL_VALUE},gte"
- assert sent_params[0]["sort"] == "+zylo_created_at"
+ assert result.requests[0].param("zylo_created_at") == f"{INITIAL_INCREMENTAL_VALUE},gte"
+ assert result.requests[0].param("sort") == "+zylo_created_at"
def test_executions_fan_out_per_automation_with_incremental_filter(self) -> None:
- manager = MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = False
-
- responses = [
- _make_http_response([{"id": "auto_1"}, {"id": "auto_2"}]),
- _make_http_response([{"id": f"exec_{i}", "automation_id": "auto_1"} for i in range(1000)]),
- _make_http_response([{"id": "exec_last", "automation_id": "auto_1"}]),
- _make_http_response([{"id": "exec_b", "automation_id": "auto_2"}]),
- ]
- sent_urls: list[str] = []
- rows: list[dict[str, Any]] = []
- sent_params = self._drive(
+ result = self._driver().run(
"AutomationExecutions",
- manager,
- responses,
- should_use_incremental_field=True,
+ [
+ self._page([{"id": "auto_1"}, {"id": "auto_2"}]),
+ self._page([{"id": f"exec_{i}", "automation_id": "auto_1"} for i in range(1000)]),
+ self._page([{"id": "exec_last", "automation_id": "auto_1"}]),
+ self._page([{"id": "exec_b", "automation_id": "auto_2"}]),
+ ],
incremental_field="zylo_modified_at",
db_incremental_field_last_value=datetime(2026, 7, 21, 12, tzinfo=UTC),
- sent_urls=sent_urls,
- rows=rows,
)
- assert [url.removeprefix("https://api.zylo.com") for url in sent_urls] == [
+ assert result.paths == [
"/v2/automations",
"/v2/automations/auto_1/executions",
"/v2/automations/auto_1/executions",
"/v2/automations/auto_2/executions",
]
- assert "zylo_modified_at" not in sent_params[0]
- assert [p.get("skip") for p in sent_params[1:]] == [0, 1000, 0]
- for child_params in sent_params[1:]:
- assert child_params["zylo_modified_at"] == "2026-07-21,gte"
- assert child_params["sort"] == "+zylo_modified_at"
- assert len(rows) == 1002
+ assert result.requests[0].param("zylo_modified_at") is None
+ assert result.params("skip")[1:] == ["0", "1000", "0"]
+ for request in result.requests[1:]:
+ assert request.param("zylo_modified_at") == "2026-07-21,gte"
+ assert request.param("sort") == "+zylo_modified_at"
+ assert len(result.rows) == 1002
def test_executions_resume_skips_completed_automations(self) -> None:
- manager = MagicMock(spec=ResumableSourceManager)
- manager.can_resume.return_value = True
- manager.load_state.return_value = ZyloResumeConfig(
- fanout_state={"completed": ["/v2/automations/auto_1/executions"], "current": None, "child_state": None}
+ result = self._driver().run(
+ "AutomationExecutions",
+ [
+ self._page([{"id": "auto_1"}, {"id": "auto_2"}]),
+ self._page([{"id": "exec_b", "automation_id": "auto_2"}]),
+ ],
+ resume_state=ZyloResumeConfig(
+ fanout_state={"completed": ["/v2/automations/auto_1/executions"], "current": None, "child_state": None}
+ ),
)
- responses = [
- _make_http_response([{"id": "auto_1"}, {"id": "auto_2"}]),
- _make_http_response([{"id": "exec_b", "automation_id": "auto_2"}]),
- ]
- sent_urls: list[str] = []
- self._drive("AutomationExecutions", manager, responses, sent_urls=sent_urls)
-
- assert [url.removeprefix("https://api.zylo.com") for url in sent_urls] == [
- "/v2/automations",
- "/v2/automations/auto_2/executions",
- ]
- saved = manager.save_state.call_args_list[-1].args[0]
+ assert result.paths == ["/v2/automations", "/v2/automations/auto_2/executions"]
+ saved = result.saved_states[-1]
assert saved.next_skip is None
assert set(saved.fanout_state["completed"]) == {
"/v2/automations/auto_1/executions",