From f5885abf3a41a1b9ff2f6ef9a76fb06119527b4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mehmet=20Karao=C4=9Flu?= Date: Mon, 30 Nov 2026 21:17:46 +0300 Subject: [PATCH 1/2] feat: add AsyncClient with identical API surface --- src/triggerdev/__init__.py | 2 + src/triggerdev/_async_client.py | 55 +++++++ src/triggerdev/_base_client.py | 210 ++++++++++++++++++++++++ src/triggerdev/resources/__init__.py | 9 +- src/triggerdev/resources/runs.py | 203 ++++++++++++++++++++++- src/triggerdev/resources/schedules.py | 116 ++++++++++++- src/triggerdev/resources/tasks.py | 53 +++++- tests/test_async_client.py | 162 ++++++++++++++++++ tests/test_async_resources_runs.py | 193 ++++++++++++++++++++++ tests/test_async_resources_schedules.py | 133 +++++++++++++++ tests/test_async_resources_tasks.py | 92 +++++++++++ 11 files changed, 1222 insertions(+), 6 deletions(-) create mode 100644 src/triggerdev/_async_client.py create mode 100644 tests/test_async_client.py create mode 100644 tests/test_async_resources_runs.py create mode 100644 tests/test_async_resources_schedules.py create mode 100644 tests/test_async_resources_tasks.py diff --git a/src/triggerdev/__init__.py b/src/triggerdev/__init__.py index aebb178..a6f15a6 100644 --- a/src/triggerdev/__init__.py +++ b/src/triggerdev/__init__.py @@ -1,5 +1,6 @@ """The first fully typed Python SDK for the Trigger.dev management API.""" +from triggerdev._async_client import AsyncClient from triggerdev._client import Client from triggerdev._exceptions import ( APIConnectionError, @@ -26,6 +27,7 @@ "APIError", "APIStatusError", "APITimeoutError", + "AsyncClient", "AuthenticationError", "BadRequestError", "Client", diff --git a/src/triggerdev/_async_client.py b/src/triggerdev/_async_client.py new file mode 100644 index 0000000..02d44fe --- /dev/null +++ b/src/triggerdev/_async_client.py @@ -0,0 +1,55 @@ +"""Trigger.dev async client.""" + +from __future__ import annotations + +from functools import cached_property +from typing import TYPE_CHECKING + +from triggerdev._base_client import AsyncBaseClient +from triggerdev.resources.runs import AsyncRuns +from triggerdev.resources.schedules import AsyncSchedules +from triggerdev.resources.tasks import AsyncTasks + +if TYPE_CHECKING: + import httpx2 + + +class AsyncClient(AsyncBaseClient): + """Async client for the Trigger.dev management API.""" + + def __init__( + self, + *, + api_key: str | None = None, + base_url: str | None = None, + timeout: float | httpx2.Timeout | None = None, + max_retries: int | None = None, + http_client: httpx2.AsyncClient | None = None, + default_headers: dict[str, str] | None = None, + ) -> None: + super().__init__( + api_key=api_key, + base_url=base_url, + timeout=timeout, + max_retries=max_retries, + http_client=http_client, + default_headers=default_headers, + ) + + @cached_property + def tasks(self) -> AsyncTasks: + return AsyncTasks(self) + + @cached_property + def runs(self) -> AsyncRuns: + return AsyncRuns(self) + + @cached_property + def schedules(self) -> AsyncSchedules: + return AsyncSchedules(self) + + async def __aenter__(self) -> AsyncClient: + return self + + async def __aexit__(self, *_args: object) -> None: + await self.aclose() diff --git a/src/triggerdev/_base_client.py b/src/triggerdev/_base_client.py index b12630f..e102a15 100644 --- a/src/triggerdev/_base_client.py +++ b/src/triggerdev/_base_client.py @@ -218,6 +218,157 @@ def __exit__(self, *_args: object) -> None: self.close() +class AsyncBaseClient: + """Shared async HTTP client logic for the Trigger.dev API.""" + + api_key: str + base_url: str + timeout: httpx2.Timeout + max_retries: int + + _client: httpx2.AsyncClient + _owns_client: bool + + def __init__( + self, + *, + api_key: str | None = None, + base_url: str | None = None, + timeout: float | httpx2.Timeout | None = None, + max_retries: int | None = None, + http_client: httpx2.AsyncClient | None = None, + default_headers: dict[str, str] | None = None, + ) -> None: + resolved_key = api_key or os.environ.get("TRIGGER_SECRET_KEY") + if not resolved_key: + raise TriggerDevError( + "The API key must be provided as the `api_key` argument or the TRIGGER_SECRET_KEY environment variable." + ) + self.api_key = resolved_key + + resolved_url = base_url or os.environ.get("TRIGGER_DEV_BASE_URL", DEFAULT_BASE_URL) + self.base_url = resolved_url.rstrip("/") + + if timeout is None: + self.timeout = DEFAULT_TIMEOUT + elif isinstance(timeout, (int, float)): + self.timeout = httpx2.Timeout(float(timeout)) + else: + self.timeout = timeout + + self.max_retries = max_retries if max_retries is not None else DEFAULT_MAX_RETRIES + + self._default_headers = default_headers or {} + + if http_client is not None: + self._client = http_client + self._owns_client = False + else: + self._client = httpx2.AsyncClient(timeout=self.timeout) + self._owns_client = True + + @overload + async def _request( + self, + method: str, + path: str, + *, + cast_to: type[_ModelT], + body: dict[str, Any] | None = ..., + params: dict[str, Any] | None = ..., + auth_required: bool = ..., + ) -> _ModelT: ... + + @overload + async def _request( + self, + method: str, + path: str, + *, + cast_to: None, + body: dict[str, Any] | None = ..., + params: dict[str, Any] | None = ..., + auth_required: bool = ..., + ) -> None: ... + + @overload + async def _request( + self, + method: str, + path: str, + *, + cast_to: _SentinelType, + body: dict[str, Any] | None = ..., + params: dict[str, Any] | None = ..., + auth_required: bool = ..., + ) -> dict[str, Any]: ... + + async def _request( + self, + method: str, + path: str, + *, + cast_to: type[_ModelT] | _SentinelType | None = None, + body: dict[str, Any] | None = None, + params: dict[str, Any] | None = None, + auth_required: bool = True, + ) -> _ModelT | dict[str, Any] | None: + url = f"{self.base_url}{path}" + + headers: dict[str, str] = { + "accept": "application/json", + **self._default_headers, + } + if auth_required: + headers["authorization"] = f"Bearer {self.api_key}" + if body is not None: + headers["content-type"] = "application/json" + + try: + response = await self._client.request( + method, + url, + json=body, + params=params, + headers=headers, + ) + except httpx2.TimeoutException as exc: + raise APITimeoutError(request=httpx2.Request(method, url)) from exc + except httpx2.TransportError as exc: + raise APIConnectionError(request=httpx2.Request(method, url)) from exc + + if not response.is_success: + raise self._make_status_error(response) + + if cast_to is None: + return None + + data: dict[str, Any] = response.json() + + if isinstance(cast_to, _SentinelType): + return data + + return cast_to.model_validate(data) + + @staticmethod + def _make_status_error(response: httpx2.Response) -> APIStatusError: + return BaseClient._make_status_error(response) + + @property + def is_closed(self) -> bool: + return self._client.is_closed + + async def aclose(self) -> None: + if self._owns_client: + await self._client.aclose() + + async def __aenter__(self) -> AsyncBaseClient: + return self + + async def __aexit__(self, *_args: object) -> None: + await self.aclose() + + class SyncAPIResource: """Base for sync resource classes.""" @@ -275,3 +426,62 @@ def _request( body=body, params=params, ) + + +class AsyncAPIResource: + """Base for async resource classes.""" + + _client: AsyncBaseClient + + def __init__(self, client: AsyncBaseClient) -> None: + self._client = client + + @overload + async def _request( + self, + method: str, + path: str, + *, + cast_to: type[_ModelT], + body: dict[str, Any] | None = ..., + params: dict[str, Any] | None = ..., + ) -> _ModelT: ... + + @overload + async def _request( + self, + method: str, + path: str, + *, + cast_to: None, + body: dict[str, Any] | None = ..., + params: dict[str, Any] | None = ..., + ) -> None: ... + + @overload + async def _request( + self, + method: str, + path: str, + *, + cast_to: _SentinelType, + body: dict[str, Any] | None = ..., + params: dict[str, Any] | None = ..., + ) -> dict[str, Any]: ... + + async def _request( + self, + method: str, + path: str, + *, + cast_to: type[_ModelT] | _SentinelType | None = None, + body: dict[str, Any] | None = None, + params: dict[str, Any] | None = None, + ) -> _ModelT | dict[str, Any] | None: + return await self._client._request( # pyright: ignore[reportPrivateUsage] + method, + path, + cast_to=cast_to, + body=body, + params=params, + ) diff --git a/src/triggerdev/resources/__init__.py b/src/triggerdev/resources/__init__.py index fe7e4d9..582232d 100644 --- a/src/triggerdev/resources/__init__.py +++ b/src/triggerdev/resources/__init__.py @@ -1,10 +1,13 @@ """Trigger.dev API resource clients.""" -from triggerdev.resources.runs import Runs -from triggerdev.resources.schedules import Schedules -from triggerdev.resources.tasks import Tasks +from triggerdev.resources.runs import AsyncRuns, Runs +from triggerdev.resources.schedules import AsyncSchedules, Schedules +from triggerdev.resources.tasks import AsyncTasks, Tasks __all__ = [ + "AsyncRuns", + "AsyncSchedules", + "AsyncTasks", "Runs", "Schedules", "Tasks", diff --git a/src/triggerdev/resources/runs.py b/src/triggerdev/resources/runs.py index d1621d7..df1a3d0 100644 --- a/src/triggerdev/resources/runs.py +++ b/src/triggerdev/resources/runs.py @@ -5,7 +5,7 @@ from datetime import datetime from typing import TYPE_CHECKING, Any -from triggerdev._base_client import RAW, SyncAPIResource +from triggerdev._base_client import RAW, AsyncAPIResource, SyncAPIResource from triggerdev.types.runs import ( AddTagsResponse, CancelRunResponse, @@ -276,3 +276,204 @@ def add_tags( cast_to=AddTagsResponse, body={"tags": tag_list}, ) + + +class AsyncRuns(AsyncAPIResource): + """Async methods for managing runs.""" + + async def list( + self, + *, + status: _List[ListRunStatus] | None = None, + task_identifier: _List[str] | None = None, + version: _List[str] | None = None, + bulk_action: str | None = None, + schedule: str | None = None, + is_test: bool | None = None, + tag: _List[str] | None = None, + error: str | None = None, + created_at_from: str | datetime | None = None, + created_at_to: str | datetime | None = None, + created_at_period: str | None = None, + page_size: int | None = None, + cursor_after: str | None = None, + cursor_before: str | None = None, + ) -> ListRunsResult: + params = _build_runs_filter_params( + status=status, + task_identifier=task_identifier, + version=version, + bulk_action=bulk_action, + schedule=schedule, + is_test=is_test, + tag=tag, + error=error, + created_at_from=created_at_from, + created_at_to=created_at_to, + created_at_period=created_at_period, + page_size=page_size, + cursor_after=cursor_after, + cursor_before=cursor_before, + ) + return await self._request( + "GET", + "/api/v1/runs", + cast_to=ListRunsResult, + params=params or None, + ) + + async def retrieve(self, run_id: str) -> RetrieveRunResponse: + return await self._request( + "GET", + f"/api/v3/runs/{run_id}", + cast_to=RetrieveRunResponse, + ) + + async def result(self, run_id: str) -> RunResultResponse: + return await self._request( + "GET", + f"/api/v1/runs/{run_id}/result", + cast_to=RunResultResponse, + ) + + async def events(self, run_id: str) -> dict[str, Any]: + return await self._request( + "GET", + f"/api/v1/runs/{run_id}/events", + cast_to=RAW, + ) + + async def trace(self, run_id: str) -> dict[str, Any]: + return await self._request( + "GET", + f"/api/v1/runs/{run_id}/trace", + cast_to=RAW, + ) + + async def trace_paged( + self, + run_id: str, + *, + page_size: int | None = None, + page_after: str | None = None, + ) -> dict[str, Any]: + params: dict[str, Any] = {} + if page_size is not None: + params["page[size]"] = page_size + if page_after is not None: + params["page[after]"] = page_after + return await self._request( + "GET", + f"/api/v1/runs/{run_id}/trace", + cast_to=RAW, + params=params or None, + ) + + async def replay( + self, + run_id: str, + *, + payload: object | None = None, + payload_type: str | None = None, + metadata: dict[str, object] | None = None, + tags: RunTags | None = None, + queue: str | None = None, + concurrency_key: str | None = None, + machine: Machine | None = None, + version: str | None = None, + region: str | None = None, + delay: str | None = None, + ttl: TTL | None = None, + idempotency_key: str | None = None, + idempotency_key_ttl: str | None = None, + max_attempts: int | None = None, + max_duration: float | None = None, + priority: float | None = None, + ) -> ReplayRunResponse: + body: dict[str, Any] = {} + if payload is not None: + body["payload"] = payload + if payload_type is not None: + body["payloadType"] = payload_type + if metadata is not None: + body["metadata"] = metadata + if tags is not None: + body["tags"] = tags + if queue is not None: + body["queue"] = queue + if concurrency_key is not None: + body["concurrencyKey"] = concurrency_key + if machine is not None: + body["machine"] = machine + if version is not None: + body["version"] = version + if region is not None: + body["region"] = region + if delay is not None: + body["delay"] = delay + if ttl is not None: + body["ttl"] = ttl + if idempotency_key is not None: + body["idempotencyKey"] = idempotency_key + if idempotency_key_ttl is not None: + body["idempotencyKeyTTL"] = idempotency_key_ttl + if max_attempts is not None: + body["maxAttempts"] = max_attempts + if max_duration is not None: + body["maxDuration"] = max_duration + if priority is not None: + body["priority"] = priority + return await self._request( + "POST", + f"/api/v1/runs/{run_id}/replay", + cast_to=ReplayRunResponse, + body=body or None, + ) + + async def cancel(self, run_id: str) -> CancelRunResponse: + return await self._request( + "POST", + f"/api/v2/runs/{run_id}/cancel", + cast_to=CancelRunResponse, + ) + + async def reschedule( + self, + run_id: str, + *, + delay: str | datetime, + ) -> RetrieveRunResponse: + delay_val: str = delay.isoformat() if isinstance(delay, datetime) else delay + return await self._request( + "POST", + f"/api/v1/runs/{run_id}/reschedule", + cast_to=RetrieveRunResponse, + body={"delay": delay_val}, + ) + + async def update_metadata( + self, + run_id: str, + *, + metadata: dict[str, Any], + ) -> UpdateMetadataResponse: + return await self._request( + "PUT", + f"/api/v1/runs/{run_id}/metadata", + cast_to=UpdateMetadataResponse, + body={"metadata": metadata}, + ) + + async def add_tags( + self, + run_id: str, + *, + tags: _List[str] | str, + ) -> AddTagsResponse: + tag_list = [tags] if isinstance(tags, str) else tags + return await self._request( + "POST", + f"/api/v1/runs/{run_id}/tags", + cast_to=AddTagsResponse, + body={"tags": tag_list}, + ) diff --git a/src/triggerdev/resources/schedules.py b/src/triggerdev/resources/schedules.py index ae647f7..2c11dbc 100644 --- a/src/triggerdev/resources/schedules.py +++ b/src/triggerdev/resources/schedules.py @@ -4,7 +4,7 @@ from typing import Any -from triggerdev._base_client import SyncAPIResource +from triggerdev._base_client import AsyncAPIResource, SyncAPIResource from triggerdev.types.schedules import ( GetTimezonesResult, ListSchedulesResult, @@ -124,3 +124,117 @@ def timezones( cast_to=GetTimezonesResult, params=params or None, ) + + +class AsyncSchedules(AsyncAPIResource): + """Async methods for managing schedules.""" + + async def list( + self, + *, + page: int | None = None, + per_page: int | None = None, + ) -> ListSchedulesResult: + params: dict[str, Any] = {} + if page is not None: + params["page"] = page + if per_page is not None: + params["perPage"] = per_page + return await self._request( + "GET", + "/api/v1/schedules", + cast_to=ListSchedulesResult, + params=params or None, + ) + + async def create( + self, + *, + task: str, + cron: str, + deduplication_key: str, + external_id: str | None = None, + timezone: str | None = None, + ) -> ScheduleObject: + body: dict[str, Any] = { + "task": task, + "cron": cron, + "deduplicationKey": deduplication_key, + } + if external_id is not None: + body["externalId"] = external_id + if timezone is not None: + body["timezone"] = timezone + return await self._request( + "POST", + "/api/v1/schedules", + cast_to=ScheduleObject, + body=body, + ) + + async def retrieve(self, schedule_id: str) -> ScheduleObject: + return await self._request( + "GET", + f"/api/v1/schedules/{schedule_id}", + cast_to=ScheduleObject, + ) + + async def update( + self, + schedule_id: str, + *, + task: str, + cron: str, + external_id: str | None = None, + timezone: str | None = None, + ) -> ScheduleObject: + body: dict[str, Any] = { + "task": task, + "cron": cron, + } + if external_id is not None: + body["externalId"] = external_id + if timezone is not None: + body["timezone"] = timezone + return await self._request( + "PUT", + f"/api/v1/schedules/{schedule_id}", + cast_to=ScheduleObject, + body=body, + ) + + async def delete(self, schedule_id: str) -> None: + await self._request( + "DELETE", + f"/api/v1/schedules/{schedule_id}", + cast_to=None, + ) + + async def activate(self, schedule_id: str) -> ScheduleObject: + return await self._request( + "POST", + f"/api/v1/schedules/{schedule_id}/activate", + cast_to=ScheduleObject, + ) + + async def deactivate(self, schedule_id: str) -> ScheduleObject: + return await self._request( + "POST", + f"/api/v1/schedules/{schedule_id}/deactivate", + cast_to=ScheduleObject, + ) + + async def timezones( + self, + *, + exclude_utc: bool = False, + ) -> GetTimezonesResult: + params: dict[str, Any] = {} + if exclude_utc: + params["excludeUtc"] = "true" + return await self._request( + "GET", + "/api/v1/timezones", + cast_to=GetTimezonesResult, + params=params or None, + ) diff --git a/src/triggerdev/resources/tasks.py b/src/triggerdev/resources/tasks.py index e83f0be..5241a1c 100644 --- a/src/triggerdev/resources/tasks.py +++ b/src/triggerdev/resources/tasks.py @@ -4,7 +4,7 @@ from typing import Any -from triggerdev._base_client import SyncAPIResource +from triggerdev._base_client import AsyncAPIResource, SyncAPIResource from triggerdev.types.tasks import ( BatchTriggerTaskResponse, TriggerTaskResponse, @@ -60,3 +60,54 @@ def batch_trigger_multi( cast_to=BatchTriggerTaskResponse, body={"items": items}, ) + + +class AsyncTasks(AsyncAPIResource): + """Async methods for triggering and batch-triggering tasks.""" + + async def trigger( + self, + task_id: str, + *, + payload: object | None = None, + context: object | None = None, + options: dict[str, Any] | None = None, + ) -> TriggerTaskResponse: + body: dict[str, Any] = {} + if payload is not None: + body["payload"] = payload + if context is not None: + body["context"] = context + if options is not None: + body["options"] = options + return await self._request( + "POST", + f"/api/v1/tasks/{task_id}/trigger", + cast_to=TriggerTaskResponse, + body=body, + ) + + async def batch_trigger( + self, + task_id: str, + *, + items: list[dict[str, Any]], + ) -> BatchTriggerTaskResponse: + return await self._request( + "POST", + f"/api/v1/tasks/{task_id}/batch", + cast_to=BatchTriggerTaskResponse, + body={"items": items}, + ) + + async def batch_trigger_multi( + self, + *, + items: list[dict[str, Any]], + ) -> BatchTriggerTaskResponse: + return await self._request( + "POST", + "/api/v1/tasks/batch", + cast_to=BatchTriggerTaskResponse, + body={"items": items}, + ) diff --git a/tests/test_async_client.py b/tests/test_async_client.py new file mode 100644 index 0000000..4531062 --- /dev/null +++ b/tests/test_async_client.py @@ -0,0 +1,162 @@ +"""Tests for the AsyncClient class and AsyncBaseClient.""" + +from __future__ import annotations + +import os +from unittest.mock import patch + +import httpx2 +import pytest +import respx + +from triggerdev import AsyncClient +from triggerdev._exceptions import ( + APIConnectionError, + APITimeoutError, + AuthenticationError, + BadRequestError, + ConflictError, + ContentTooLargeError, + HTTPNotImplementedError, + InternalServerError, + NotFoundError, + PermissionDeniedError, + RateLimitError, + ServiceUnavailableError, + TriggerDevError, + UnprocessableEntityError, +) + + +class TestAsyncClientConstructor: + def test_api_key_from_param(self) -> None: + client = AsyncClient(api_key="tr_dev_sk_test") + assert client.api_key == "tr_dev_sk_test" + + def test_api_key_from_env(self) -> None: + with patch.dict(os.environ, {"TRIGGER_SECRET_KEY": "tr_dev_sk_env"}): + client = AsyncClient() + assert client.api_key == "tr_dev_sk_env" + + def test_api_key_missing_raises(self) -> None: + with patch.dict(os.environ, {}, clear=True), pytest.raises(TriggerDevError, match="API key"): + AsyncClient() + + def test_param_overrides_env(self) -> None: + with patch.dict(os.environ, {"TRIGGER_SECRET_KEY": "tr_dev_sk_env"}): + client = AsyncClient(api_key="tr_dev_sk_param") + assert client.api_key == "tr_dev_sk_param" + + def test_default_base_url(self) -> None: + client = AsyncClient(api_key="tr_dev_sk_test") + assert client.base_url == "https://api.trigger.dev" + + def test_custom_base_url(self) -> None: + client = AsyncClient(api_key="tr_dev_sk_test", base_url="https://custom.example.com") + assert client.base_url == "https://custom.example.com" + + def test_base_url_strips_trailing_slash(self) -> None: + client = AsyncClient(api_key="tr_dev_sk_test", base_url="https://custom.example.com/") + assert client.base_url == "https://custom.example.com" + + def test_default_timeout(self) -> None: + client = AsyncClient(api_key="tr_dev_sk_test") + assert client.timeout == httpx2.Timeout(60.0) + + def test_custom_timeout_float(self) -> None: + client = AsyncClient(api_key="tr_dev_sk_test", timeout=30.0) + assert client.timeout == httpx2.Timeout(30.0) + + def test_custom_timeout_object(self) -> None: + t = httpx2.Timeout(10.0, connect=5.0) + client = AsyncClient(api_key="tr_dev_sk_test", timeout=t) + assert client.timeout == t + + def test_resource_namespaces_exist(self) -> None: + client = AsyncClient(api_key="tr_dev_sk_test") + assert hasattr(client, "tasks") + assert hasattr(client, "runs") + assert hasattr(client, "schedules") + + +class TestAsyncClientContextManager: + async def test_async_context_manager(self) -> None: + async with AsyncClient(api_key="tr_dev_sk_test") as client: + assert not client.is_closed + assert client.is_closed + + async def test_aclose(self) -> None: + client = AsyncClient(api_key="tr_dev_sk_test") + assert not client.is_closed + await client.aclose() + assert client.is_closed + + async def test_custom_http_client_not_closed(self) -> None: + http_client = httpx2.AsyncClient() + client = AsyncClient(api_key="tr_dev_sk_test", http_client=http_client) + await client.aclose() + assert not http_client.is_closed + await http_client.aclose() + + +class TestAsyncClientAuth: + @respx.mock + async def test_auth_header_sent(self) -> None: + route = respx.get("https://api.trigger.dev/api/v1/timezones").mock( + return_value=httpx2.Response(200, json={"timezones": []}) + ) + async with AsyncClient(api_key="tr_dev_sk_test_1234") as client: + await client.schedules.timezones() + assert route.called + request = route.calls[0].request + assert request.headers["authorization"] == "Bearer tr_dev_sk_test_1234" + + +class TestAsyncErrorMapping: + @pytest.mark.parametrize( + ("status", "exc_cls"), + [ + (400, BadRequestError), + (401, AuthenticationError), + (403, PermissionDeniedError), + (404, NotFoundError), + (409, ConflictError), + (413, ContentTooLargeError), + (422, UnprocessableEntityError), + (429, RateLimitError), + (500, InternalServerError), + (501, HTTPNotImplementedError), + (503, ServiceUnavailableError), + ], + ) + @respx.mock + async def test_status_code_to_exception(self, status: int, exc_cls: type) -> None: + respx.get("https://api.trigger.dev/api/v3/runs/run_1234").mock( + return_value=httpx2.Response(status, json={"error": "test error"}) + ) + async with AsyncClient(api_key="tr_dev_sk_test_1234") as client: + with pytest.raises(exc_cls): + await client.runs.retrieve("run_1234") + + @respx.mock + async def test_connection_error(self) -> None: + respx.get("https://api.trigger.dev/api/v3/runs/run_1234").mock( + side_effect=httpx2.ConnectError("Connection refused") + ) + async with AsyncClient(api_key="tr_dev_sk_test_1234") as client: + with pytest.raises(APIConnectionError): + await client.runs.retrieve("run_1234") + + @respx.mock + async def test_timeout_error(self) -> None: + respx.get("https://api.trigger.dev/api/v3/runs/run_1234").mock(side_effect=httpx2.ReadTimeout("Read timed out")) + async with AsyncClient(api_key="tr_dev_sk_test_1234") as client: + with pytest.raises(APITimeoutError): + await client.runs.retrieve("run_1234") + + +class TestAsyncPublicReExports: + def test_async_client_importable_from_package(self) -> None: + import triggerdev + + assert hasattr(triggerdev, "AsyncClient") diff --git a/tests/test_async_resources_runs.py b/tests/test_async_resources_runs.py new file mode 100644 index 0000000..8d06183 --- /dev/null +++ b/tests/test_async_resources_runs.py @@ -0,0 +1,193 @@ +"""Tests for async Runs resource.""" + +from __future__ import annotations + +from typing import Any + +import httpx2 +import respx + +from triggerdev import AsyncClient +from triggerdev.types.runs import ListRunsResult, RetrieveRunResponse + +RETRIEVE_RUN_RESPONSE: dict[str, Any] = { + "id": "run_1234", + "status": "COMPLETED", + "taskIdentifier": "my-task", + "createdAt": "2024-01-01T00:00:00Z", + "updatedAt": "2024-01-01T00:01:00Z", + "isTest": False, + "attempts": [ + { + "id": "attempt_1", + "status": "COMPLETED", + "createdAt": "2024-01-01T00:00:00Z", + "updatedAt": "2024-01-01T00:01:00Z", + } + ], +} + + +class TestAsyncRunsList: + @respx.mock + async def test_list_basic(self) -> None: + route = respx.get("https://api.trigger.dev/api/v1/runs").mock( + return_value=httpx2.Response( + 200, + json={ + "data": [ + { + "id": "run_1", + "status": "COMPLETED", + "taskIdentifier": "t1", + "env": {"id": "env_1", "name": "dev"}, + "isTest": False, + "createdAt": "2024-01-01T00:00:00Z", + "updatedAt": "2024-01-01T00:01:00Z", + } + ], + "pagination": {"next": "run_2"}, + }, + ) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.runs.list() + assert isinstance(result, ListRunsResult) + assert result.data is not None + assert len(result.data) == 1 + assert result.data[0].id == "run_1" + assert route.called + + @respx.mock + async def test_list_with_filters(self) -> None: + route = respx.get("https://api.trigger.dev/api/v1/runs").mock( + return_value=httpx2.Response(200, json={"data": []}) + ) + async with AsyncClient(api_key="sk_test") as client: + await client.runs.list(status=["COMPLETED"], page_size=10) + assert route.called + url = str(route.calls[0].request.url) + assert "filter%5Bstatus%5D=COMPLETED" in url or "filter[status]=COMPLETED" in url + + +class TestAsyncRunsRetrieve: + @respx.mock + async def test_retrieve(self) -> None: + respx.get("https://api.trigger.dev/api/v3/runs/run_1234").mock( + return_value=httpx2.Response(200, json=RETRIEVE_RUN_RESPONSE) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.runs.retrieve("run_1234") + assert isinstance(result, RetrieveRunResponse) + assert result.id == "run_1234" + assert result.status == "COMPLETED" + + +class TestAsyncRunsResult: + @respx.mock + async def test_result(self) -> None: + respx.get("https://api.trigger.dev/api/v1/runs/run_1234/result").mock( + return_value=httpx2.Response( + 200, + json={ + "ok": True, + "id": "run_1234", + "output": '{"result": 42}', + "outputType": "application/json", + "taskIdentifier": "my-task", + "usage": {"durationMs": 150}, + }, + ) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.runs.result("run_1234") + assert result.ok is True + assert result.id == "run_1234" + assert result.output == '{"result": 42}' + + +class TestAsyncRunsEvents: + @respx.mock + async def test_events(self) -> None: + respx.get("https://api.trigger.dev/api/v1/runs/run_1234/events").mock( + return_value=httpx2.Response(200, json={"events": []}) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.runs.events("run_1234") + assert result == {"events": []} + + +class TestAsyncRunsTrace: + @respx.mock + async def test_trace(self) -> None: + respx.get("https://api.trigger.dev/api/v1/runs/run_1234/trace").mock( + return_value=httpx2.Response(200, json={"spans": []}) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.runs.trace("run_1234") + assert result == {"spans": []} + + @respx.mock + async def test_trace_paged(self) -> None: + respx.get("https://api.trigger.dev/api/v1/runs/run_1234/trace").mock( + return_value=httpx2.Response(200, json={"spans": [], "next": "cursor_abc"}) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.runs.trace_paged("run_1234", page_size=10) + assert result == {"spans": [], "next": "cursor_abc"} + + +class TestAsyncRunsReplay: + @respx.mock + async def test_replay(self) -> None: + respx.post("https://api.trigger.dev/api/v1/runs/run_1234/replay").mock( + return_value=httpx2.Response(200, json={"id": "run_5678"}) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.runs.replay("run_1234") + assert result.id == "run_5678" + + +class TestAsyncRunsCancel: + @respx.mock + async def test_cancel(self) -> None: + respx.post("https://api.trigger.dev/api/v2/runs/run_1234/cancel").mock( + return_value=httpx2.Response(200, json={"id": "run_1234"}) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.runs.cancel("run_1234") + assert result.id == "run_1234" + + +class TestAsyncRunsReschedule: + @respx.mock + async def test_reschedule(self) -> None: + respx.post("https://api.trigger.dev/api/v1/runs/run_1234/reschedule").mock( + return_value=httpx2.Response(200, json=RETRIEVE_RUN_RESPONSE) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.runs.reschedule("run_1234", delay="1h") + assert isinstance(result, RetrieveRunResponse) + assert result.id == "run_1234" + + +class TestAsyncRunsUpdateMetadata: + @respx.mock + async def test_update_metadata(self) -> None: + respx.put("https://api.trigger.dev/api/v1/runs/run_1234/metadata").mock( + return_value=httpx2.Response(200, json={"metadata": {"key": "val"}}) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.runs.update_metadata("run_1234", metadata={"key": "val"}) + assert result.metadata == {"key": "val"} + + +class TestAsyncRunsAddTags: + @respx.mock + async def test_add_tags(self) -> None: + respx.post("https://api.trigger.dev/api/v1/runs/run_1234/tags").mock( + return_value=httpx2.Response(200, json={"message": "Successfully set 2 new tags."}) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.runs.add_tags("run_1234", tags=["tag1", "tag2"]) + assert "Successfully" in result.message diff --git a/tests/test_async_resources_schedules.py b/tests/test_async_resources_schedules.py new file mode 100644 index 0000000..1335734 --- /dev/null +++ b/tests/test_async_resources_schedules.py @@ -0,0 +1,133 @@ +"""Tests for async Schedules resource.""" + +from __future__ import annotations + +from typing import Any + +import httpx2 +import respx + +from triggerdev import AsyncClient +from triggerdev.types.schedules import ( + GetTimezonesResult, + ListSchedulesResult, + ScheduleObject, +) + +SCHEDULE_JSON: dict[str, Any] = { + "id": "sched_1234", + "task": "my-task", + "type": "IMPERATIVE", + "active": True, + "deduplicationKey": "dedup_1", + "generator": {"type": "CRON", "expression": "0 0 * * *"}, + "timezone": "UTC", +} + + +class TestAsyncSchedulesList: + @respx.mock + async def test_list_basic(self) -> None: + route = respx.get("https://api.trigger.dev/api/v1/schedules").mock( + return_value=httpx2.Response( + 200, + json={"data": [SCHEDULE_JSON], "pagination": {"currentPage": 1, "totalPages": 1, "count": 1}}, + ) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.schedules.list() + assert isinstance(result, ListSchedulesResult) + assert result.data is not None + assert len(result.data) == 1 + assert result.data[0].id == "sched_1234" + assert route.called + + +class TestAsyncSchedulesCreate: + @respx.mock + async def test_create(self) -> None: + respx.post("https://api.trigger.dev/api/v1/schedules").mock( + return_value=httpx2.Response(200, json=SCHEDULE_JSON) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.schedules.create( + task="my-task", + cron="0 0 * * *", + deduplication_key="dedup_1", + timezone="UTC", + ) + assert isinstance(result, ScheduleObject) + assert result.id == "sched_1234" + + +class TestAsyncSchedulesRetrieve: + @respx.mock + async def test_retrieve(self) -> None: + respx.get("https://api.trigger.dev/api/v1/schedules/sched_1234").mock( + return_value=httpx2.Response(200, json=SCHEDULE_JSON) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.schedules.retrieve("sched_1234") + assert isinstance(result, ScheduleObject) + assert result.id == "sched_1234" + + +class TestAsyncSchedulesUpdate: + @respx.mock + async def test_update(self) -> None: + respx.put("https://api.trigger.dev/api/v1/schedules/sched_1234").mock( + return_value=httpx2.Response(200, json=SCHEDULE_JSON) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.schedules.update( + "sched_1234", + task="my-task", + cron="0 12 * * *", + ) + assert isinstance(result, ScheduleObject) + + +class TestAsyncSchedulesDelete: + @respx.mock + async def test_delete(self) -> None: + route = respx.delete("https://api.trigger.dev/api/v1/schedules/sched_1234").mock( + return_value=httpx2.Response(200) + ) + async with AsyncClient(api_key="sk_test") as client: + await client.schedules.delete("sched_1234") + assert route.called + + +class TestAsyncSchedulesActivateDeactivate: + @respx.mock + async def test_activate(self) -> None: + respx.post("https://api.trigger.dev/api/v1/schedules/sched_1234/activate").mock( + return_value=httpx2.Response(200, json={**SCHEDULE_JSON, "active": True}) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.schedules.activate("sched_1234") + assert isinstance(result, ScheduleObject) + assert result.active is True + + @respx.mock + async def test_deactivate(self) -> None: + respx.post("https://api.trigger.dev/api/v1/schedules/sched_1234/deactivate").mock( + return_value=httpx2.Response(200, json={**SCHEDULE_JSON, "active": False}) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.schedules.deactivate("sched_1234") + assert isinstance(result, ScheduleObject) + assert result.active is False + + +class TestAsyncSchedulesTimezones: + @respx.mock + async def test_timezones(self) -> None: + respx.get("https://api.trigger.dev/api/v1/timezones").mock( + return_value=httpx2.Response(200, json={"timezones": ["UTC", "America/New_York"]}) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.schedules.timezones() + assert isinstance(result, GetTimezonesResult) + assert result.timezones is not None + assert "UTC" in result.timezones diff --git a/tests/test_async_resources_tasks.py b/tests/test_async_resources_tasks.py new file mode 100644 index 0000000..1f6a209 --- /dev/null +++ b/tests/test_async_resources_tasks.py @@ -0,0 +1,92 @@ +"""Tests for async Tasks resource.""" + +from __future__ import annotations + +import json + +import httpx2 +import respx + +from triggerdev import AsyncClient +from triggerdev.types.tasks import BatchTriggerTaskResponse, TriggerTaskResponse + + +class TestAsyncTasksTrigger: + @respx.mock + async def test_trigger_basic(self) -> None: + route = respx.post("https://api.trigger.dev/api/v1/tasks/my-task/trigger").mock( + return_value=httpx2.Response(200, json={"id": "run_1234"}) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.tasks.trigger("my-task", payload={"message": "hello"}) + assert isinstance(result, TriggerTaskResponse) + assert result.id == "run_1234" + assert route.called + body = json.loads(route.calls[0].request.read()) + assert body["payload"] == {"message": "hello"} + + @respx.mock + async def test_trigger_with_options(self) -> None: + route = respx.post("https://api.trigger.dev/api/v1/tasks/my-task/trigger").mock( + return_value=httpx2.Response(200, json={"id": "run_5678"}) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.tasks.trigger( + "my-task", + payload={"data": 1}, + context={"user": "u1"}, + ) + assert result.id == "run_5678" + body = json.loads(route.calls[0].request.read()) + assert body["payload"] == {"data": 1} + assert body["context"] == {"user": "u1"} + + @respx.mock + async def test_trigger_empty_payload(self) -> None: + respx.post("https://api.trigger.dev/api/v1/tasks/my-task/trigger").mock( + return_value=httpx2.Response(200, json={"id": "run_0"}) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.tasks.trigger("my-task") + assert result.id == "run_0" + + +class TestAsyncTasksBatchTrigger: + @respx.mock + async def test_batch_trigger(self) -> None: + route = respx.post("https://api.trigger.dev/api/v1/tasks/my-task/batch").mock( + return_value=httpx2.Response( + 200, + json={"batchId": "batch_1", "runs": ["run_1", "run_2"]}, + ) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.tasks.batch_trigger( + "my-task", + items=[{"payload": {"n": 1}}, {"payload": {"n": 2}}], + ) + assert isinstance(result, BatchTriggerTaskResponse) + assert result.batch_id == "batch_1" + assert result.runs == ["run_1", "run_2"] + assert route.called + + +class TestAsyncTasksBatchTriggerMulti: + @respx.mock + async def test_batch_trigger_multi(self) -> None: + route = respx.post("https://api.trigger.dev/api/v1/tasks/batch").mock( + return_value=httpx2.Response( + 200, + json={"batchId": "batch_2", "runs": ["run_a", "run_b"]}, + ) + ) + async with AsyncClient(api_key="sk_test") as client: + result = await client.tasks.batch_trigger_multi( + items=[ + {"task": "task-a", "payload": {"n": 1}}, + {"task": "task-b", "payload": {"n": 2}}, + ], + ) + assert result.batch_id == "batch_2" + assert result.runs == ["run_a", "run_b"] + assert route.called From 3ee2bce07f50fe0ff88a636c547fe65a592878f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mehmet=20Karao=C4=9Flu?= Date: Mon, 30 Nov 2026 22:09:29 +0300 Subject: [PATCH 2/2] fix: suppress pyright reportPrivateUsage on shared static method --- src/triggerdev/_base_client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/triggerdev/_base_client.py b/src/triggerdev/_base_client.py index e102a15..51316ed 100644 --- a/src/triggerdev/_base_client.py +++ b/src/triggerdev/_base_client.py @@ -352,7 +352,7 @@ async def _request( @staticmethod def _make_status_error(response: httpx2.Response) -> APIStatusError: - return BaseClient._make_status_error(response) + return BaseClient._make_status_error(response) # pyright: ignore[reportPrivateUsage] @property def is_closed(self) -> bool: