Skip to content

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

feat(data-warehouse): implement the qonto import source (#111852)

Tom Owers986c98808d04
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index ee9cf3ae474d..799d794aa8bd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -629,6 +629,7 @@ the row lists both.
| pylon | HTTP | requests | ✅ |
| pypi | HTTP | requests | ✅ |
| qdrant | HTTP | requests | ✅ |
+| qonto | HTTP | requests | ✅ |
| qualaroo | HTTP | requests | ✅ |
| qualtrics | HTTP | requests | ✅ |
| qualys_vmdr | HTTP (XML responses) | requests | ✅ |
@@ -1337,7 +1338,6 @@ doesn't conflict with concurrent PRs.
- prompting_company
- proofpoint_tap
- pubnub
-- qonto
- quay
- quickbooks
- railz
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/qonto.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/qonto.py
index 4a1e1ba38eb8..2302dcefad7c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/qonto.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/qonto.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class QontoSourceConfig(config.Config):
- pass
+ login: str
+ secret_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/qonto/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qonto/canonical_descriptions.py
new file mode 100644
index 000000000000..680eb11edd4e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qonto/canonical_descriptions.py
@@ -0,0 +1,59 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+DOCS = "https://docs.qonto.com/api-reference/business-api/"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "bank_accounts": {
+ "description": "Qonto bank accounts for the authenticated organization, including balances and account details.",
+ "docs_url": DOCS
+ + "accounts-organizations/organizations/retrieve-the-authenticated-organization-and-list-bank-accounts",
+ "columns": {
+ "id": "Unique bank account identifier.",
+ "iban": "International bank account number.",
+ "currency": "Currency of the bank account.",
+ "balance": "Current account balance.",
+ "authorized_balance": "Balance available for payments, including transactions in progress.",
+ "status": "Account status: active or closed.",
+ },
+ },
+ "transactions": {
+ "description": "Transactions across Qonto bank accounts, including pending, declined, completed, and reversed transactions.",
+ "docs_url": DOCS + "transactions-statements/transactions/list-transactions",
+ "columns": {
+ "id": "Unique transaction identifier.",
+ "bank_account_id": "Identifier of the bank account that contains the transaction.",
+ "amount_cents": "Transaction amount in the smallest currency unit.",
+ "currency": "Transaction currency.",
+ "side": "Direction of the transaction: credit or debit.",
+ "updated_at": "Time of the last transaction update.",
+ "settled_at": "Time when the transaction settled.",
+ "label_ids": "Identifiers of labels assigned to the transaction.",
+ },
+ },
+ "labels": {
+ "description": "Labels that classify transactions for the authenticated organization.",
+ "docs_url": DOCS + "accounts-organizations/labels/list-labels",
+ "columns": {
+ "id": "Unique label identifier.",
+ "name": "Label name.",
+ "parent_id": "Identifier of the parent label.",
+ },
+ },
+ "memberships": {
+ "description": "Users with access to the organization's Qonto account.",
+ "docs_url": DOCS + "accounts-organizations/memberships/list-memberships",
+ "columns": {"id": "Unique membership identifier.", "role": "Member's role in the organization."},
+ },
+ "transfers": {
+ "description": "SEPA transfers for the authenticated organization.",
+ "docs_url": DOCS + "payments-transfers/sepa-transfers/sepa-transfers/index",
+ "columns": {
+ "id": "Unique transfer identifier.",
+ "status": "Current transfer status.",
+ "updated_at": "Time of the last transfer update.",
+ "beneficiary_id": "Identifier of the transfer beneficiary.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/qonto/qonto.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qonto/qonto.py
new file mode 100644
index 000000000000..caed8732bf7d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qonto/qonto.py
@@ -0,0 +1,149 @@
+from datetime import datetime
+from typing import Any
+from urllib.parse import quote
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_value
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import rest_api_resources
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ Endpoint,
+ EndpointResource,
+ RESTAPIConfig,
+)
+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 SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.qonto import QontoSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.qonto.settings import (
+ AUTH_ERROR,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ PERMISSION_ERROR,
+)
+
+
+@frozen
+class QontoResumeConfig:
+ paginator_state: dict[str, Any]
+
+
+def validate_credentials(
+ config: QontoSourceConfig, api_version: str, schema_name: str | None
+) -> tuple[bool, str | None]:
+ if any("\r" in value or "\n" in value for value in (config.login, config.secret_key)):
+ return False, AUTH_ERROR
+
+ with make_tracked_session() as session:
+ response = session.get(
+ f"https://thirdparty.qonto.com/{api_version}/organization",
+ auth=APIKeyAuth(api_key=f"{config.login}:{config.secret_key}"),
+ timeout=30,
+ )
+ if response.status_code == 401:
+ return False, AUTH_ERROR
+ if response.status_code == 403:
+ return (True, None) if schema_name is None else (False, PERMISSION_ERROR)
+ response.raise_for_status()
+ return True, None
+
+
+def account_for_request(row: dict[str, Any]) -> dict[str, Any]:
+ return {**row, "request_id": quote(str(row["id"]), safe="")}
+
+
+def transaction_with_account(row: dict[str, Any]) -> dict[str, Any]:
+ row["bank_account_id"] = row.pop("_bank_accounts_id")
+ return row
+
+
+def get_resource(name: str, incremental: bool, last_value: str | datetime | None) -> EndpointResource:
+ if name not in ENDPOINTS:
+ raise ValueError(f"Unknown Qonto table: {name}")
+ path, selector = ENDPOINTS[name]
+ params: dict[str, Any] = {}
+ if name != "bank_accounts":
+ params["per_page"] = 100
+ if name in INCREMENTAL_FIELDS:
+ params["sort_by"] = "updated_at:desc"
+ if incremental and last_value is not None:
+ watermark = parse_datetime_value(last_value)
+ if watermark is None:
+ raise ValueError("Invalid Qonto incremental timestamp")
+ params["updated_at_from"] = watermark.isoformat()
+ if name == "transactions":
+ # The account belongs in the path because the framework uses paths to identify resume checkpoints.
+ path += "?bank_account_id={bank_account_id}"
+ params["bank_account_id"] = {"type": "resolve", "resource": "bank_accounts", "field": "request_id"}
+ params["status[]"] = ["pending", "declined", "completed", "reversed"]
+
+ endpoint: Endpoint = {
+ "path": path,
+ "data_selector": selector,
+ "data_selector_required": True,
+ "params": params,
+ "paginator": "single_page"
+ if name == "bank_accounts"
+ else PageNumberPaginator(base_page=1, total_path="meta.total_pages"),
+ }
+ resource: EndpointResource = {
+ "name": name,
+ "table_name": name,
+ "endpoint": endpoint,
+ }
+ if name == "transactions":
+ resource["include_from_parent"] = ["id"]
+ resource["data_map"] = transaction_with_account
+ return resource
+
+
+def qonto_source(
+ config: QontoSourceConfig,
+ endpoint: str,
+ api_version: str,
+ team_id: int,
+ job_id: str,
+ manager: ResumableSourceManager[QontoResumeConfig],
+ incremental: bool,
+ last_value: str | datetime | None,
+) -> SourceResponse:
+ resource = get_resource(endpoint, incremental, last_value)
+ resources: list[str | EndpointResource] = [resource]
+ if endpoint == "transactions":
+ parent = get_resource("bank_accounts", False, None)
+ parent["data_map"] = account_for_request
+ resources.insert(0, parent)
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": f"https://thirdparty.qonto.com/{api_version}/",
+ "auth": APIKeyAuth(api_key=f"{config.login}:{config.secret_key}"),
+ "request_timeout": 30,
+ },
+ "resources": resources,
+ }
+ resume = manager.load_state() if manager.can_resume() else None
+
+ def save_checkpoint(state: dict[str, Any] | None) -> None:
+ if state is not None:
+ manager.save_state(QontoResumeConfig(paginator_state=state))
+
+ result = rest_api_resources(
+ rest_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=resume.paginator_state if resume else None,
+ )
+ selected = next(item for item in result if item.name == endpoint)
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: selected,
+ primary_keys=["bank_account_id", "id"] if endpoint == "transactions" else ["id"],
+ sort_mode="desc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/qonto/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qonto/settings.py
new file mode 100644
index 000000000000..45e314967731
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qonto/settings.py
@@ -0,0 +1,24 @@
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+ENDPOINTS = {
+ "bank_accounts": ("organization", "organization.bank_accounts"),
+ "transactions": ("transactions", "transactions"),
+ "labels": ("labels", "labels"),
+ "memberships": ("memberships", "memberships"),
+ "transfers": ("sepa/transfers", "transfers"),
+}
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: [
+ {
+ "label": "updated_at",
+ "field": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ]
+ for name in ("transactions", "transfers")
+}
+
+AUTH_ERROR = "Qonto rejected the credentials. Check your organization login and secret key."
+PERMISSION_ERROR = "Qonto denied access. Check that your account can read the selected data."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/qonto/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qonto/source.py
index 50ef89ee22e7..867a80f42da4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/qonto/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qonto/source.py
@@ -1,18 +1,98 @@
from typing import cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.qonto import QontoSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.qonto.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.qonto.qonto import (
+ QontoResumeConfig,
+ qonto_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.qonto.settings import (
+ AUTH_ERROR,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ PERMISSION_ERROR,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class QontoSource(SimpleSource[QontoSourceConfig]):
+class QontoSource(ResumableSource[QontoSourceConfig, QontoResumeConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = ("v2",)
+ default_version = "v2"
+ api_docs_url = "https://docs.qonto.com/get-started/general/versioning"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.QONTO
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {"401 Client Error": AUTH_ERROR, "403 Client Error": PERMISSION_ERROR}
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: QontoSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: QontoSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_credentials(config, self.resolve_api_version(api_version), schema_name)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[QontoResumeConfig]:
+ return ResumableSourceManager(inputs, QontoResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: QontoSourceConfig,
+ resumable_source_manager: ResumableSourceManager[QontoResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return qonto_source(
+ config=config,
+ endpoint=inputs.schema_name,
+ api_version=self.resolve_api_version(inputs.api_version),
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ manager=resumable_source_manager,
+ incremental=inputs.should_use_incremental_field,
+ last_value=inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
@@ -20,6 +100,27 @@ class QontoSource(SimpleSource[QontoSourceConfig]):
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
label="Qonto",
iconPath="/static/services/qonto.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="Find your organization login and secret key in Qonto under **Integrations and Partnerships > API key**.",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="login",
+ label="Organization login",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="example-company-1234",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="secret_key",
+ label="Secret key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/qonto/tests/test_qonto.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qonto/tests/test_qonto.py
new file mode 100644
index 000000000000..ebe72f9e8328
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qonto/tests/test_qonto.py
@@ -0,0 +1,246 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, datetime
+from http import HTTPStatus
+from typing import Any, cast
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import HTTPError, Response
+
+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.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.qonto import QontoSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.qonto.qonto import (
+ QontoResumeConfig,
+ qonto_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.qonto.settings import AUTH_ERROR, PERMISSION_ERROR
+from products.warehouse_sources.backend.temporal.data_imports.sources.qonto.source import QontoSource
+
+CONFIG = QontoSourceConfig(login="example-company", secret_key="fake-secret")
+
+
+def response(body: dict[str, Any], status: int = 200) -> Response:
+ result = Response()
+ result.status_code = status
+ result.reason = HTTPStatus(status).phrase
+ result.url = "https://thirdparty.qonto.com/v2/organization"
+ result.headers["Content-Type"] = "application/json"
+ result._content = json.dumps(body).encode()
+ return result
+
+
+def page(name: str, rows: list[dict[str, Any]], current: int = 1, total: int = 1) -> Response:
+ return response(
+ {
+ name: rows,
+ "meta": {
+ "current_page": current,
+ "total_pages": total,
+ "next_page": current + 1 if current < total else None,
+ },
+ }
+ )
+
+
+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 = QontoResumeConfig(paginator_state=state) if state is not None else None
+ return result
+
+
+def source(
+ endpoint: str, resume_manager: MagicMock, incremental: bool = False, last_value: str | datetime | None = None
+) -> SourceResponse:
+ return qonto_source(CONFIG, endpoint, "v2", 1, "test-job", resume_manager, incremental, last_value)
+
+
[email protected]("endpoint", ["labels", "memberships", "transfers"])
[email protected]("empty_terminal", [False, True])
+def test_pagination_stops_at_last_page(endpoint: str, empty_terminal: bool) -> None:
+ resume_manager = manager()
+ last_rows = [] if empty_terminal else [{"id": "last"}]
+ with patch(
+ "requests.Session.send", side_effect=[page(endpoint, [{"id": "first"}], 1, 2), page(endpoint, last_rows, 2, 2)]
+ ) as send:
+ result = source(endpoint, resume_manager)
+ rows = [row for batch in cast(Iterable[list[dict[str, Any]]], result.items()) for row in batch]
+ assert rows == [{"id": "first"}, *last_rows]
+ requests = [call.args[0] for call in send.call_args_list]
+ assert [parse_qs(urlsplit(request.url).query)["page"] for request in requests] == [["1"], ["2"]]
+ assert all(request.headers["Authorization"] == "example-company:fake-secret" for request in requests)
+ assert all(call.kwargs["timeout"] == 30 for call in send.call_args_list)
+ assert all(parse_qs(urlsplit(request.url).query)["per_page"] == ["100"] for request in requests)
+ expected_path = "/v2/sepa/transfers" if endpoint == "transfers" else f"/v2/{endpoint}"
+ assert all(urlsplit(request.url).path == expected_path for request in requests)
+ resume_manager.save_state.assert_called_once_with(QontoResumeConfig(paginator_state={"page": 2}))
+
+
+def test_resume_starts_at_saved_page() -> None:
+ resume_manager = manager({"page": 3})
+ with patch("requests.Session.send", side_effect=[page("labels", [{"id": "last"}], 3, 3)]) as send:
+ assert list(cast(Iterable[Any], source("labels", resume_manager).items())) == [[{"id": "last"}]]
+ assert parse_qs(urlsplit(send.call_args.args[0].url).query)["page"] == ["3"]
+ resume_manager.save_state.assert_not_called()
+
+
+ ("incremental", "last_value", "expected"),
+ [
+ (False, "2025-01-02T03:04:05Z", None),
+ (True, None, None),
+ (True, "2025-01-02T03:04:05Z", "2025-01-02T03:04:05+00:00"),
+ (True, datetime(2025, 1, 2, 3, 4, 5, tzinfo=UTC), "2025-01-02T03:04:05+00:00"),
+ (True, datetime(2025, 1, 2, 3, 4, 5), "2025-01-02T03:04:05+00:00"),
+ ],
+)
[email protected]("endpoint", ["transactions", "transfers"])
+def test_incremental_filters(
+ endpoint: str, incremental: bool, last_value: str | datetime | None, expected: str | None
+) -> None:
+ responses = [page(endpoint, [{"id": "row"}], 1, 2), page(endpoint, [{"id": "last"}], 2, 2)]
+ if endpoint == "transactions":
+ responses.insert(0, response({"organization": {"bank_accounts": [{"id": "account-1"}]}}))
+ with patch("requests.Session.send", side_effect=responses) as send:
+ result = source(endpoint, manager(), incremental, last_value)
+ list(cast(Iterable[Any], result.items()))
+ requests = [call.args[0] for call in send.call_args_list if urlsplit(call.args[0].url).path != "/v2/organization"]
+ for request in requests:
+ params = parse_qs(urlsplit(request.url).query)
+ assert params.get("updated_at_from") == ([expected] if expected else None)
+ assert params["sort_by"] == ["updated_at:desc"]
+ if endpoint == "transactions":
+ assert params["status[]"] == ["pending", "declined", "completed", "reversed"]
+ assert params["bank_account_id"] == ["account-1"]
+ assert result.sort_mode == "desc"
+
+
+def test_transactions_across_accounts_and_resume() -> None:
+ resume_manager = manager()
+ accounts = response({"organization": {"bank_accounts": [{"id": "account-1"}, {"id": "account&2"}]}})
+ with patch(
+ "requests.Session.send",
+ side_effect=[
+ accounts,
+ page("transactions", [{"id": "shared-id"}]),
+ page("transactions", [{"id": "shared-id"}], 1, 2),
+ page("transactions", [{"id": "last"}], 2, 2),
+ ],
+ ) as send:
+ result = source("transactions", resume_manager)
+ batches = list(cast(Iterable[Any], result.items()))
+ assert batches == [
+ [{"id": "shared-id", "bank_account_id": "account-1"}],
+ [{"id": "shared-id", "bank_account_id": "account&2"}],
+ [{"id": "last", "bank_account_id": "account&2"}],
+ ]
+ assert result.primary_keys == ["bank_account_id", "id"]
+ assert [parse_qs(urlsplit(call.args[0].url).query)["bank_account_id"] for call in send.call_args_list[1:]] == [
+ ["account-1"],
+ ["account&2"],
+ ["account&2"],
+ ]
+ saved = [call.args[0].paginator_state for call in resume_manager.save_state.call_args_list]
+ checkpoint = next(state for state in saved if state.get("child_state") == {"page": 2})
+ assert checkpoint["completed"] == ["transactions?bank_account_id=account-1"]
+ assert checkpoint["current"] == "transactions?bank_account_id=account%262"
+ with patch(
+ "requests.Session.send", side_effect=[accounts, page("transactions", [{"id": "last"}], 2, 2)]
+ ) as resumed_send:
+ resumed = source("transactions", manager(checkpoint))
+ assert list(cast(Iterable[Any], resumed.items())) == [batches[-1]]
+ params = parse_qs(urlsplit(resumed_send.call_args.args[0].url).query)
+ assert params["page"] == ["2"]
+ assert params["bank_account_id"] == ["account&2"]
+
+
[email protected]("accounts", [[], [{"id": "account-1", "balance": 123}]])
+def test_bank_accounts_and_empty_transaction_fanout(accounts: list[dict[str, Any]]) -> None:
+ payload = response({"organization": {"bank_accounts": accounts}})
+ with patch("requests.Session.send", return_value=payload) as send:
+ batches = list(cast(Iterable[Any], source("bank_accounts", manager()).items()))
+ assert batches == ([accounts] if accounts else [])
+ assert send.call_count == 1
+ assert send.call_args.args[0].url == "https://thirdparty.qonto.com/v2/organization"
+ if not accounts:
+ with patch("requests.Session.send", return_value=payload) as send:
+ assert list(cast(Iterable[Any], source("transactions", manager()).items())) == []
+ assert send.call_count == 1
+
+
+ ("status", "schema_name", "expected"),
+ [
+ (200, None, (True, None)),
+ (401, None, (False, AUTH_ERROR)),
+ (403, None, (True, None)),
+ (403, "transactions", (False, PERMISSION_ERROR)),
+ ],
+)
+def test_credential_validation(status: int, schema_name: str | None, expected: tuple[bool, str | None]) -> None:
+ with patch("requests.Session.send", return_value=response({}, status)) as send:
+ assert validate_credentials(CONFIG, "v2", schema_name) == expected
+ send.assert_called_once()
+ assert send.call_args.args[0].url == "https://thirdparty.qonto.com/v2/organization"
+ assert send.call_args.args[0].headers["Authorization"] == "example-company:fake-secret"
+
+
+ "config",
+ [
+ QontoSourceConfig(login="bad\nlogin", secret_key="stored-secret"),
+ QontoSourceConfig(login="example-company", secret_key="bad\rsecret"),
+ ],
+)
+def test_credential_validation_rejects_header_injection(config: QontoSourceConfig) -> None:
+ with patch("requests.Session.send") as send:
+ assert validate_credentials(config, "v2", None) == (False, AUTH_ERROR)
+ send.assert_not_called()
+
+
[email protected]("status", [429, 500])
+def test_credential_validation_propagates_transient_errors(status: int) -> None:
+ with patch("requests.Session.send", return_value=response({}, status)), pytest.raises(HTTPError):
+ validate_credentials(CONFIG, "v2", None)
+
+
[email protected](("status", "message"), [(401, AUTH_ERROR), (403, PERMISSION_ERROR)])
+def test_sync_auth_errors_are_terminal(status: int, message: str) -> None:
+ with patch(
+ "requests.Session.send",
+ return_value=response({"errors": [{"code": "unauthorized", "detail": "Invalid credentials"}]}, status),
+ ) as send:
+ with pytest.raises(HTTPError) as error:
+ list(cast(Iterable[Any], source("labels", manager()).items()))
+ assert send.call_count == 1
+ matches = [value for key, value in QontoSource().get_non_retryable_errors().items() if key in str(error.value)]
+ assert matches == [message]
+
+
[email protected]("status", [429, 500])
+def test_sync_transient_errors_remain_retryable(status: int) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.DEFAULT_RETRY_ATTEMPTS", 1
+ ):
+ with patch("requests.Session.send", return_value=response({}, status)):
+ with pytest.raises(RESTClientRetryableError) as error:
+ list(cast(Iterable[Any], source("labels", manager()).items()))
+ assert not any(key in str(error.value) for key in QontoSource().get_non_retryable_errors())
+
+
+ ("endpoint", "last_value", "message"),
+ [("missing", None, "Unknown Qonto table"), ("transfers", "invalid", "Invalid Qonto incremental timestamp")],
+)
+def test_invalid_inputs_fail_before_requests(endpoint: str, last_value: str | None, message: str) -> None:
+ with patch("requests.Session.send") as send, pytest.raises(ValueError, match=message):
+ source(endpoint, manager(), True, last_value)
+ send.assert_not_called()