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(warehouse_sources): support codemagic API version v3 (#113235)

Tom Owers0c3d4ef2bc42
diff --git a/.agents/skills/warehouse-source-new-version/SKILL.md b/.agents/skills/warehouse-source-new-version/SKILL.md
index b1fc20c87b25..a9de6c366654 100644
--- a/.agents/skills/warehouse-source-new-version/SKILL.md
+++ b/.agents/skills/warehouse-source-new-version/SKILL.md
@@ -109,6 +109,7 @@ The opposite gap also occurs: a reference rendered from one version-blind OpenAP
- When the vendor renames a collection between versions, keep the schema/table name set identical across versions and put the rename in a per-version path on the endpoint config — otherwise discovery diffs orphan the table on repin.
- When the new version has no equivalent for an old endpoint (a dropped collection, not a rename), keep that table only on the versions that serve it and let the table set differ by version — never map it to a guessed path just to keep the sets equal, since docs are the sole source of truth and an unverified path makes a new source surface a table that 404s at sync time.
- A source with no dispatch may currently read its version from a constant on a shared model (e.g. the OAuth `Integration` model) that also drives version-independent flows like OAuth token minting. Repoint only the sync request path onto the resolved pin; leave that constant, since bumping it changes those other flows' version with a blast radius beyond this source.
+- A collection the new version serves only under a parent scope (per team, workspace, or project) instead of account-wide is not a dropped table: keep the table and fan out over the version's parent list endpoint, which the token can also read.
- The opposite holds when the new version is a genuinely different vendor product rather than a renamed collection (the old and new labels serve different endpoints and tables): give the new version its own disjoint table set, don't force the old names onto it. That divergence is safe only because sources are never repinned — so a 2.5→3.0-style move is lossy, and its migration is documented-not-scripted, exactly like a rename that changes primary keys.
- The shared REST framework only binds a resolved parent field into a child resource's URL **path**, not its query string (`_bind_path_params` raises "Resolve query params not supported yet"). If a new version scopes a fan-out child by a query param where the old version used a path segment, the dependent-resource `{"type": "resolve"}` machinery can't express it — iterate the parent ids explicitly in the source and bake each id into the child's params (or POST body) instead.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/canonical_descriptions.py
index d98ad8b555db..429d8622d9e5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/canonical_descriptions.py
@@ -5,6 +5,7 @@ build object shape confirmed via a live response shared in
https://github.com/orgs/codemagic-ci-cd/discussions/1941 (GET /builds is not itself documented —
see the comment on `ENDPOINTS["Builds"]` in `settings.py`). Keyed by the resource names in
`settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced Codemagic table.
+The snake_case columns are the v3 API's field names, from https://codemagic.io/api/v3/schema.
Columns absent here fall back to LLM enrichment.
"""
@@ -22,6 +23,11 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"branches": "Branches available on the application's repository.",
"workflowIds": "Identifiers of the Workflow Editor workflows configured for this application.",
"workflows": "Workflow Editor workflows configured for this application, keyed by workflow id.",
+ "id": "Unique identifier for the application.",
+ "name": "Name of the application.",
+ "icon_url": "URL of the application's icon, or null if none is set.",
+ "last_build_id": "Identifier of the application's most recent build, or null if it has never been built.",
+ "archived": "Whether the application is archived.",
},
},
"Builds": {
@@ -45,6 +51,17 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"config": "Workflow configuration snapshot used for the build.",
"artefacts": "Build artifacts produced by the build (e.g. app binaries), if any.",
"labels": "Labels attached to the build.",
+ "id": "Unique identifier for the build.",
+ "app_id": "Identifier of the application this build ran for.",
+ "workflow": "Workflow the build ran, with its id, name, and source (codemagic.yaml file or Workflow Editor).",
+ "artifacts": "Build artifacts produced by the build (e.g. app binaries), if any.",
+ "release_notes": "Release notes attached to the build, one entry per language.",
+ "created_at": "Time the build was created (queued).",
+ "tag": "Git tag the build ran against, if any.",
+ "pull_request": "Pull request the build ran for, if any.",
+ "app_store_connect_status": "App Store Connect processing status for the build, if it was published there.",
+ "started_at": "Time the build started running, or null if it never started.",
+ "finished_at": "Time the build finished, or null while still running.",
},
},
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/codemagic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/codemagic.py
index 3ff84056ecb4..b777f5ab5cfa 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/codemagic.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/codemagic.py
@@ -3,24 +3,45 @@ from typing import Any, Optional
from requests import Request, Response
-from products.warehouse_sources.backend.temporal.data_imports.sources.codemagic.settings import BASE_URL, ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.codemagic.settings import (
+ BASE_URL,
+ CODEMAGIC_V1,
+ CODEMAGIC_V3,
+ ENDPOINTS,
+ V3_BASE_URL,
+ V3_ENDPOINTS,
+ V3_PAGE_SIZE,
+ V3_TEAMS_PATH,
+)
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 (
RESTAPIConfig,
rest_api_resource,
+ rest_api_resources,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
BasePaginator,
+ JSONResponseCursorPaginator,
+ PageNumberPaginator,
SinglePagePaginator,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ EndpointResource,
+)
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
[email protected](frozen=True)
class CodemagicResumeConfig:
- skip: int
+ # v1 Builds: offset of the next page.
+ skip: Optional[int] = None
+ # v3 Builds fan out per team: team build paths already synced, the one in progress, and its
+ # cursor paginator state.
+ completed: Optional[list[str]] = None
+ current: Optional[str] = None
+ child_state: Optional[dict[str, Any]] = None
class CodemagicBuildsPaginator(BasePaginator):
@@ -84,6 +105,21 @@ def codemagic_source(
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[CodemagicResumeConfig],
+ api_version: str,
+) -> SourceResponse:
+ if api_version == CODEMAGIC_V1:
+ return _v1_source(api_token, endpoint, team_id, job_id, resumable_source_manager)
+ if api_version == CODEMAGIC_V3:
+ return _v3_source(api_token, endpoint, team_id, job_id, resumable_source_manager)
+ raise ValueError(f"Unsupported Codemagic API version: {api_version}")
+
+
+def _v1_source(
+ api_token: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[CodemagicResumeConfig],
) -> SourceResponse:
endpoint_config = ENDPOINTS[endpoint]
is_builds = endpoint == "Builds"
@@ -112,7 +148,7 @@ def codemagic_source(
initial_paginator_state: Optional[dict[str, Any]] = None
if is_builds and resumable_source_manager.can_resume():
resume_config = resumable_source_manager.load_state()
- if resume_config is not None:
+ if resume_config is not None and resume_config.skip is not None:
initial_paginator_state = {"skip": resume_config.skip}
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
@@ -146,9 +182,139 @@ def codemagic_source(
)
-def validate_credentials(api_token: str) -> tuple[bool, str | None]:
+def _v3_client_config(api_token: str) -> ClientConfig:
+ return {
+ "base_url": V3_BASE_URL,
+ "auth": {
+ "type": "api_key",
+ "api_key": api_token,
+ "name": "x-auth-token",
+ "location": "header",
+ },
+ "allow_redirects": False,
+ }
+
+
+def _v3_page_number_paginator() -> PageNumberPaginator:
+ return PageNumberPaginator(base_page=1, total_path="total_pages")
+
+
+def _v3_source(
+ api_token: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[CodemagicResumeConfig],
+) -> SourceResponse:
+ endpoint_config = V3_ENDPOINTS[endpoint]
+ table_name = endpoint_config.name.lower()
+ is_builds = endpoint == "Builds"
+
+ if not is_builds:
+ resource = rest_api_resource(
+ {
+ "client": _v3_client_config(api_token),
+ "resources": [
+ {
+ "name": table_name,
+ "table_name": table_name,
+ "write_disposition": "replace",
+ "endpoint": {
+ "path": endpoint_config.path,
+ "params": {"page_size": V3_PAGE_SIZE},
+ "data_selector": endpoint_config.data_selector,
+ "paginator": _v3_page_number_paginator(),
+ },
+ "table_format": "delta",
+ }
+ ],
+ },
+ team_id,
+ job_id,
+ db_incremental_field_last_value=None,
+ )
+ else:
+ initial_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None and (resume_config.completed or resume_config.current):
+ initial_state = {
+ "completed": resume_config.completed or [],
+ "current": resume_config.current,
+ "child_state": resume_config.child_state,
+ }
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(
+ CodemagicResumeConfig(
+ completed=state.get("completed"),
+ current=state.get("current"),
+ child_state=state.get("child_state"),
+ )
+ )
+
+ resources = rest_api_resources(
+ {
+ "client": _v3_client_config(api_token),
+ "resources": [
+ {
+ "name": "teams",
+ "endpoint": {
+ "path": V3_TEAMS_PATH,
+ "params": {"page_size": V3_PAGE_SIZE},
+ "data_selector": "data",
+ "paginator": _v3_page_number_paginator(),
+ },
+ },
+ {
+ "name": table_name,
+ "table_name": table_name,
+ "write_disposition": "replace",
+ "endpoint": {
+ "path": endpoint_config.path,
+ "params": {
+ "team_id": {"type": "resolve", "resource": "teams", "field": "id"},
+ "page_size": V3_PAGE_SIZE,
+ },
+ "data_selector": endpoint_config.data_selector,
+ "paginator": JSONResponseCursorPaginator(
+ cursor_path="cursor", cursor_param="cursor", raise_on_repeated_cursor=True
+ ),
+ },
+ "table_format": "delta",
+ },
+ ],
+ },
+ team_id,
+ job_id,
+ db_incremental_field_last_value=None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_state,
+ )
+ resource = next(r for r in resources if getattr(r, "name", None) == table_name)
+
+ return SourceResponse(
+ name=table_name,
+ items=lambda: resource,
+ primary_keys=["id"],
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="week" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
+
+
+def validate_credentials(api_token: str, api_version: str) -> tuple[bool, str | None]:
+ if api_version == CODEMAGIC_V1:
+ url = f"{BASE_URL}/apps"
+ elif api_version == CODEMAGIC_V3:
+ url = f"{V3_BASE_URL}{V3_ENDPOINTS['Applications'].path}"
+ else:
+ raise ValueError(f"Unsupported Codemagic API version: {api_version}")
response = make_tracked_session(redact_values=(api_token,), allow_redirects=False).get(
- f"{BASE_URL}/apps",
+ url,
headers={"x-auth-token": api_token},
)
if response.status_code == 200:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/settings.py
index 7da822e205bf..79339484f5c9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/settings.py
@@ -3,7 +3,18 @@ from typing import Optional
from products.warehouse_sources.backend.types import IncrementalField
+CODEMAGIC_V1 = "v1"
+CODEMAGIC_V3 = "v3"
+SUPPORTED_VERSIONS = (CODEMAGIC_V1, CODEMAGIC_V3)
+DEFAULT_VERSION = CODEMAGIC_V3
+
BASE_URL = "https://api.codemagic.io"
+# v3 is served from the main host under /api/v3, not from the legacy api. subdomain.
+V3_BASE_URL = "https://codemagic.io"
+V3_PAGE_SIZE = 100
+# v3 has no account-wide build list, only GET /teams/{team_id}/builds, so builds fan out over
+# the teams the token's user belongs to.
+V3_TEAMS_PATH = "/api/v3/user/teams"
@dataclass
@@ -39,6 +50,20 @@ ENDPOINTS: dict[str, CodemagicEndpointConfig] = {
),
}
+V3_ENDPOINTS: dict[str, CodemagicEndpointConfig] = {
+ "Applications": CodemagicEndpointConfig(
+ name="Applications",
+ path="/api/v3/user/apps",
+ data_selector="data",
+ ),
+ "Builds": CodemagicEndpointConfig(
+ name="Builds",
+ path="/api/v3/teams/{team_id}/builds",
+ data_selector="data",
+ partition_key="created_at",
+ ),
+}
+
# Neither endpoint exposes a server-side created/updated-since filter — GET /builds has no
# documented timestamp filter param, only the `skip` offset — so both tables are full refresh only.
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/source.py
index c68e9ee383c5..4164e1a8fd74 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/source.py
@@ -13,8 +13,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.codemagic.
validate_credentials as validate_codemagic_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.codemagic.settings import (
+ DEFAULT_VERSION,
ENDPOINTS,
INCREMENTAL_FIELDS,
+ SUPPORTED_VERSIONS,
)
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 (
@@ -37,6 +39,8 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
class CodemagicSource(ResumableSource[CodemagicSourceConfig, CodemagicResumeConfig]):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
api_docs_url = "https://docs.codemagic.io/rest-api/codemagic-rest-api/"
+ supported_versions = SUPPORTED_VERSIONS
+ default_version = DEFAULT_VERSION
@property
def source_type(self) -> ExternalDataSourceType:
@@ -106,7 +110,7 @@ Supported tables:
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
- return validate_codemagic_credentials(config.api_token)
+ return validate_codemagic_credentials(config.api_token, self.resolve_api_version(api_version))
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CodemagicResumeConfig]:
return ResumableSourceManager[CodemagicResumeConfig](inputs, CodemagicResumeConfig)
@@ -123,4 +127,5 @@ Supported tables:
team_id=inputs.team_id,
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
+ api_version=self.resolve_api_version(inputs.api_version),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/tests/test_codemagic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/tests/test_codemagic.py
index a8e643e93bf0..94685928c338 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/tests/test_codemagic.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/tests/test_codemagic.py
@@ -13,6 +13,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.codemagic.
codemagic_source,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.codemagic.settings import (
+ CODEMAGIC_V1,
+ CODEMAGIC_V3,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -109,7 +113,7 @@ def _make_http_response(body: Any, status_code: int = 200) -> Response:
class TestCodemagicSourceResumeBehavior:
- """End-to-end resume behaviour of ``codemagic_source`` via ``rest_api_resource``."""
+ """End-to-end resume behaviour of the v1 ``codemagic_source`` via ``rest_api_resource``."""
def _drive(
self, endpoint: str, manager: MagicMock, responses: list[Response]
@@ -135,6 +139,7 @@ class TestCodemagicSourceResumeBehavior:
team_id=123,
job_id="test_job",
resumable_source_manager=manager,
+ api_version=CODEMAGIC_V1,
)
list(cast(Iterable[Any], response.items()))
return mock_session, sent_params
@@ -167,6 +172,7 @@ class TestCodemagicSourceResumeBehavior:
team_id=123,
job_id="test_job",
resumable_source_manager=manager,
+ api_version=CODEMAGIC_V1,
)
list(cast(Iterable[Any], response.items()))
@@ -259,6 +265,7 @@ class TestCodemagicSourceResumeBehavior:
team_id=123,
job_id="test_job",
resumable_source_manager=manager,
+ api_version=CODEMAGIC_V1,
)
assert response.sort_mode == expected_sort_mode
@@ -282,6 +289,7 @@ class TestCodemagicSourceResumeBehavior:
team_id=123,
job_id="test_job",
resumable_source_manager=manager,
+ api_version=CODEMAGIC_V1,
)
assert response.partition_mode == "datetime"
@@ -305,12 +313,129 @@ class TestCodemagicSourceResumeBehavior:
team_id=123,
job_id="test_job",
resumable_source_manager=manager,
+ api_version=CODEMAGIC_V1,
)
assert response.partition_mode is None
assert response.partition_keys is None
+class TestCodemagicV3Source:
+ def _drive(
+ self, endpoint: str, manager: MagicMock, responses: dict[str, list[Response]]
+ ) -> tuple[Any, list[dict[str, Any]], list[tuple[str, dict[str, Any]]]]:
+ sent: list[tuple[str, dict[str, Any]]] = []
+ queues = {path: iter(rs) for path, rs in responses.items()}
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent.append((request.url, dict(request.params or {})))
+ return next(queues[request.url])
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ response = codemagic_source(
+ api_token="test-token",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ api_version=CODEMAGIC_V3,
+ )
+ rows = [row for page in cast(Iterable[Any], response.items()) for row in page]
+ return response, rows, sent
+
+ def test_applications_page_through_user_apps(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ url = "https://codemagic.io/api/v3/user/apps"
+ responses = {
+ url: [
+ _make_http_response({"data": [{"id": "a1"}], "page_size": 100, "current_page": 1, "total_pages": 2}),
+ _make_http_response({"data": [{"id": "a2"}], "page_size": 100, "current_page": 2, "total_pages": 2}),
+ ]
+ }
+
+ response, rows, sent = self._drive("Applications", manager, responses)
+
+ assert [r["id"] for r in rows] == ["a1", "a2"]
+ assert sent == [(url, {"page_size": 100, "page": 1}), (url, {"page_size": 100, "page": 2})]
+ assert response.primary_keys == ["id"]
+ assert response.partition_keys is None
+
+ def test_builds_fan_out_over_teams_and_follow_cursor(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ teams_url = "https://codemagic.io/api/v3/user/teams"
+ t1_url = "https://codemagic.io/api/v3/teams/t1/builds"
+ t2_url = "https://codemagic.io/api/v3/teams/t2/builds"
+ responses = {
+ teams_url: [
+ _make_http_response(
+ {"data": [{"id": "t1"}, {"id": "t2"}], "page_size": 100, "current_page": 1, "total_pages": 1}
+ )
+ ],
+ t1_url: [
+ _make_http_response({"data": [{"id": "b1"}], "page_size": 100, "cursor": "b1"}),
+ _make_http_response({"data": [{"id": "b2"}], "page_size": 100, "cursor": None}),
+ ],
+ t2_url: [_make_http_response({"data": [{"id": "b3"}], "page_size": 100, "cursor": None})],
+ }
+
+ response, rows, sent = self._drive("Builds", manager, responses)
+
+ assert [r["id"] for r in rows] == ["b1", "b2", "b3"]
+ assert sent == [
+ (teams_url, {"page_size": 100, "page": 1}),
+ (t1_url, {"page_size": 100}),
+ (t1_url, {"page_size": 100, "cursor": "b1"}),
+ (t2_url, {"page_size": 100}),
+ ]
+ assert manager.save_state.call_args_list[0].args[0] == CodemagicResumeConfig(
+ completed=[], current="/api/v3/teams/t1/builds", child_state={"cursor": "b1"}
+ )
+ assert response.primary_keys == ["id"]
+ assert response.partition_keys == ["created_at"]
+
+ def test_builds_resume_skips_completed_teams_and_seeds_cursor(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = CodemagicResumeConfig(
+ completed=["/api/v3/teams/t1/builds"], current="/api/v3/teams/t2/builds", child_state={"cursor": "b9"}
+ )
+ teams_url = "https://codemagic.io/api/v3/user/teams"
+ t2_url = "https://codemagic.io/api/v3/teams/t2/builds"
+ responses = {
+ teams_url: [
+ _make_http_response(
+ {"data": [{"id": "t1"}, {"id": "t2"}], "page_size": 100, "current_page": 1, "total_pages": 1}
+ )
+ ],
+ t2_url: [_make_http_response({"data": [{"id": "b10"}], "page_size": 100, "cursor": None})],
+ }
+
+ _, rows, sent = self._drive("Builds", manager, responses)
+
+ assert [r["id"] for r in rows] == ["b10"]
+ assert sent[1:] == [(t2_url, {"page_size": 100, "cursor": "b9"})]
+
+ def test_unknown_version_is_rejected(self) -> None:
+ with pytest.raises(ValueError, match="Unsupported Codemagic API version"):
+ codemagic_source(
+ api_token="test-token",
+ endpoint="Builds",
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=MagicMock(spec=ResumableSourceManager),
+ api_version="v2",
+ )
+
+
class TestValidateCredentials:
@pytest.mark.parametrize(
("status_code", "expected_valid"),
@@ -328,13 +453,22 @@ class TestValidateCredentials:
mock_session.get.return_value = MagicMock(status_code=status_code)
mock_make_session.return_value = mock_session
- is_valid, error = validate_credentials("test-token")
+ is_valid, error = validate_credentials("test-token", CODEMAGIC_V3)
assert is_valid is expected_valid
if not expected_valid:
assert error == "Invalid Codemagic API token"
- def test_validate_credentials_sends_auth_header_and_redacts_token(self) -> None:
+ @pytest.mark.parametrize(
+ ("api_version", "expected_url"),
+ [
+ (CODEMAGIC_V1, "https://api.codemagic.io/apps"),
+ (CODEMAGIC_V3, "https://codemagic.io/api/v3/user/apps"),
+ ],
+ )
+ def test_validate_credentials_sends_auth_header_and_redacts_token(
+ self, api_version: str, expected_url: str
+ ) -> None:
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.codemagic.codemagic.make_tracked_session"
) as mock_make_session:
@@ -342,10 +476,8 @@ class TestValidateCredentials:
mock_session.get.return_value = MagicMock(status_code=200)
mock_make_session.return_value = mock_session
- validate_credentials("secret-token")
+ validate_credentials("secret-token", api_version)
# allow_redirects=False keeps the custom-header token from following a 3xx off-host.
mock_make_session.assert_called_once_with(redact_values=("secret-token",), allow_redirects=False)
- mock_session.get.assert_called_once_with(
- "https://api.codemagic.io/apps", headers={"x-auth-token": "secret-token"}
- )
+ mock_session.get.assert_called_once_with(expected_url, headers={"x-auth-token": "secret-token"})
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/tests/test_codemagic_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/tests/test_codemagic_source.py
index 6684dfc816c2..8adc7a1cda4e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/tests/test_codemagic_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codemagic/tests/test_codemagic_source.py
@@ -1,4 +1,5 @@
import pytest
+from unittest.mock import MagicMock, patch
from products.warehouse_sources.backend.temporal.data_imports.sources.codemagic.source import CodemagicSource
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.codemagic import (
@@ -35,3 +36,24 @@ class TestCodemagicSource:
matched = next((msg for key, msg in non_retryable.items() if key in error_message), None)
assert matched is not None
assert expected_substring in matched
+
+ @pytest.mark.parametrize(
+ ("pinned_version", "expected_version"),
+ [
+ (None, "v3"),
+ ("v1", "v1"),
+ ("v3", "v3"),
+ ],
+ )
+ def test_pinned_version_reaches_request_layer(self, pinned_version: str | None, expected_version: str) -> None:
+ module = "products.warehouse_sources.backend.temporal.data_imports.sources.codemagic.source"
+ with (
+ patch(f"{module}.validate_codemagic_credentials", return_value=(True, None)) as mock_validate,
+ patch(f"{module}.codemagic_source") as mock_source,
+ ):
+ self.source.validate_credentials(self.config, self.team_id, api_version=pinned_version)
+ inputs = MagicMock(api_version=self.source.resolve_api_version(pinned_version), schema_name="Builds")
+ self.source.source_for_pipeline(self.config, MagicMock(), inputs)
+
+ mock_validate.assert_called_once_with("test-token", expected_version)
+ assert mock_source.call_args.kwargs["api_version"] == expected_version