Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ with Client() as client:
## Requirements

- Python 3.10+
- [httpx](https://www.python-httpx.org/) (installed automatically)
- [httpx2](https://github.com/pydantic/httpx2) (installed automatically)
- [pydantic](https://docs.pydantic.dev/) v2 (installed automatically)

## Contributing
Expand Down
8 changes: 6 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ classifiers = [
"Typing :: Typed",
]
dependencies = [
"httpx>=0.27.0",
"pydantic>=2.7.0",
"httpx2>=2.0.0,<3",
"pydantic>=2.7.0,<3",
]

[project.urls]
Expand Down Expand Up @@ -59,6 +59,8 @@ exclude = [
"/scripts",
"/spec",
"/tests",
"/.gitattributes",
"/.gitignore",
"uv.lock",
]

Expand Down Expand Up @@ -98,6 +100,8 @@ typeCheckingMode = "strict"
include = ["src"]

[tool.pytest.ini_options]
addopts = "-p tests._alias_httpx"
pythonpath = ["."]
testpaths = ["tests"]
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"
Expand Down
26 changes: 13 additions & 13 deletions src/triggerdev/_base_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import os
from typing import Any, TypeVar, cast, overload

import httpx
import httpx2
from pydantic import BaseModel

from triggerdev._exceptions import (
Expand All @@ -27,7 +27,7 @@
)

DEFAULT_BASE_URL = "https://api.trigger.dev"
DEFAULT_TIMEOUT = httpx.Timeout(60.0)
DEFAULT_TIMEOUT = httpx2.Timeout(60.0)
DEFAULT_MAX_RETRIES = 0

_ModelT = TypeVar("_ModelT", bound=BaseModel)
Expand All @@ -45,20 +45,20 @@ class BaseClient:

api_key: str
base_url: str
timeout: httpx.Timeout
timeout: httpx2.Timeout
max_retries: int

_client: httpx.Client
_client: httpx2.Client
_owns_client: bool

def __init__(
self,
*,
api_key: str | None = None,
base_url: str | None = None,
timeout: float | httpx.Timeout | None = None,
timeout: float | httpx2.Timeout | None = None,
max_retries: int | None = None,
http_client: httpx.Client | None = None,
http_client: httpx2.Client | None = None,
default_headers: dict[str, str] | None = None,
) -> None:
resolved_key = api_key or os.environ.get("TRIGGER_SECRET_KEY")
Expand All @@ -74,7 +74,7 @@ def __init__(
if timeout is None:
self.timeout = DEFAULT_TIMEOUT
elif isinstance(timeout, (int, float)):
self.timeout = httpx.Timeout(float(timeout))
self.timeout = httpx2.Timeout(float(timeout))
else:
self.timeout = timeout

Expand All @@ -86,7 +86,7 @@ def __init__(
self._client = http_client
self._owns_client = False
else:
self._client = httpx.Client(timeout=self.timeout)
self._client = httpx2.Client(timeout=self.timeout)
self._owns_client = True

@overload
Expand Down Expand Up @@ -154,10 +154,10 @@ def _request(
params=params,
headers=headers,
)
except httpx.TimeoutException as exc:
raise APITimeoutError(request=httpx.Request(method, url)) from exc
except httpx.TransportError as exc:
raise APIConnectionError(request=httpx.Request(method, url)) from exc
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)
Expand All @@ -173,7 +173,7 @@ def _request(
return cast_to.model_validate(data)

@staticmethod
def _make_status_error(response: httpx.Response) -> APIStatusError:
def _make_status_error(response: httpx2.Response) -> APIStatusError:
body: dict[str, Any] | None
try:
raw: object = response.json()
Expand Down
6 changes: 3 additions & 3 deletions src/triggerdev/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from triggerdev.resources.tasks import Tasks

if TYPE_CHECKING:
import httpx
import httpx2


class Client(BaseClient):
Expand All @@ -22,9 +22,9 @@ def __init__(
*,
api_key: str | None = None,
base_url: str | None = None,
timeout: float | httpx.Timeout | None = None,
timeout: float | httpx2.Timeout | None = None,
max_retries: int | None = None,
http_client: httpx.Client | None = None,
http_client: httpx2.Client | None = None,
default_headers: dict[str, str] | None = None,
) -> None:
super().__init__(
Expand Down
14 changes: 7 additions & 7 deletions src/triggerdev/_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from typing import TYPE_CHECKING

if TYPE_CHECKING:
import httpx
import httpx2


class TriggerDevError(Exception):
Expand All @@ -21,14 +21,14 @@ def __init__(self, message: str) -> None:
class APIError(TriggerDevError):
"""An error from the Trigger.dev API."""

request: httpx.Request
request: httpx2.Request
body: object | None

def __init__(
self,
message: str,
*,
request: httpx.Request,
request: httpx2.Request,
body: object | None,
) -> None:
super().__init__(message)
Expand All @@ -39,14 +39,14 @@ def __init__(
class APIStatusError(APIError):
"""An HTTP error response from the API."""

response: httpx.Response
response: httpx2.Response
status_code: int

def __init__(
self,
message: str,
*,
response: httpx.Response,
response: httpx2.Response,
body: object | None,
) -> None:
super().__init__(
Expand Down Expand Up @@ -119,7 +119,7 @@ class ServiceUnavailableError(InternalServerError):
class APIConnectionError(APIError):
"""Failed to connect to the API."""

def __init__(self, *, request: httpx.Request) -> None:
def __init__(self, *, request: httpx2.Request) -> None:
super().__init__(
"Connection error.",
request=request,
Expand All @@ -130,7 +130,7 @@ def __init__(self, *, request: httpx.Request) -> None:
class APITimeoutError(APIConnectionError):
"""The request timed out."""

def __init__(self, *, request: httpx.Request) -> None:
def __init__(self, *, request: httpx2.Request) -> None:
super().__init__(request=request)
self.message = "Request timed out."

Expand Down
2 changes: 0 additions & 2 deletions src/triggerdev/types/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@
RunTags,
SerializedError,
TriggerFunction,
_ApiModel,
)
from triggerdev.types.tasks import (
BatchTriggerTaskRequestBodyItem,
Expand Down Expand Up @@ -107,5 +106,4 @@
"TriggerTaskResponse",
"UpdateMetadataResponse",
"UpdateScheduleOptions",
"_ApiModel",
]
9 changes: 9 additions & 0 deletions tests/_alias_httpx.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"""Loaded as an early pytest plugin (`-p tests._alias_httpx` in `pyproject.toml`).

`respx` mocks `httpx`, while this SDK is built on `httpx2`, so we make `import httpx` (and `httpcore`)
resolve to `httpx2` (and `httpcore2`) before `respx` is imported, which lets it mock our client.
"""

import httpx2

httpx2.alias_httpx()
6 changes: 3 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from __future__ import annotations

import httpx
import httpx2
import pytest
import respx

Expand Down Expand Up @@ -31,5 +31,5 @@ def client(api_key: str, base_url: str) -> Client:


@pytest.fixture()
def mock_response() -> httpx.Response:
return httpx.Response(200, json={"id": "run_1234"})
def mock_response() -> httpx2.Response:
return httpx2.Response(200, json={"id": "run_1234"})
24 changes: 12 additions & 12 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import os
from unittest.mock import patch

import httpx
import httpx2
import pytest
import respx

Expand Down Expand Up @@ -62,14 +62,14 @@ def test_base_url_strips_trailing_slash(self) -> None:

def test_default_timeout(self) -> None:
client = Client(api_key="tr_dev_sk_test")
assert client.timeout == httpx.Timeout(60.0)
assert client.timeout == httpx2.Timeout(60.0)

def test_custom_timeout_float(self) -> None:
client = Client(api_key="tr_dev_sk_test", timeout=30.0)
assert client.timeout == httpx.Timeout(30.0)
assert client.timeout == httpx2.Timeout(30.0)

def test_custom_timeout_object(self) -> None:
t = httpx.Timeout(10.0, connect=5.0)
t = httpx2.Timeout(10.0, connect=5.0)
client = Client(api_key="tr_dev_sk_test", timeout=t)
assert client.timeout == t

Expand All @@ -93,7 +93,7 @@ def test_close(self) -> None:
assert client.is_closed

def test_custom_http_client_not_closed(self) -> None:
http_client = httpx.Client()
http_client = httpx2.Client()
client = Client(api_key="tr_dev_sk_test", http_client=http_client)
client.close()
assert not http_client.is_closed
Expand All @@ -104,7 +104,7 @@ class TestClientAuth:
@respx.mock
def test_auth_header_sent(self, client: Client) -> None:
route = respx.get("https://api.trigger.dev/api/v1/timezones").mock(
return_value=httpx.Response(200, json={"timezones": []})
return_value=httpx2.Response(200, json={"timezones": []})
)
client.schedules.timezones()
assert route.called
Expand Down Expand Up @@ -132,15 +132,15 @@ class TestErrorMapping:
@respx.mock
def test_status_code_to_exception(self, client: Client, status: int, exc_cls: type) -> None:
respx.get("https://api.trigger.dev/api/v3/runs/run_1234").mock(
return_value=httpx.Response(status, json={"error": "test error"})
return_value=httpx2.Response(status, json={"error": "test error"})
)
with pytest.raises(exc_cls):
client.runs.retrieve("run_1234")

@respx.mock
def test_unknown_4xx_raises_api_status_error(self, client: Client) -> None:
respx.get("https://api.trigger.dev/api/v3/runs/run_1234").mock(
return_value=httpx.Response(418, json={"error": "I'm a teapot"})
return_value=httpx2.Response(418, json={"error": "I'm a teapot"})
)
with pytest.raises(APIStatusError) as exc_info:
client.runs.retrieve("run_1234")
Expand All @@ -149,7 +149,7 @@ def test_unknown_4xx_raises_api_status_error(self, client: Client) -> None:
@respx.mock
def test_error_body_parsed(self, client: Client) -> None:
respx.get("https://api.trigger.dev/api/v3/runs/run_1234").mock(
return_value=httpx.Response(404, json={"error": "Run not found"})
return_value=httpx2.Response(404, json={"error": "Run not found"})
)
with pytest.raises(NotFoundError) as exc_info:
client.runs.retrieve("run_1234")
Expand All @@ -159,7 +159,7 @@ def test_error_body_parsed(self, client: Client) -> None:
@respx.mock
def test_non_json_error_body(self, client: Client) -> None:
respx.get("https://api.trigger.dev/api/v3/runs/run_1234").mock(
return_value=httpx.Response(
return_value=httpx2.Response(
502,
content=b"<html>Bad Gateway</html>",
headers={"content-type": "text/html"},
Expand All @@ -173,14 +173,14 @@ def test_non_json_error_body(self, client: Client) -> None:
@respx.mock
def test_connection_error(self, client: Client) -> None:
respx.get("https://api.trigger.dev/api/v3/runs/run_1234").mock(
side_effect=httpx.ConnectError("Connection refused")
side_effect=httpx2.ConnectError("Connection refused")
)
with pytest.raises(APIConnectionError):
client.runs.retrieve("run_1234")

@respx.mock
def test_timeout_error(self, client: Client) -> None:
respx.get("https://api.trigger.dev/api/v3/runs/run_1234").mock(side_effect=httpx.ReadTimeout("Read timed out"))
respx.get("https://api.trigger.dev/api/v3/runs/run_1234").mock(side_effect=httpx2.ReadTimeout("Read timed out"))
with pytest.raises(APITimeoutError):
client.runs.retrieve("run_1234")

Expand Down
10 changes: 5 additions & 5 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from __future__ import annotations

import httpx
import httpx2
import pytest

from triggerdev._exceptions import (
Expand All @@ -25,12 +25,12 @@
)


def _make_request() -> httpx.Request:
return httpx.Request("GET", "https://api.trigger.dev/api/v1/runs")
def _make_request() -> httpx2.Request:
return httpx2.Request("GET", "https://api.trigger.dev/api/v1/runs")


def _make_response(status_code: int, headers: dict[str, str] | None = None) -> httpx.Response:
return httpx.Response(
def _make_response(status_code: int, headers: dict[str, str] | None = None) -> httpx2.Response:
return httpx2.Response(
status_code,
request=_make_request(),
headers=headers or {},
Expand Down
Loading