diff --git a/.github/workflows/linter.yaml b/.github/workflows/linter.yaml index a6138f4f3..858fbde25 100644 --- a/.github/workflows/linter.yaml +++ b/.github/workflows/linter.yaml @@ -25,14 +25,14 @@ jobs: - name: Set up Python uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v6 with: - python-version-file: .python-version + python-version: '3.11' - name: Install uv uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 - name: Add uv to PATH run: | echo "$HOME/.cargo/bin" >> $GITHUB_PATH - name: Install dependencies - run: uv sync --locked + run: uv sync --locked --group httpx2 - name: Run Ruff Linter id: ruff-lint run: uv run ruff check --output-format=github diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 6126903eb..5c707c5ff 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -129,3 +129,39 @@ jobs: - name: Show coverage summary in log run: uv run coverage report + + # httpx2 testing - Running test on httpx2 for marked tests + httpx2: + name: Test with httpx2 (Python ${{ matrix.python-version }}) + runs-on: ubuntu-latest + + if: github.repository == 'a2aproject/a2a-python' + + strategy: + matrix: + python-version: ['3.11', '3.12', '3.13', '3.14'] + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 + + - name: Install uv for Python ${{ matrix.python-version }} + uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 + with: + python-version: ${{ matrix.python-version }} + - name: Add uv to PATH + run: | + echo "$HOME/.cargo/bin" >> $GITHUB_PATH + + - name: Install dependencies + run: uv sync --locked --group httpx2 + + # httpx_lib silently falls back to httpx when httpx2 is missing, thus installing httpx2 is required + - name: Verify httpx2 is the installed flavor + run: | + uv run python -c " + from a2a.utils._httpx_compat import httpx_lib + assert httpx_lib.__name__ == 'httpx2', httpx_lib.__name__ + " + + - name: Run tests + run: uv run pytest -m httpx2 diff --git a/pyproject.toml b/pyproject.toml index 23590e6a2..979c247a6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -85,6 +85,7 @@ addopts = "-ra --strict-markers --dist loadgroup" markers = [ "asyncio: mark a test as a coroutine that should be run by pytest-asyncio", "xdist_group: mark a test to run in a specific sequential group for isolation", + "httpx2: mark a test whose behavior depends on the installed HTTP client", ] filterwarnings = [ # SQLAlchemy warning about duplicate class registration - this is a known limitation @@ -105,6 +106,7 @@ vcs = "git" style = "pep440" [dependency-groups] +httpx2 = ["httpx2>=2.0.0,<3 ; python_version >= '3.11'"] dev = [ "fastapi>=0.115.2", "PyJWT>=2.0.0", diff --git a/src/a2a/client/card_resolver.py b/src/a2a/client/card_resolver.py index 447913572..c2ebae933 100644 --- a/src/a2a/client/card_resolver.py +++ b/src/a2a/client/card_resolver.py @@ -4,14 +4,17 @@ from collections.abc import Callable from typing import Any -import httpx - from google.protobuf.json_format import ParseDict, ParseError from a2a.client.errors import AgentCardResolutionError from a2a.types.a2a_pb2 import ( AgentCard, ) +from a2a.utils._httpx_compat import ( + HTTP_STATUS_ERROR, + REQUEST_ERROR, + AsyncClient, +) from a2a.utils.constants import AGENT_CARD_WELL_KNOWN_PATH @@ -133,14 +136,15 @@ class A2ACardResolver: def __init__( self, - httpx_client: httpx.AsyncClient, + httpx_client: AsyncClient, base_url: str, agent_card_path: str = AGENT_CARD_WELL_KNOWN_PATH, ) -> None: """Initializes the A2ACardResolver. Args: - httpx_client: An async HTTP client instance (e.g., httpx.AsyncClient). + httpx_client: An async HTTP client instance (`httpx.AsyncClient` + or `httpx2.AsyncClient`). base_url: The base URL of the agent's host. agent_card_path: The path to the agent card endpoint, relative to the base URL. """ @@ -200,7 +204,7 @@ async def get_agent_card( agent_card = parse_agent_card(agent_card_data) if signature_verifier: signature_verifier(agent_card) - except httpx.HTTPStatusError as e: + except HTTP_STATUS_ERROR as e: raise AgentCardResolutionError( f'Failed to fetch agent card from {target_url} (HTTP {e.response.status_code}): {e}', status_code=e.response.status_code, @@ -209,7 +213,7 @@ async def get_agent_card( raise AgentCardResolutionError( f'Failed to parse JSON for agent card from {target_url}: {e}' ) from e - except httpx.RequestError as e: + except REQUEST_ERROR as e: raise AgentCardResolutionError( f'Network communication error fetching agent card from {target_url}: {e}', ) from e diff --git a/src/a2a/client/client.py b/src/a2a/client/client.py index 3fbf4f287..ec33e74e3 100644 --- a/src/a2a/client/client.py +++ b/src/a2a/client/client.py @@ -6,8 +6,6 @@ from types import TracebackType from typing import Any -import httpx - from pydantic import BaseModel, Field from typing_extensions import Self @@ -31,6 +29,7 @@ Task, TaskPushNotificationConfig, ) +from a2a.utils._httpx_compat import AsyncClient logger = logging.getLogger(__name__) @@ -48,7 +47,7 @@ class ClientConfig: the callers job to check if the response is completed and if not run a polling loop.""" - httpx_client: httpx.AsyncClient | None = None + httpx_client: AsyncClient | None = None """Http client to use to connect to agent.""" grpc_channel_factory: Callable[[str], Channel] | None = None diff --git a/src/a2a/client/client_factory.py b/src/a2a/client/client_factory.py index db6266779..14d2ab107 100644 --- a/src/a2a/client/client_factory.py +++ b/src/a2a/client/client_factory.py @@ -33,6 +33,7 @@ if TYPE_CHECKING: from a2a.client.interceptors import ClientCallInterceptor + from a2a.utils._httpx_compat import AsyncClient try: @@ -96,7 +97,7 @@ def __init__( self._registry: dict[str, TransportProducer] = {} self._register_defaults(config.supported_protocol_bindings) - def _resolve_http_client(self) -> tuple[httpx.AsyncClient, bool]: + def _resolve_http_client(self) -> tuple[AsyncClient, bool]: """Returns an HTTP client and whether it is shared across clients.""" if self._config.httpx_client: return self._config.httpx_client, True diff --git a/src/a2a/client/transports/http_helpers.py b/src/a2a/client/transports/http_helpers.py index 89857c954..17e882b24 100644 --- a/src/a2a/client/transports/http_helpers.py +++ b/src/a2a/client/transports/http_helpers.py @@ -3,12 +3,19 @@ from collections.abc import AsyncGenerator, Callable, Iterator from contextlib import contextmanager -from typing import Any, NoReturn - -import httpx +from typing import TYPE_CHECKING, Any, NoReturn from a2a.client.client import ClientCallContext from a2a.client.errors import A2AClientError, A2AClientTimeoutError +from a2a.utils._httpx_compat import ( + HTTP_STATUS_ERROR, + REQUEST_ERROR, + TIMEOUT_EXCEPTION, + AsyncClient, + HTTPStatusError, + Request, + Response, +) def _default_sse_error_handler(sse_data: str) -> NoReturn: @@ -17,25 +24,24 @@ def _default_sse_error_handler(sse_data: str) -> NoReturn: @contextmanager def handle_http_exceptions( - status_error_handler: Callable[[httpx.HTTPStatusError], NoReturn] - | None = None, + status_error_handler: Callable[[HTTPStatusError], NoReturn] | None = None, ) -> Iterator[None]: """Handles common HTTP exceptions for REST and JSON-RPC transports. Args: - status_error_handler: Optional handler for `httpx.HTTPStatusError`. + status_error_handler: Optional handler for an HTTP status error. If provided, this handler should raise an appropriate domain-specific exception. If not provided, a default `A2AClientError` will be raised. """ try: yield - except httpx.TimeoutException as e: + except TIMEOUT_EXCEPTION as e: raise A2AClientTimeoutError('Client Request timed out') from e - except httpx.HTTPStatusError as e: + except HTTP_STATUS_ERROR as e: if status_error_handler: status_error_handler(e) raise A2AClientError(f'HTTP Error {e.response.status_code}: {e}') from e - except httpx.RequestError as e: + except REQUEST_ERROR as e: raise A2AClientError(f'Network communication error: {e}') from e except json.JSONDecodeError as e: raise A2AClientError(f'JSON Decode Error: {e}') from e @@ -52,10 +58,9 @@ def get_http_args(context: ClientCallContext | None) -> dict[str, Any]: async def send_http_request( - httpx_client: httpx.AsyncClient, - request: httpx.Request, - status_error_handler: Callable[[httpx.HTTPStatusError], NoReturn] - | None = None, + httpx_client: AsyncClient, + request: Request, + status_error_handler: Callable[[HTTPStatusError], NoReturn] | None = None, ) -> dict[str, Any]: """Sends an HTTP request and parses the JSON response, handling common exceptions.""" if httpx_client.is_closed: @@ -70,7 +75,7 @@ async def send_http_request( async def _aiter_sse_lines( - response: httpx.Response, + response: Response, ) -> AsyncGenerator[str, None]: """Yields lines ended only by CRLF, LF or CR, unlike `aiter_lines()`. @@ -100,9 +105,9 @@ async def _aiter_sse_lines( async def parse_sse_stream( - response: httpx.Response, + response: Response, ) -> AsyncGenerator[tuple[str, str], None]: - """Yields (event_name, data) from a streaming httpx.Response. + """Yields (event_name, data) from a streaming response. Conforms to the W3C Server-Sent Events specification. """ @@ -138,11 +143,10 @@ async def parse_sse_stream( async def send_http_stream_request( - httpx_client: httpx.AsyncClient, + httpx_client: AsyncClient, method: str, url: str, - status_error_handler: Callable[[httpx.HTTPStatusError], NoReturn] - | None = None, + status_error_handler: Callable[[HTTPStatusError], NoReturn] | None = None, sse_error_handler: Callable[[str], NoReturn] = _default_sse_error_handler, **kwargs: Any, ) -> AsyncGenerator[str]: @@ -167,7 +171,7 @@ async def send_http_stream_request( ) as response: try: response.raise_for_status() - except httpx.HTTPStatusError as e: + except HTTP_STATUS_ERROR as e: # Read upfront streaming error content immediately, otherwise lower-level handlers # (e.g. response.json()) crash with 'ResponseNotRead' Access errors. await response.aread() @@ -205,9 +209,12 @@ class _SSEEventSource: collision (see https://bugs.python.org/issue38559). """ + if TYPE_CHECKING: + _request: Request + def __init__( self, - client: httpx.AsyncClient, + client: AsyncClient, method: str, url: str, **kwargs: Any, @@ -222,9 +229,9 @@ def __init__( method, url, headers=headers, **kwargs ) self._client = client - self._response: httpx.Response | None = None + self._response: Response | None = None - async def __aenter__(self) -> httpx.Response: + async def __aenter__(self) -> Response: self._response = await self._client.send(self._request, stream=True) return self._response diff --git a/src/a2a/client/transports/jsonrpc.py b/src/a2a/client/transports/jsonrpc.py index 8519b5c75..2d39b7d21 100644 --- a/src/a2a/client/transports/jsonrpc.py +++ b/src/a2a/client/transports/jsonrpc.py @@ -5,8 +5,6 @@ from typing import Any, NoReturn from uuid import uuid4 -import httpx - from google.protobuf import json_format from jsonrpc.jsonrpc2 import JSONRPC20Request @@ -36,6 +34,7 @@ Task, TaskPushNotificationConfig, ) +from a2a.utils._httpx_compat import AsyncClient from a2a.utils.errors import JSON_RPC_ERROR_CODE_MAP from a2a.utils.proto_utils import parse_lenient from a2a.utils.telemetry import SpanKind, trace_class @@ -55,7 +54,7 @@ class JsonRpcTransport(ClientTransport): def __init__( self, - httpx_client: httpx.AsyncClient, + httpx_client: AsyncClient, agent_card: AgentCard, url: str, is_shared_httpx: bool = False, diff --git a/src/a2a/client/transports/rest.py b/src/a2a/client/transports/rest.py index 82a72f650..9d2b6ec2b 100644 --- a/src/a2a/client/transports/rest.py +++ b/src/a2a/client/transports/rest.py @@ -36,6 +36,7 @@ Task, TaskPushNotificationConfig, ) +from a2a.utils._httpx_compat import AsyncClient, HTTPStatusError, Request from a2a.utils.errors import A2A_REASON_TO_ERROR, MethodNotFoundError from a2a.utils.proto_utils import parse_lenient from a2a.utils.telemetry import SpanKind, trace_class @@ -102,7 +103,7 @@ class RestTransport(ClientTransport): def __init__( self, - httpx_client: httpx.AsyncClient, + httpx_client: AsyncClient, agent_card: AgentCard, url: str, is_shared_httpx: bool = False, @@ -305,7 +306,7 @@ async def delete_task_push_notification_config( f'/pushNotificationConfigs/{_quote_id(request.id)}', request.tenant, ) - http_request = self.httpx_client.build_request( + http_request: Request = self.httpx_client.build_request( 'DELETE', f'{self.url}{path}', params=params, @@ -370,7 +371,7 @@ def _get_path(self, base_path: str, tenant: str) -> str: """Returns the full path, prepending the tenant if provided.""" return f'/{tenant}{base_path}' if tenant else base_path - def _handle_http_error(self, e: httpx.HTTPStatusError) -> NoReturn: + def _handle_http_error(self, e: HTTPStatusError) -> NoReturn: """Handles HTTP status errors and raises the appropriate A2AError.""" try: error_payload = e.response.json() @@ -434,7 +435,7 @@ def _raise_in_band_error(self, sse_data: str) -> None: if isinstance(payload, dict) and 'error' in payload: self._handle_sse_error(sse_data) - async def _send_request(self, request: httpx.Request) -> dict[str, Any]: + async def _send_request(self, request: Request) -> dict[str, Any]: return await send_http_request( self.httpx_client, request, self._handle_http_error ) diff --git a/src/a2a/compat/v0_3/jsonrpc_transport.py b/src/a2a/compat/v0_3/jsonrpc_transport.py index 9e83168a1..ddeeb3f89 100644 --- a/src/a2a/compat/v0_3/jsonrpc_transport.py +++ b/src/a2a/compat/v0_3/jsonrpc_transport.py @@ -5,8 +5,6 @@ from typing import Any, NoReturn from uuid import uuid4 -import httpx - from jsonrpc.jsonrpc2 import JSONRPC20Request, JSONRPC20Response from a2a.client.client import ClientCallContext @@ -38,6 +36,7 @@ Task, TaskPushNotificationConfig, ) +from a2a.utils._httpx_compat import AsyncClient, HTTPStatusError from a2a.utils.constants import PROTOCOL_VERSION_0_3, VERSION_HEADER from a2a.utils.errors import JSON_RPC_ERROR_CODE_MAP from a2a.utils.telemetry import SpanKind, trace_class @@ -56,7 +55,7 @@ class CompatJsonRpcTransport(ClientTransport): def __init__( self, - httpx_client: httpx.AsyncClient, + httpx_client: AsyncClient, agent_card: AgentCard | None, url: str, *, @@ -424,7 +423,7 @@ def _create_jsonrpc_error(self, error_dict: dict[str, Any]) -> Exception: return A2AClientError(message) - def _handle_http_error(self, e: httpx.HTTPStatusError) -> NoReturn: + def _handle_http_error(self, e: HTTPStatusError) -> NoReturn: """Handles HTTP errors for standard requests.""" raise A2AClientError(f'HTTP Error: {e.response.status_code}') from e diff --git a/src/a2a/compat/v0_3/rest_transport.py b/src/a2a/compat/v0_3/rest_transport.py index 3f1e6b5c0..d48b83a5f 100644 --- a/src/a2a/compat/v0_3/rest_transport.py +++ b/src/a2a/compat/v0_3/rest_transport.py @@ -46,6 +46,14 @@ Task, TaskPushNotificationConfig, ) +from a2a.utils._httpx_compat import ( + HTTP_STATUS_ERROR, + RESPONSE_NOT_READ, + STREAM_CLOSED, + AsyncClient, + HTTPStatusError, + Request, +) from a2a.utils.constants import PROTOCOL_VERSION_0_3, VERSION_HEADER from a2a.utils.errors import JSON_RPC_ERROR_CODE_MAP, MethodNotFoundError from a2a.utils.proto_utils import warn_on_missing_required_fields @@ -70,7 +78,7 @@ class CompatRestTransport(ClientTransport): def __init__( self, - httpx_client: httpx.AsyncClient, + httpx_client: AsyncClient, agent_card: AgentCard | None, url: str, subscribe_method_override: str | None = None, @@ -322,10 +330,10 @@ async def subscribe( ): yield event except A2AClientError as e: - # Check for 405 Method Not Allowed in the cause (httpx.HTTPStatusError) + # Check for 405 Method Not Allowed in the cause (an HTTP status error) cause = e.__cause__ if ( - isinstance(cause, httpx.HTTPStatusError) + isinstance(cause, HTTP_STATUS_ERROR) and cause.response.status_code == httpx.codes.METHOD_NOT_ALLOWED ): if self._subscribe_method_override: @@ -377,15 +385,15 @@ async def close(self) -> None: except Exception as e: raise A2AClientError(f'Failed to close HTTP client: {e}') from e - def _handle_http_error(self, e: httpx.HTTPStatusError) -> NoReturn: + def _handle_http_error(self, e: HTTPStatusError) -> NoReturn: """Handles HTTP status errors and raises the appropriate A2AError.""" try: - with contextlib.suppress(httpx.StreamClosed): + with contextlib.suppress(*STREAM_CLOSED): e.response.read() try: error_data = e.response.json() - except (json.JSONDecodeError, ValueError, httpx.ResponseNotRead): + except (json.JSONDecodeError, ValueError, *RESPONSE_NOT_READ): error_data = {} if not isinstance(error_data, dict): error_data = {} @@ -437,7 +445,7 @@ async def _send_stream_request( ) ) - async def _send_request(self, request: httpx.Request) -> dict[str, Any]: + async def _send_request(self, request: Request) -> dict[str, Any]: return await send_http_request( self.httpx_client, request, self._handle_http_error ) diff --git a/src/a2a/server/tasks/base_push_notification_sender.py b/src/a2a/server/tasks/base_push_notification_sender.py index bade95752..974ad6ac9 100644 --- a/src/a2a/server/tasks/base_push_notification_sender.py +++ b/src/a2a/server/tasks/base_push_notification_sender.py @@ -4,8 +4,6 @@ from collections.abc import Awaitable, Callable -import httpx - from google.protobuf.json_format import MessageToDict from a2a.plugins.manager import PluginManager, get_global @@ -19,6 +17,7 @@ PushNotificationSender, ) from a2a.types.a2a_pb2 import TaskPushNotificationConfig +from a2a.utils._httpx_compat import AsyncClient from a2a.utils.proto_utils import to_stream_response @@ -30,7 +29,7 @@ class BasePushNotificationSender(PushNotificationSender): def __init__( self, - httpx_client: httpx.AsyncClient, + httpx_client: AsyncClient, config_store: PushNotificationConfigStore, context: ServerCallContext | None = None, *, diff --git a/src/a2a/utils/_httpx_compat.py b/src/a2a/utils/_httpx_compat.py new file mode 100644 index 000000000..36ba679a4 --- /dev/null +++ b/src/a2a/utils/_httpx_compat.py @@ -0,0 +1,94 @@ +"""Compatibility layer for `httpx` and `httpx2`. + +Although both packages share the same API, their classes are distinct types, so +`httpx2` classes are included in type unions and exception catch-tuples when +`httpx2` is installed. +""" + +from typing import TYPE_CHECKING, Any + +import httpx + + +if TYPE_CHECKING: + from typing import TypeAlias + + import httpx2 # ty: ignore[unresolved-import] + + httpx_lib = httpx + + AsyncClient: TypeAlias = httpx.AsyncClient | httpx2.AsyncClient + Response: TypeAlias = httpx.Response | httpx2.Response + HTTPStatusError: TypeAlias = httpx.HTTPStatusError | httpx2.HTTPStatusError + Request: TypeAlias = Any # For unions, Request could be httpx2 and be expected to return httpx + + HTTP_STATUS_ERROR: tuple[ + type[httpx.HTTPStatusError], type[httpx2.HTTPStatusError] + ] + REQUEST_ERROR: tuple[type[httpx.RequestError], type[httpx2.RequestError]] + TIMEOUT_EXCEPTION: tuple[ + type[httpx.TimeoutException], type[httpx2.TimeoutException] + ] + STREAM_CLOSED: tuple[type[httpx.StreamClosed], type[httpx2.StreamClosed]] + RESPONSE_NOT_READ: tuple[ + type[httpx.ResponseNotRead], type[httpx2.ResponseNotRead] + ] +else: + try: + import httpx2 + + httpx_lib = httpx2 + + AsyncClient = httpx.AsyncClient | httpx2.AsyncClient + Request = httpx.Request | httpx2.Request + Response = httpx.Response | httpx2.Response + HTTPStatusError = httpx.HTTPStatusError | httpx2.HTTPStatusError + + HTTP_STATUS_ERROR = ( + httpx.HTTPStatusError, + httpx2.HTTPStatusError, + ) + REQUEST_ERROR = ( + httpx.RequestError, + httpx2.RequestError, + ) + TIMEOUT_EXCEPTION = ( + httpx.TimeoutException, + httpx2.TimeoutException, + ) + STREAM_CLOSED = ( + httpx.StreamClosed, + httpx2.StreamClosed, + ) + RESPONSE_NOT_READ = ( + httpx.ResponseNotRead, + httpx2.ResponseNotRead, + ) + + except ImportError: + httpx_lib = httpx + + AsyncClient = httpx.AsyncClient + Request = httpx.Request + Response = httpx.Response + HTTPStatusError = httpx.HTTPStatusError + + HTTP_STATUS_ERROR = (httpx.HTTPStatusError,) + REQUEST_ERROR = (httpx.RequestError,) + TIMEOUT_EXCEPTION = (httpx.TimeoutException,) + STREAM_CLOSED = (httpx.StreamClosed,) + RESPONSE_NOT_READ = (httpx.ResponseNotRead,) + + +__all__ = [ + 'HTTP_STATUS_ERROR', + 'REQUEST_ERROR', + 'RESPONSE_NOT_READ', + 'STREAM_CLOSED', + 'TIMEOUT_EXCEPTION', + 'AsyncClient', + 'HTTPStatusError', + 'Request', + 'Response', + 'httpx_lib', +] diff --git a/tests/client/test_base_client.py b/tests/client/test_base_client.py index 43d2b0766..a69d00ae3 100644 --- a/tests/client/test_base_client.py +++ b/tests/client/test_base_client.py @@ -22,6 +22,9 @@ ) +pytestmark = pytest.mark.httpx2 + + @pytest.fixture def mock_transport() -> AsyncMock: return AsyncMock(spec=ClientTransport) diff --git a/tests/client/test_base_client_plugins.py b/tests/client/test_base_client_plugins.py index 2704f9291..dbb375e7e 100644 --- a/tests/client/test_base_client_plugins.py +++ b/tests/client/test_base_client_plugins.py @@ -1,7 +1,6 @@ from typing import Any from unittest.mock import AsyncMock -import httpx import pytest from a2a import plugins @@ -35,6 +34,10 @@ TaskStatus, TaskStatusUpdateEvent, ) +from a2a.utils._httpx_compat import httpx_lib + + +pytestmark = pytest.mark.httpx2 class Recorder(plugins.ClientPlugin): @@ -312,9 +315,9 @@ def test_factory_clients_use_the_global_manager(): manager = plugins.sequential(Recorder()) plugins.set_global(manager) - c = ClientFactory(ClientConfig(httpx_client=httpx.AsyncClient())).create( - card() - ) + c = ClientFactory( + ClientConfig(httpx_client=httpx_lib.AsyncClient()) + ).create(card()) assert isinstance(c, BaseClient) assert c._plugins is manager diff --git a/tests/client/test_card_resolver.py b/tests/client/test_card_resolver.py index a96402542..88144600c 100644 --- a/tests/client/test_card_resolver.py +++ b/tests/client/test_card_resolver.py @@ -5,7 +5,6 @@ from unittest.mock import AsyncMock, MagicMock, Mock -import httpx import pytest from a2a.client import A2ACardResolver, AgentCardResolutionError @@ -30,13 +29,17 @@ StringList, ) from a2a.utils import AGENT_CARD_WELL_KNOWN_PATH +from a2a.utils._httpx_compat import httpx_lib from google.protobuf.json_format import ParseError +pytestmark = pytest.mark.httpx2 + + @pytest.fixture def mock_httpx_client(): """Fixture providing a mocked async httpx client.""" - return AsyncMock(spec=httpx.AsyncClient) + return AsyncMock(spec=httpx_lib.AsyncClient) @pytest.fixture @@ -57,7 +60,7 @@ def resolver(mock_httpx_client, base_url): @pytest.fixture def mock_response(): """Fixture providing a mock httpx Response.""" - response = Mock(spec=httpx.Response) + response = Mock(spec=httpx_lib.Response) response.raise_for_status = Mock() return response @@ -198,7 +201,7 @@ async def test_get_agent_card_with_http_kwargs( mock_response, valid_agent_card_data, ): - """Test that http_kwargs are passed to httpx.get.""" + """Test that http_kwargs are passed to httpx_lib.get.""" mock_response.json.return_value = valid_agent_card_data mock_httpx_client.get.return_value = mock_response http_kwargs = { @@ -249,9 +252,9 @@ async def test_get_agent_card_http_status_error( ): """Test A2AClientHTTPError raised on HTTP status error.""" status_code = 404 - mock_response = Mock(spec=httpx.Response) + mock_response = Mock(spec=httpx_lib.Response) mock_response.status_code = status_code - mock_response.raise_for_status.side_effect = httpx.HTTPStatusError( + mock_response.raise_for_status.side_effect = httpx_lib.HTTPStatusError( 'Not Found', request=Mock(), response=mock_response ) mock_httpx_client.get.return_value = mock_response @@ -281,7 +284,7 @@ async def test_get_agent_card_request_error( self, resolver, mock_httpx_client ): """Test A2AClientHTTPError raised on network request error.""" - mock_httpx_client.get.side_effect = httpx.RequestError( + mock_httpx_client.get.side_effect = httpx_lib.RequestError( 'Connection timeout', request=Mock() ) with pytest.raises(AgentCardResolutionError) as exc_info: @@ -329,10 +332,10 @@ async def test_get_agent_card_non_object_json( self, response_body: str ) -> None: """Non-object JSON responses use the documented resolution error.""" - transport = httpx.MockTransport( - lambda _request: httpx.Response(200, content=response_body) + transport = httpx_lib.MockTransport( + lambda _request: httpx_lib.Response(200, content=response_body) ) - async with httpx.AsyncClient(transport=transport) as client: + async with httpx_lib.AsyncClient(transport=transport) as client: resolver = A2ACardResolver(client, 'https://example.com') with pytest.raises(AgentCardResolutionError) as exc_info: await resolver.get_agent_card() @@ -370,10 +373,10 @@ async def test_get_agent_card_malformed_nested_fields( self, response_body: str, original_error: type[Exception] ) -> None: """Malformed legacy fields preserve the documented error chain.""" - transport = httpx.MockTransport( - lambda _request: httpx.Response(200, content=response_body) + transport = httpx_lib.MockTransport( + lambda _request: httpx_lib.Response(200, content=response_body) ) - async with httpx.AsyncClient(transport=transport) as client: + async with httpx_lib.AsyncClient(transport=transport) as client: resolver = A2ACardResolver(client, 'https://example.com') with pytest.raises(AgentCardResolutionError) as exc_info: await resolver.get_agent_card() @@ -445,9 +448,9 @@ async def test_get_agent_card_different_status_codes( self, resolver, mock_httpx_client, status_code ): """Test different HTTP status codes raise appropriate errors.""" - mock_response = Mock(spec=httpx.Response) + mock_response = Mock(spec=httpx_lib.Response) mock_response.status_code = status_code - mock_response.raise_for_status.side_effect = httpx.HTTPStatusError( + mock_response.raise_for_status.side_effect = httpx_lib.HTTPStatusError( f'Status {status_code}', request=Mock(), response=mock_response ) mock_httpx_client.get.return_value = mock_response @@ -473,7 +476,7 @@ async def test_get_agent_card_with_signature_verifier( """Test that the signature verifier is called if provided.""" mock_verifier = MagicMock() - mock_response = MagicMock(spec=httpx.Response) + mock_response = MagicMock(spec=httpx_lib.Response) mock_response.json.return_value = valid_agent_card_data mock_httpx_client.get.return_value = mock_response diff --git a/tests/client/test_client_factory.py b/tests/client/test_client_factory.py index 10380d6c9..269090c83 100644 --- a/tests/client/test_client_factory.py +++ b/tests/client/test_client_factory.py @@ -4,7 +4,6 @@ from unittest.mock import AsyncMock, MagicMock, patch -import httpx import pytest from a2a.client import ClientConfig, ClientFactory, create_client @@ -20,11 +19,15 @@ AgentCard, AgentInterface, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.constants import ( TransportProtocol, ) +pytestmark = pytest.mark.httpx2 + + @pytest.fixture def base_agent_card() -> AgentCard: """Provides a base AgentCard for tests.""" @@ -48,7 +51,7 @@ def base_agent_card() -> AgentCard: def test_client_factory_selects_preferred_transport(base_agent_card: AgentCard): """Verify that the factory selects the preferred transport by default.""" config = ClientConfig( - httpx_client=httpx.AsyncClient(), + httpx_client=httpx_lib.AsyncClient(), supported_protocol_bindings=[ TransportProtocol.JSONRPC, TransportProtocol.HTTP_JSON, @@ -73,7 +76,7 @@ def test_client_factory_selects_secondary_transport_url( ) # Client prefers REST, which is available as a secondary transport config = ClientConfig( - httpx_client=httpx.AsyncClient(), + httpx_client=httpx_lib.AsyncClient(), supported_protocol_bindings=[ TransportProtocol.HTTP_JSON, TransportProtocol.JSONRPC, @@ -105,7 +108,7 @@ def test_client_factory_server_preference(base_agent_card: AgentCard): ) # Client supports both, but server prefers REST config = ClientConfig( - httpx_client=httpx.AsyncClient(), + httpx_client=httpx_lib.AsyncClient(), supported_protocol_bindings=[ TransportProtocol.JSONRPC, TransportProtocol.HTTP_JSON, @@ -139,7 +142,7 @@ def test_client_factory_prefers_1_0_ignoring_patch_version( ] ) config = ClientConfig( - httpx_client=httpx.AsyncClient(), + httpx_client=httpx_lib.AsyncClient(), supported_protocol_bindings=[TransportProtocol.JSONRPC], ) client = ClientFactory(config).create(base_agent_card) @@ -151,7 +154,7 @@ def test_client_factory_prefers_1_0_ignoring_patch_version( def test_client_factory_no_compatible_transport(base_agent_card: AgentCard): """Verify that the factory raises an error if no compatible transport is found.""" config = ClientConfig( - httpx_client=httpx.AsyncClient(), + httpx_client=httpx_lib.AsyncClient(), supported_protocol_bindings=['UNKNOWN_PROTOCOL'], ) factory = ClientFactory(config) @@ -200,7 +203,7 @@ async def test_client_factory_create_from_url_uses_factory_httpx_client( ) agent_url = 'http://example.com' - mock_httpx_client = httpx.AsyncClient() + mock_httpx_client = httpx_lib.AsyncClient() config = ClientConfig(httpx_client=mock_httpx_client) factory = ClientFactory(config) @@ -227,7 +230,7 @@ async def test_client_factory_create_from_url_passes_resolver_args( relative_path = '/extendedAgentCard' http_kwargs = {'headers': {'X-Test': 'true'}} - config = ClientConfig(httpx_client=httpx.AsyncClient()) + config = ClientConfig(httpx_client=httpx_lib.AsyncClient()) factory = ClientFactory(config) await factory.create_from_url( @@ -360,7 +363,7 @@ def test_client_factory_applies_tenant_decorator(base_agent_card: AgentCard): """Verify that the factory applies TenantTransportDecorator when tenant is present.""" base_agent_card.supported_interfaces[0].tenant = 'my-tenant' config = ClientConfig( - httpx_client=httpx.AsyncClient(), + httpx_client=httpx_lib.AsyncClient(), supported_protocol_bindings=[TransportProtocol.JSONRPC], ) factory = ClientFactory(config) @@ -402,7 +405,7 @@ async def test_create_client_with_url_and_config(base_agent_card: AgentCard): return_value=base_agent_card ) - mock_httpx_client = httpx.AsyncClient() + mock_httpx_client = httpx_lib.AsyncClient() config = ClientConfig(httpx_client=mock_httpx_client) await create_client('http://example.com', client_config=config) @@ -433,7 +436,7 @@ async def test_client_close_does_not_close_shared_httpx_client( base_agent_card: AgentCard, ): """Verify closing a client does not close a shared httpx_client from config.""" - shared_httpx_client = httpx.AsyncClient() + shared_httpx_client = httpx_lib.AsyncClient() try: factory = ClientFactory(ClientConfig(httpx_client=shared_httpx_client)) client = factory.create(base_agent_card) diff --git a/tests/client/test_errors.py b/tests/client/test_errors.py index 280f1c293..02a09757c 100644 --- a/tests/client/test_errors.py +++ b/tests/client/test_errors.py @@ -7,6 +7,9 @@ ) +pytestmark = pytest.mark.httpx2 + + class TestA2AClientError: """Test cases for the base A2AClientError class.""" diff --git a/tests/client/transports/test_http_helpers.py b/tests/client/transports/test_http_helpers.py index 86d9591d1..84a0ed2e2 100644 --- a/tests/client/transports/test_http_helpers.py +++ b/tests/client/transports/test_http_helpers.py @@ -1,6 +1,5 @@ from collections.abc import AsyncIterator -import httpx import pytest from a2a.client.client import ClientCallContext @@ -12,6 +11,10 @@ parse_sse_stream, send_http_stream_request, ) +from a2a.utils._httpx_compat import httpx_lib + + +pytestmark = pytest.mark.httpx2 def test_default_sse_error_handler(): @@ -33,7 +36,7 @@ async def mock_aiter_text(): yield 'data: \n' yield '\n' - response = httpx.Response(200) + response = httpx_lib.Response(200) response.aiter_text = mock_aiter_text # type: ignore events = [e async for e in parse_sse_stream(response)] @@ -73,7 +76,7 @@ async def test_parse_sse_stream_ends_lines_only_at_cr_or_lf( chunks: list[bytes], expected: list[tuple[str, str]] ) -> None: """Only CRLF, LF and CR end a line, as the SSE specification requires.""" - response = httpx.Response(200, content=_byte_chunks(chunks)) + response = httpx_lib.Response(200, content=_byte_chunks(chunks)) events = [e async for e in parse_sse_stream(response)] @@ -88,7 +91,7 @@ async def test_parse_sse_stream_long_data_line_over_many_chunks() -> None: body = f'data: {payload}\r\n\r\n'.encode() chunk_size = 512 chunks = [body[i : i + chunk_size] for i in range(0, len(body), chunk_size)] - response = httpx.Response(200, content=_byte_chunks(chunks)) + response = httpx_lib.Response(200, content=_byte_chunks(chunks)) # Re-joining and re-scanning the whole line on every chunk took tens of # seconds here; the linear version takes well under a second. @@ -99,9 +102,9 @@ async def test_parse_sse_stream_long_data_line_over_many_chunks() -> None: @pytest.mark.asyncio async def test_send_http_stream_request_non_sse(mocker): - client = httpx.AsyncClient() - request = httpx.Request('GET', 'http://test') - response = httpx.Response( + client = httpx_lib.AsyncClient() + request = httpx_lib.Request('GET', 'http://test') + response = httpx_lib.Response( 200, headers={'Content-Type': 'application/json'}, content=b'plain error response', @@ -128,9 +131,9 @@ def test_get_http_args_passes_timeout_through_unwrapped(): http_kwargs = get_http_args(ClientCallContext(timeout=5.0)) assert http_kwargs['timeout'] == 5.0 - assert not isinstance(http_kwargs['timeout'], httpx.Timeout) + assert not isinstance(http_kwargs['timeout'], httpx_lib.Timeout) - request = httpx.AsyncClient().build_request( + request = httpx_lib.AsyncClient().build_request( 'GET', 'http://test', **http_kwargs ) assert request.extensions['timeout'] == { @@ -142,7 +145,7 @@ def test_get_http_args_passes_timeout_through_unwrapped(): def test_sse_event_source_sets_default_stream_headers(): - source = _SSEEventSource(httpx.AsyncClient(), 'GET', 'http://test') + source = _SSEEventSource(httpx_lib.AsyncClient(), 'GET', 'http://test') assert source._request.headers['Accept'] == 'text/event-stream' assert source._request.headers['Cache-Control'] == 'no-store' @@ -160,7 +163,7 @@ def test_sse_event_source_keeps_caller_accept_whatever_its_case( spelling exactly is not enough to detect that they already set one. """ source = _SSEEventSource( - httpx.AsyncClient(), + httpx_lib.AsyncClient(), 'GET', 'http://test', headers={caller_spelling: 'application/json'}, diff --git a/tests/client/transports/test_jsonrpc_client.py b/tests/client/transports/test_jsonrpc_client.py index 0f49fbb7a..3ae287d23 100644 --- a/tests/client/transports/test_jsonrpc_client.py +++ b/tests/client/transports/test_jsonrpc_client.py @@ -6,7 +6,6 @@ from unittest.mock import AsyncMock, MagicMock, patch from uuid import uuid4 -import httpx import pytest from a2a.client.errors import A2AClientError @@ -30,6 +29,7 @@ TaskPushNotificationConfig, TaskState, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.errors import JSON_RPC_ERROR_CODE_MAP, TaskNotFoundError from google.protobuf import json_format @@ -44,11 +44,11 @@ async def async_iterable_from_list( @pytest.fixture def mock_httpx_client(): - """Creates a mock httpx.AsyncClient.""" - client = AsyncMock(spec=httpx.AsyncClient) + """Creates a mock AsyncClient.""" + client = AsyncMock(spec=httpx_lib.AsyncClient) client.is_closed = False - client.headers = httpx.Headers() - client.timeout = httpx.Timeout(30.0) + client.headers = httpx_lib.Headers() + client.timeout = httpx_lib.Timeout(30.0) return client @@ -104,6 +104,9 @@ def create_send_message_request(text='Hello'): from a2a.extensions.common import HTTP_EXTENSION_HEADER +pytestmark = pytest.mark.httpx2 + + def _assert_extensions_header(mock_kwargs: dict, expected_extensions: set[str]): headers = mock_kwargs.get('headers', {}) assert HTTP_EXTENSION_HEADER in headers @@ -185,7 +188,7 @@ async def test_send_message_jsonrpc_error( @pytest.mark.asyncio async def test_send_message_timeout(self, transport, mock_httpx_client): """Test handling of request timeout.""" - mock_httpx_client.send.side_effect = httpx.ReadTimeout('Timeout') + mock_httpx_client.send.side_effect = httpx_lib.ReadTimeout('Timeout') request = create_send_message_request() @@ -197,7 +200,7 @@ async def test_send_message_http_error(self, transport, mock_httpx_client): """Test handling of HTTP errors.""" mock_response = MagicMock() mock_response.status_code = 500 - mock_httpx_client.send.side_effect = httpx.HTTPStatusError( + mock_httpx_client.send.side_effect = httpx_lib.HTTPStatusError( 'Server Error', request=MagicMock(), response=mock_response ) @@ -448,7 +451,7 @@ async def test_send_message_streaming_sse_error( transport: JsonRpcTransport, ): request = create_send_message_request() - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.raise_for_status = MagicMock() mock_response.headers = {'content-type': 'text/event-stream'} mock_response.aiter_text.return_value = async_iterable_from_list( @@ -468,10 +471,10 @@ async def test_send_message_streaming_request_error( transport: JsonRpcTransport, ): request = create_send_message_request() - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.raise_for_status = MagicMock() mock_response.headers = {'content-type': 'text/event-stream'} - mock_response.aiter_text.side_effect = httpx.RequestError( + mock_response.aiter_text.side_effect = httpx_lib.RequestError( 'Simulated request error', request=MagicMock() ) mock_aconnect_sse.return_value.__aenter__.return_value = mock_response @@ -488,10 +491,12 @@ async def test_send_message_streaming_timeout( transport: JsonRpcTransport, ): request = create_send_message_request() - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.raise_for_status = MagicMock() mock_response.headers = {'content-type': 'text/event-stream'} - mock_response.aiter_text.side_effect = httpx.TimeoutException('Timeout') + mock_response.aiter_text.side_effect = httpx_lib.TimeoutException( + 'Timeout' + ) mock_aconnect_sse.return_value.__aenter__.return_value = mock_response with pytest.raises(A2AClientError, match='timed out'): @@ -567,12 +572,12 @@ async def test_send_message_streaming_server_error_propagates( ) request = create_send_message_request(text='Error stream') - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 403 mock_response.headers = {'content-type': 'text/event-stream'} - mock_response.raise_for_status.side_effect = httpx.HTTPStatusError( + mock_response.raise_for_status.side_effect = httpx_lib.HTTPStatusError( 'Forbidden', - request=httpx.Request('POST', 'http://test.url'), + request=httpx_lib.Request('POST', 'http://test.url'), response=mock_response, ) mock_response.aiter_text.return_value = async_iterable_from_list([]) @@ -804,7 +809,7 @@ async def test_send_message_streaming_ignores_unrecognized_fields( 'someNewField': 'x', }, } - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.raise_for_status = MagicMock() mock_response.headers = {'content-type': 'text/event-stream'} mock_response.aiter_text.return_value = async_iterable_from_list( @@ -960,7 +965,7 @@ async def test_delete_push_config_error_still_raises( async def test_streaming_malformed_event_raises_a2a_error( self, mock_sse_source: AsyncMock, transport, lines, expected_error ): - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.raise_for_status = MagicMock() mock_response.headers = {'content-type': 'text/event-stream'} mock_response.aiter_text.return_value = async_iterable_from_list( diff --git a/tests/client/transports/test_rest_client.py b/tests/client/transports/test_rest_client.py index a75aafc3c..0163da021 100644 --- a/tests/client/transports/test_rest_client.py +++ b/tests/client/transports/test_rest_client.py @@ -3,7 +3,6 @@ from collections.abc import AsyncGenerator from unittest.mock import AsyncMock, MagicMock, patch -import httpx import pytest import pytest_asyncio @@ -37,6 +36,7 @@ TaskState, TaskStatus, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.constants import ( PROTOCOL_VERSION_CURRENT, VERSION_HEADER, @@ -52,9 +52,12 @@ from starlette.applications import Starlette +pytestmark = pytest.mark.httpx2 + + @pytest.fixture def mock_httpx_client() -> AsyncMock: - client = AsyncMock(spec=httpx.AsyncClient) + client = AsyncMock(spec=httpx_lib.AsyncClient) client.is_closed = False return client @@ -106,10 +109,10 @@ async def test_send_message_streaming_timeout( params = SendMessageRequest( message=new_text_message(text='Hello stream') ) - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.headers = {'content-type': 'text/event-stream'} mock_response.raise_for_status.return_value = None - mock_response.aiter_text.side_effect = httpx.TimeoutException( + mock_response.aiter_text.side_effect = httpx_lib.TimeoutException( 'Read timed out' ) mock_aconnect_sse.return_value.__aenter__.return_value = mock_response @@ -139,11 +142,11 @@ async def test_rest_mapped_errors( params = SendMessageRequest(message=new_text_message(text='Hello')) mock_build_request = MagicMock( - return_value=AsyncMock(spec=httpx.Request) + return_value=AsyncMock(spec=httpx_lib.Request) ) mock_httpx_client.build_request = mock_build_request - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 500 reason = A2A_ERROR_MAPPING[error_cls][2] @@ -164,9 +167,9 @@ async def test_rest_mapped_errors( } } - error = httpx.HTTPStatusError( + error = httpx_lib.HTTPStatusError( 'Server Error', - request=httpx.Request('POST', 'http://test.url'), + request=httpx_lib.Request('POST', 'http://test.url'), response=mock_response, ) @@ -199,12 +202,12 @@ def test_rest_non_status_error_bodies( agent_card=mock_agent_card, url='http://agent.example.com/api', ) - mock_response = MagicMock(spec=httpx.Response) + mock_response = MagicMock(spec=httpx_lib.Response) mock_response.status_code = status_code mock_response.json.return_value = body - error = httpx.HTTPStatusError( + error = httpx_lib.HTTPStatusError( 'Error', - request=httpx.Request('GET', 'http://test.url'), + request=httpx_lib.Request('GET', 'http://test.url'), response=mock_response, ) @@ -226,11 +229,11 @@ async def test_send_message_with_timeout_context( context = ClientCallContext(timeout=10.0) mock_build_request = MagicMock( - return_value=AsyncMock(spec=httpx.Request) + return_value=AsyncMock(spec=httpx_lib.Request) ) mock_httpx_client.build_request = mock_build_request - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 200 mock_response.json = MagicMock(return_value={}) mock_httpx_client.send.return_value = mock_response @@ -265,10 +268,10 @@ async def test_url_serialization( # Use real build_request to get actual URL serialization mock_httpx_client.build_request.side_effect = ( - httpx.AsyncClient().build_request + httpx_lib.AsyncClient().build_request ) mock_httpx_client.send.return_value = AsyncMock( - spec=httpx.Response, status_code=200, json=lambda: {'tasks': []} + spec=httpx_lib.Response, status_code=200, json=lambda: {'tasks': []} ) await client.list_tasks(request=request) @@ -299,12 +302,12 @@ async def test_send_message_with_default_extensions( # Mock the build_request method to capture its inputs mock_build_request = MagicMock( - return_value=AsyncMock(spec=httpx.Request) + return_value=AsyncMock(spec=httpx_lib.Request) ) mock_httpx_client.build_request = mock_build_request # Mock the send method - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 200 mock_response.json = MagicMock(return_value={}) mock_httpx_client.send.return_value = mock_response @@ -345,7 +348,7 @@ async def test_send_message_streaming_with_new_extensions( message=new_text_message(text='Hello stream') ) - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.headers = {'content-type': 'text/event-stream'} mock_response.raise_for_status.return_value = None mock_response.aiter_text.return_value = async_iterable_from_list([]) @@ -390,12 +393,12 @@ async def test_send_message_streaming_server_error_propagates( message=new_text_message(text='Error stream') ) - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 403 mock_response.headers = {'content-type': 'text/event-stream'} - mock_response.raise_for_status.side_effect = httpx.HTTPStatusError( + mock_response.raise_for_status.side_effect = httpx_lib.HTTPStatusError( 'Forbidden', - request=httpx.Request('POST', 'http://test.url'), + request=httpx_lib.Request('POST', 'http://test.url'), response=mock_response, ) mock_response.aiter_text.return_value = async_iterable_from_list([]) @@ -434,7 +437,7 @@ async def test_get_card_with_extended_card_support_with_extensions( url='http://agent.example.com/api', ) - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 200 mock_response.json.return_value = json_format.MessageToDict( agent_card @@ -481,7 +484,7 @@ async def test_list_task_push_notification_configs_success( url='http://agent.example.com/api', ) task_id = 'task-1' - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 200 mock_response.json.return_value = { 'configs': [ @@ -496,7 +499,7 @@ async def test_list_task_push_notification_configs_success( # Mock the build_request method to capture its inputs mock_build_request = MagicMock( - return_value=AsyncMock(spec=httpx.Request) + return_value=AsyncMock(spec=httpx_lib.Request) ) mock_httpx_client.build_request = mock_build_request @@ -524,14 +527,14 @@ async def test_delete_task_push_notification_config_success( url='http://agent.example.com/api', ) task_id = 'task-1' - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 200 mock_response.json.return_value = {} mock_httpx_client.send.return_value = mock_response # Mock the build_request method to capture its inputs mock_build_request = MagicMock( - return_value=AsyncMock(spec=httpx.Request) + return_value=AsyncMock(spec=httpx_lib.Request) ) mock_httpx_client.build_request = mock_build_request @@ -559,10 +562,10 @@ async def test_delete_task_push_notification_config_ignores_body( self, mock_agent_card: MagicMock, status_code: int, content: bytes ): """Servers confirm a deletion with `{}`, 204, or a 200 with no body.""" - transport = httpx.MockTransport( - lambda request: httpx.Response(status_code, content=content) + transport = httpx_lib.MockTransport( + lambda request: httpx_lib.Response(status_code, content=content) ) - async with httpx.AsyncClient(transport=transport) as http_client: + async with httpx_lib.AsyncClient(transport=transport) as http_client: client = RestTransport( httpx_client=http_client, agent_card=mock_agent_card, @@ -593,10 +596,10 @@ async def test_delete_task_push_notification_config_maps_errors( ], } } - transport = httpx.MockTransport( - lambda request: httpx.Response(404, json=body) + transport = httpx_lib.MockTransport( + lambda request: httpx_lib.Response(404, json=body) ) - async with httpx.AsyncClient(transport=transport) as http_client: + async with httpx_lib.AsyncClient(transport=transport) as http_client: client = RestTransport( httpx_client=http_client, agent_card=mock_agent_card, @@ -710,10 +713,10 @@ async def test_rest_methods_prepend_tenant( # 2. Setup mocks mock_httpx_client.build_request.return_value = MagicMock( - spec=httpx.Request + spec=httpx_lib.Request ) mock_httpx_client.send.return_value = AsyncMock( - spec=httpx.Response, + spec=httpx_lib.Response, status_code=200, json=MagicMock(return_value={}), ) @@ -742,10 +745,10 @@ async def test_rest_get_extended_agent_card_prepend_tenant( # 1. Setup mocks mock_httpx_client.build_request.return_value = MagicMock( - spec=httpx.Request + spec=httpx_lib.Request ) mock_httpx_client.send.return_value = AsyncMock( - spec=httpx.Response, + spec=httpx_lib.Response, status_code=200, json=MagicMock(return_value={}), ) @@ -776,10 +779,10 @@ async def test_rest_get_task_prepend_empty_tenant( # 1. Setup mocks mock_httpx_client.build_request.return_value = MagicMock( - spec=httpx.Request + spec=httpx_lib.Request ) mock_httpx_client.send.return_value = AsyncMock( - spec=httpx.Response, + spec=httpx_lib.Response, status_code=200, json=MagicMock(return_value={}), ) @@ -830,7 +833,7 @@ async def test_rest_streaming_methods_prepend_tenant( # noqa: PLR0913 method = getattr(client, method_name) # 2. Setup mocks - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.headers = {'content-type': 'text/event-stream'} mock_response.raise_for_status.return_value = None mock_response.aiter_text.return_value = async_iterable_from_list([]) @@ -884,8 +887,8 @@ async def transport(self) -> AsyncGenerator[RestTransport, None]: app = Starlette( routes=create_rest_routes(request_handler=request_handler) ) - httpx_client = httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), + httpx_client = httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport(app=app), headers={VERSION_HEADER: PROTOCOL_VERSION_CURRENT}, ) transport = RestTransport(httpx_client, agent_card, 'http://agent') @@ -938,9 +941,9 @@ async def test_get_task_ignores_unrecognized_fields( url='http://agent.example.com/api', ) mock_httpx_client.build_request = MagicMock( - return_value=AsyncMock(spec=httpx.Request) + return_value=AsyncMock(spec=httpx_lib.Request) ) - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.raise_for_status = MagicMock() mock_response.json = MagicMock( return_value={ @@ -983,7 +986,7 @@ async def test_send_message_streaming_ignores_unrecognized_fields( }, 'someNewField': 'x', } - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.raise_for_status = MagicMock() mock_response.headers = {'content-type': 'text/event-stream'} mock_response.aiter_text.return_value = async_iterable_from_list( @@ -1017,9 +1020,9 @@ async def test_get_task_rejects_body_that_is_not_an_object( url='http://agent.example.com/api', ) mock_httpx_client.build_request = MagicMock( - return_value=AsyncMock(spec=httpx.Request) + return_value=AsyncMock(spec=httpx_lib.Request) ) - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.raise_for_status = MagicMock() mock_response.json = MagicMock(return_value=body) mock_httpx_client.send.return_value = mock_response @@ -1068,7 +1071,7 @@ async def test_stream_error_raises_mapped_error( agent_card=mock_agent_card, url='http://agent.example.com/api', ) - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.raise_for_status = MagicMock() mock_response.headers = {'content-type': 'text/event-stream'} mock_response.aiter_text.return_value = async_iterable_from_list( @@ -1094,7 +1097,7 @@ async def test_stream_event_of_unknown_type_is_still_yielded( agent_card=mock_agent_card, url='http://agent.example.com/api', ) - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.raise_for_status = MagicMock() mock_response.headers = {'content-type': 'text/event-stream'} mock_response.aiter_text.return_value = async_iterable_from_list( diff --git a/tests/client/transports/test_stream_media_type.py b/tests/client/transports/test_stream_media_type.py index 2679aef1b..2fbc75130 100644 --- a/tests/client/transports/test_stream_media_type.py +++ b/tests/client/transports/test_stream_media_type.py @@ -2,7 +2,6 @@ from typing import Any -import httpx import pytest from a2a.client.transports.jsonrpc import JsonRpcTransport @@ -15,9 +14,13 @@ SendMessageRequest, StreamResponse, ) +from a2a.utils._httpx_compat import httpx_lib from google.protobuf.json_format import MessageToDict +pytestmark = pytest.mark.httpx2 + + @pytest.mark.asyncio @pytest.mark.parametrize('transport_class', [RestTransport, JsonRpcTransport]) @pytest.mark.parametrize( @@ -44,7 +47,7 @@ async def test_streaming_transport_accepts_media_type_case( ) ) - def respond(request: httpx.Request) -> httpx.Response: + def respond(request: httpx_lib.Request) -> httpx_lib.Response: payload: dict[str, Any] = MessageToDict(expected) if transport_class is JsonRpcTransport: payload = { @@ -54,12 +57,12 @@ def respond(request: httpx.Request) -> httpx.Response: } serialized = json.dumps(payload) body = f'data: {serialized}\n\n' if is_sse else serialized - return httpx.Response( + return httpx_lib.Response( 200, headers={'Content-Type': content_type}, text=body ) - async with httpx.AsyncClient( - transport=httpx.MockTransport(respond) + async with httpx_lib.AsyncClient( + transport=httpx_lib.MockTransport(respond) ) as http_client: transport = transport_class( httpx_client=http_client, diff --git a/tests/compat/v0_3/test_jsonrpc_app_compat.py b/tests/compat/v0_3/test_jsonrpc_app_compat.py index 5a9227d20..5dc75ade9 100644 --- a/tests/compat/v0_3/test_jsonrpc_app_compat.py +++ b/tests/compat/v0_3/test_jsonrpc_app_compat.py @@ -31,6 +31,9 @@ from starlette.testclient import TestClient +pytestmark = pytest.mark.httpx2 + + logger = logging.getLogger(__name__) diff --git a/tests/compat/v0_3/test_jsonrpc_transport.py b/tests/compat/v0_3/test_jsonrpc_transport.py index 13d91162a..56a17e084 100644 --- a/tests/compat/v0_3/test_jsonrpc_transport.py +++ b/tests/compat/v0_3/test_jsonrpc_transport.py @@ -1,6 +1,5 @@ from unittest.mock import AsyncMock, MagicMock, patch -import httpx import pytest from a2a.client.errors import A2AClientError @@ -26,12 +25,16 @@ TaskPushNotificationConfig, TaskState, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.errors import InvalidParamsError +pytestmark = pytest.mark.httpx2 + + @pytest.fixture def mock_httpx_client(): - client = AsyncMock(spec=httpx.AsyncClient) + client = AsyncMock(spec=httpx_lib.AsyncClient) client.is_closed = False return client @@ -435,13 +438,13 @@ async def mock_send_stream_request(*args, **kwargs): def test_compat_jsonrpc_transport_handle_http_error(transport): - mock_response = MagicMock(spec=httpx.Response) + mock_response = MagicMock(spec=httpx_lib.Response) mock_response.status_code = 400 - mock_request = MagicMock(spec=httpx.Request) + mock_request = MagicMock(spec=httpx_lib.Request) mock_request.url = 'http://example.com' - error = httpx.HTTPStatusError( + error = httpx_lib.HTTPStatusError( 'Error', request=mock_request, response=mock_response ) @@ -526,7 +529,7 @@ async def test_compat_jsonrpc_transport_send_request( mock_send_http_request, transport ): mock_send_http_request.return_value = {'result': {'ok': True}} - mock_request = httpx.Request('POST', 'http://example.com') + mock_request = httpx_lib.Request('POST', 'http://example.com') transport.httpx_client.build_request.return_value = mock_request res = await transport._send_request({'some': 'data'}) @@ -553,7 +556,7 @@ async def test_compat_jsonrpc_transport_mirrors_extension_header( from a2a.client.client import ClientCallContext mock_send_http_request.return_value = {'result': {'ok': True}} - transport.httpx_client.build_request.return_value = httpx.Request( + transport.httpx_client.build_request.return_value = httpx_lib.Request( 'POST', 'http://example.com' ) diff --git a/tests/compat/v0_3/test_rest_routes_compat.py b/tests/compat/v0_3/test_rest_routes_compat.py index fbeacb1cf..0f1877772 100644 --- a/tests/compat/v0_3/test_rest_routes_compat.py +++ b/tests/compat/v0_3/test_rest_routes_compat.py @@ -22,15 +22,18 @@ TaskState as TaskState10, TaskStatus as TaskStatus10, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.errors import TaskNotFoundError from fastapi import FastAPI from google.protobuf import json_format -from httpx import ASGITransport, AsyncClient from starlette.applications import Starlette from starlette.datastructures import Headers from starlette.requests import Request +pytestmark = pytest.mark.httpx2 + + logger = logging.getLogger(__name__) @@ -100,15 +103,15 @@ async def app( @pytest.fixture -async def client(app: FastAPI) -> AsyncClient: - return AsyncClient( - transport=ASGITransport(app=app), base_url='http://testapp' +async def client(app: FastAPI) -> httpx_lib.AsyncClient: + return httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport(app=app), base_url='http://testapp' ) @pytest.mark.anyio async def test_send_message_success_message_v03( - client: AsyncClient, request_handler: MagicMock + client: httpx_lib.AsyncClient, request_handler: MagicMock ) -> None: expected_response = a2a_v0_3_pb2.SendMessageResponse( msg=a2a_v0_3_pb2.Message( @@ -143,7 +146,7 @@ async def test_send_message_success_message_v03( @pytest.mark.anyio async def test_send_message_success_task_v03( - client: AsyncClient, request_handler: MagicMock + client: httpx_lib.AsyncClient, request_handler: MagicMock ) -> None: expected_response = a2a_v0_3_pb2.SendMessageResponse( task=a2a_v0_3_pb2.Task( @@ -178,7 +181,7 @@ async def test_send_message_success_task_v03( @pytest.mark.anyio async def test_get_task_v03( - client: AsyncClient, request_handler: MagicMock + client: httpx_lib.AsyncClient, request_handler: MagicMock ) -> None: expected_response = a2a_v0_3_pb2.Task( id='test_task_id', @@ -205,7 +208,7 @@ async def test_get_task_v03( @pytest.mark.anyio async def test_get_task_v03_non_integer_history_length( - client: AsyncClient, request_handler: MagicMock + client: httpx_lib.AsyncClient, request_handler: MagicMock ) -> None: response = await client.get('/v1/tasks/test_task_id?historyLength=abc') @@ -220,7 +223,7 @@ async def test_get_task_v03_non_integer_history_length( ['/v1/message:send', '/v1/tasks/test_task_id/pushNotificationConfigs'], ) async def test_invalid_utf8_body_v03_is_bad_request( - client: AsyncClient, path: str + client: httpx_lib.AsyncClient, path: str ) -> None: response = await client.post( path, content=b'{"message": {"messageId": "\xff"}}' @@ -232,7 +235,7 @@ async def test_invalid_utf8_body_v03_is_bad_request( @pytest.mark.anyio async def test_delete_push_notification_config_v03( - client: AsyncClient, request_handler: MagicMock + client: httpx_lib.AsyncClient, request_handler: MagicMock ) -> None: request_handler.on_delete_task_push_notification_config.return_value = None @@ -253,7 +256,7 @@ async def test_delete_push_notification_config_v03( @pytest.mark.anyio async def test_delete_push_notification_config_v03_unknown_task_returns_404( - client: AsyncClient, request_handler: MagicMock + client: httpx_lib.AsyncClient, request_handler: MagicMock ) -> None: request_handler.on_delete_task_push_notification_config.side_effect = ( TaskNotFoundError @@ -269,7 +272,7 @@ async def test_delete_push_notification_config_v03_unknown_task_returns_404( @pytest.mark.anyio async def test_compat_rest_client_deletes_push_notification_config( - client: AsyncClient, request_handler: MagicMock + client: httpx_lib.AsyncClient, request_handler: MagicMock ) -> None: request_handler.on_delete_task_push_notification_config.return_value = None transport = CompatRestTransport( @@ -303,7 +306,7 @@ async def test_list_tasks_not_in_v03_adapter_routes( @pytest.mark.anyio async def test_cancel_task_v03( - client: AsyncClient, request_handler: MagicMock + client: httpx_lib.AsyncClient, request_handler: MagicMock ) -> None: expected_response = a2a_v0_3_pb2.Task( id='test_task_id', @@ -369,7 +372,7 @@ async def stream_with_non_ascii( @pytest.mark.anyio async def test_v03_message_stream_malformed_json_returns_400( - client: AsyncClient, request_handler: MagicMock + client: httpx_lib.AsyncClient, request_handler: MagicMock ) -> None: response = await client.post( '/v1/message:stream', @@ -385,7 +388,7 @@ async def test_v03_message_stream_malformed_json_returns_400( @pytest.mark.anyio async def test_v03_subscribe_unknown_task_returns_404( - client: AsyncClient, request_handler: MagicMock + client: httpx_lib.AsyncClient, request_handler: MagicMock ) -> None: async def not_found(*args: object, **kwargs: object) -> AsyncIterator[None]: raise TaskNotFoundError diff --git a/tests/compat/v0_3/test_rest_transport.py b/tests/compat/v0_3/test_rest_transport.py index 551d39c35..98006a16d 100644 --- a/tests/compat/v0_3/test_rest_transport.py +++ b/tests/compat/v0_3/test_rest_transport.py @@ -3,7 +3,6 @@ from collections.abc import AsyncGenerator from unittest.mock import AsyncMock, MagicMock, patch -import httpx import pytest import pytest_asyncio @@ -39,13 +38,17 @@ TaskState, TaskStatus, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.errors import InvalidParamsError, MethodNotFoundError from starlette.applications import Starlette +pytestmark = pytest.mark.httpx2 + + @pytest.fixture def mock_httpx_client(): - client = AsyncMock(spec=httpx.AsyncClient) + client = AsyncMock(spec=httpx_lib.AsyncClient) client.is_closed = False return client @@ -68,7 +71,7 @@ def transport(mock_httpx_client, agent_card): async def test_compat_rest_transport_send_message_response_msg_parsing( transport, ): - mock_response = MagicMock(spec=httpx.Response) + mock_response = MagicMock(spec=httpx_lib.Response) mock_response.json.return_value = { 'msg': {'messageId': 'msg-123', 'role': 'agent'} } @@ -92,7 +95,7 @@ async def mock_send_request(*args, **kwargs): @pytest.mark.asyncio async def test_compat_rest_transport_send_message_task(transport): - mock_response = MagicMock(spec=httpx.Response) + mock_response = MagicMock(spec=httpx_lib.Response) mock_response.json.return_value = {'task': {'id': 'task-123'}} async def mock_send_request(*args, **kwargs): @@ -296,31 +299,31 @@ async def mock_send_stream_request(*args, **kwargs): def create_405_error(): - mock_response = MagicMock(spec=httpx.Response) + mock_response = MagicMock(spec=httpx_lib.Response) mock_response.status_code = 405 mock_response.json.return_value = { 'type': 'MethodNotAllowed', 'message': 'Method Not Allowed', } - mock_request = MagicMock(spec=httpx.Request) + mock_request = MagicMock(spec=httpx_lib.Request) mock_request.url = 'http://example.com/v1/tasks/task-123:subscribe' - status_error = httpx.HTTPStatusError( + status_error = httpx_lib.HTTPStatusError( '405 Method Not Allowed', request=mock_request, response=mock_response ) raise A2AClientError('HTTP Error 405') from status_error def create_500_error(): - mock_response = MagicMock(spec=httpx.Response) + mock_response = MagicMock(spec=httpx_lib.Response) mock_response.status_code = 500 mock_response.json.return_value = { 'type': 'InternalError', 'message': 'Internal Error', } - mock_request = MagicMock(spec=httpx.Request) + mock_request = MagicMock(spec=httpx_lib.Request) - status_error = httpx.HTTPStatusError( + status_error = httpx_lib.HTTPStatusError( '500 Internal Error', request=mock_request, response=mock_response ) raise A2AClientError('HTTP Error 500') from status_error @@ -511,17 +514,17 @@ async def mock_stream(method, path, context=None, json=None): def test_compat_rest_transport_handle_http_error(transport): - mock_response = MagicMock(spec=httpx.Response) + mock_response = MagicMock(spec=httpx_lib.Response) mock_response.status_code = 400 mock_response.json.return_value = { 'type': 'InvalidParamsError', 'message': 'Invalid parameters', } - mock_request = MagicMock(spec=httpx.Request) + mock_request = MagicMock(spec=httpx_lib.Request) mock_request.url = 'http://example.com' - error = httpx.HTTPStatusError( + error = httpx_lib.HTTPStatusError( 'Error', request=mock_request, response=mock_response ) @@ -532,14 +535,14 @@ def test_compat_rest_transport_handle_http_error(transport): def test_compat_rest_transport_handle_http_error_not_found(transport): - mock_response = MagicMock(spec=httpx.Response) + mock_response = MagicMock(spec=httpx_lib.Response) mock_response.status_code = 404 mock_response.json.side_effect = json.JSONDecodeError('msg', 'doc', 0) - mock_request = MagicMock(spec=httpx.Request) + mock_request = MagicMock(spec=httpx_lib.Request) mock_request.url = 'http://example.com' - error = httpx.HTTPStatusError( + error = httpx_lib.HTTPStatusError( 'Error', request=mock_request, response=mock_response ) @@ -548,14 +551,14 @@ def test_compat_rest_transport_handle_http_error_not_found(transport): def test_compat_rest_transport_handle_http_error_generic(transport): - mock_response = MagicMock(spec=httpx.Response) + mock_response = MagicMock(spec=httpx_lib.Response) mock_response.status_code = 500 mock_response.json.side_effect = json.JSONDecodeError('msg', 'doc', 0) - mock_request = MagicMock(spec=httpx.Request) + mock_request = MagicMock(spec=httpx_lib.Request) mock_request.url = 'http://example.com' - error = httpx.HTTPStatusError( + error = httpx_lib.HTTPStatusError( 'Error', request=mock_request, response=mock_response ) @@ -801,17 +804,17 @@ async def mock_execute_request(method, path, context=None, params=None): def test_compat_rest_transport_handle_http_error_invalid_error_type(transport): - mock_response = MagicMock(spec=httpx.Response) + mock_response = MagicMock(spec=httpx_lib.Response) mock_response.status_code = 500 mock_response.json.return_value = { 'type': 123, 'message': 'Invalid parameters', } - mock_request = MagicMock(spec=httpx.Request) + mock_request = MagicMock(spec=httpx_lib.Request) mock_request.url = 'http://example.com' - error = httpx.HTTPStatusError( + error = httpx_lib.HTTPStatusError( 'Error', request=mock_request, response=mock_response ) @@ -830,14 +833,14 @@ def test_compat_rest_transport_handle_http_error_invalid_error_type(transport): def test_compat_rest_transport_handle_http_error_non_object_body( transport, status_code, body, expected_error ): - mock_response = MagicMock(spec=httpx.Response) + mock_response = MagicMock(spec=httpx_lib.Response) mock_response.status_code = status_code mock_response.json.return_value = body - mock_request = MagicMock(spec=httpx.Request) + mock_request = MagicMock(spec=httpx_lib.Request) mock_request.url = 'http://example.com' - error = httpx.HTTPStatusError( + error = httpx_lib.HTTPStatusError( 'Error', request=mock_request, response=mock_response ) @@ -846,17 +849,17 @@ def test_compat_rest_transport_handle_http_error_non_object_body( def test_compat_rest_transport_handle_http_error_unknown_error_type(transport): - mock_response = MagicMock(spec=httpx.Response) + mock_response = MagicMock(spec=httpx_lib.Response) mock_response.status_code = 500 mock_response.json.return_value = { 'type': 'SomeUnknownErrorClass', 'message': 'Unknown', } - mock_request = MagicMock(spec=httpx.Request) + mock_request = MagicMock(spec=httpx_lib.Request) mock_request.url = 'http://example.com' - error = httpx.HTTPStatusError( + error = httpx_lib.HTTPStatusError( 'Error', request=mock_request, response=mock_response ) @@ -898,7 +901,7 @@ async def test_compat_rest_transport_execute_request( mock_send_http_request, transport ): mock_send_http_request.return_value = {'ok': True} - mock_request = httpx.Request('POST', 'http://example.com') + mock_request = httpx_lib.Request('POST', 'http://example.com') transport.httpx_client.build_request.return_value = mock_request res = await transport._execute_request( @@ -951,7 +954,9 @@ async def transport(self) -> AsyncGenerator[CompatRestTransport, None]: request_handler=request_handler, enable_v0_3_compat=True ) ) - httpx_client = httpx.AsyncClient(transport=httpx.ASGITransport(app=app)) + httpx_client = httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport(app=app) + ) transport = CompatRestTransport( httpx_client, agent_card, 'http://agent' ) diff --git a/tests/integration/push_notifications/agent_app.py b/tests/integration/push_notifications/agent_app.py index 127ee9d1e..6a5302023 100644 --- a/tests/integration/push_notifications/agent_app.py +++ b/tests/integration/push_notifications/agent_app.py @@ -1,5 +1,3 @@ -import httpx - from a2a.auth.user import UnauthenticatedUser, User from a2a.helpers.proto_helpers import ( new_task_from_user_message, @@ -26,6 +24,7 @@ Message, Task, ) +from a2a.utils._httpx_compat import httpx_lib from starlette.applications import Starlette from starlette.requests import Request @@ -138,7 +137,7 @@ async def cancel( def create_agent_app( - url: str, notification_client: httpx.AsyncClient + url: str, notification_client: httpx_lib.AsyncClient ) -> Starlette: """Creates a new HTTP+REST Starlette application for the test agent.""" push_config_store = InMemoryPushNotificationConfigStore() @@ -191,7 +190,7 @@ def build_user(self, request: Request) -> User: def create_multi_user_agent_app( - url: str, notification_client: httpx.AsyncClient + url: str, notification_client: httpx_lib.AsyncClient ) -> Starlette: """Creates a multi-user variant of the test agent app. diff --git a/tests/integration/push_notifications/test_default_push_notification_support.py b/tests/integration/push_notifications/test_default_push_notification_support.py index eb7928ba9..7e1f72605 100644 --- a/tests/integration/push_notifications/test_default_push_notification_support.py +++ b/tests/integration/push_notifications/test_default_push_notification_support.py @@ -2,7 +2,6 @@ import time import uuid -import httpx import pytest import pytest_asyncio @@ -21,6 +20,7 @@ TaskPushNotificationConfig, TaskState, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.constants import TransportProtocol from .agent_app import create_agent_app, create_multi_user_agent_app @@ -32,6 +32,9 @@ ) +pytestmark = pytest.mark.httpx2 + + _TEST_USER_HEADER = 'x-test-user' @@ -61,12 +64,12 @@ def notifications_server(): @pytest_asyncio.fixture(scope='module') async def notifications_client(): """An async client fixture for calling the notifications server.""" - async with httpx.AsyncClient() as client: + async with httpx_lib.AsyncClient() as client: yield client @pytest.fixture(scope='module') -def agent_server(notifications_client: httpx.AsyncClient): +def agent_server(notifications_client: httpx_lib.AsyncClient): """Starts a test agent server and yields its URL.""" host = '127.0.0.1' port = find_free_port() @@ -91,7 +94,7 @@ def agent_server(notifications_client: httpx.AsyncClient): @pytest.fixture(scope='module') -def multi_user_agent_server(notifications_client: httpx.AsyncClient): +def multi_user_agent_server(notifications_client: httpx_lib.AsyncClient): """Starts the multi-user variant of the test agent server. This variant reads identity from an x-test-user request header @@ -127,7 +130,7 @@ def multi_user_agent_server(notifications_client: httpx.AsyncClient): @pytest_asyncio.fixture(scope='function') async def http_client(): """An async client fixture for test functions.""" - async with httpx.AsyncClient() as client: + async with httpx_lib.AsyncClient() as client: yield client @@ -135,7 +138,7 @@ async def http_client(): async def test_notification_triggering_with_in_message_config_e2e( notifications_server: str, agent_server: str, - http_client: httpx.AsyncClient, + http_client: httpx_lib.AsyncClient, ): """ Tests push notification triggering for in-message push notification config. @@ -195,7 +198,9 @@ async def test_notification_triggering_with_in_message_config_e2e( @pytest.mark.asyncio async def test_notification_triggering_after_config_change_e2e( - notifications_server: str, agent_server: str, http_client: httpx.AsyncClient + notifications_server: str, + agent_server: str, + http_client: httpx_lib.AsyncClient, ): """ Tests notification triggering after setting the push notification config in a separate call. @@ -278,7 +283,7 @@ async def test_notification_triggering_after_config_change_e2e( async def test_multi_registrar_fan_out_e2e( notifications_server: str, agent_server: str, - http_client: httpx.AsyncClient, + http_client: httpx_lib.AsyncClient, ): """Two pushNotificationConfigs registered for the same task both fire end-to-end. @@ -387,10 +392,10 @@ def _make_user_a2a_client(agent_server: str, user_name: str): """Builds an A2A client that identifies as user_name on every request. Identity is conveyed via a default header on the underlying - httpx.AsyncClient; the multi-user agent app's context builder + AsyncClient; the multi-user agent app's context builder reads that header to populate ServerCallContext.user. """ - httpx_client = httpx.AsyncClient(headers={_TEST_USER_HEADER: user_name}) + httpx_client = httpx_lib.AsyncClient(headers={_TEST_USER_HEADER: user_name}) return ClientFactory( ClientConfig( httpx_client=httpx_client, @@ -405,7 +410,7 @@ def _make_user_a2a_client(agent_server: str, user_name: str): async def test_alice_and_bob_both_receive_notifications_on_shared_task_e2e( notifications_server: str, multi_user_agent_server: str, - http_client: httpx.AsyncClient, + http_client: httpx_lib.AsyncClient, ): """Alice registers a webhook; Bob registers a webhook; both fire end-to-end. @@ -541,7 +546,7 @@ async def test_alice_and_bob_both_receive_notifications_on_shared_task_e2e( async def wait_for_n_notifications( - http_client: httpx.AsyncClient, + http_client: httpx_lib.AsyncClient, url: str, n: int, timeout: int = 3, diff --git a/tests/integration/push_notifications/utils.py b/tests/integration/push_notifications/utils.py index a7317f1b2..62d85fb05 100644 --- a/tests/integration/push_notifications/utils.py +++ b/tests/integration/push_notifications/utils.py @@ -4,9 +4,10 @@ import sys import time -import httpx import uvicorn +from a2a.utils._httpx_compat import httpx_lib + def find_free_port(): """Finds and returns an available ephemeral localhost port.""" @@ -26,8 +27,8 @@ def wait_for_server_ready( """Polls the provided URL endpoint until the server is up.""" start_time = time.time() while True: - with contextlib.suppress(httpx.ConnectError): - with httpx.Client(headers=headers) as client: + with contextlib.suppress(httpx_lib.ConnectError): + with httpx_lib.Client(headers=headers) as client: response = client.get(url) if response.status_code == 200: return diff --git a/tests/integration/test_agent_card.py b/tests/integration/test_agent_card.py index 9cc6b142a..155603e8c 100644 --- a/tests/integration/test_agent_card.py +++ b/tests/integration/test_agent_card.py @@ -1,4 +1,3 @@ -import httpx import pytest from a2a.server.agent_execution import AgentExecutor, RequestContext @@ -16,11 +15,15 @@ AgentCard, AgentInterface, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.constants import VERSION_HEADER, TransportProtocol from fastapi import FastAPI from starlette.applications import Starlette +pytestmark = pytest.mark.httpx2 + + class DummyAgentExecutor(AgentExecutor): """An agent executor that does nothing for integration testing.""" @@ -115,8 +118,8 @@ async def test_agent_card_integration(header_val: str | None) -> None: headers[VERSION_HEADER] = header_val # 3. Use direct http client (ASGITransport) to fetch and assert - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), base_url='http://testserver' + async with httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport(app=app), base_url='http://testserver' ) as client: # Fetch from JSONRPC endpoint resp_jsonrpc = await client.get( diff --git a/tests/integration/test_client_server_integration.py b/tests/integration/test_client_server_integration.py index ea093aa7e..15c8bea5c 100644 --- a/tests/integration/test_client_server_integration.py +++ b/tests/integration/test_client_server_integration.py @@ -5,7 +5,6 @@ from unittest.mock import ANY, AsyncMock, patch import grpc -import httpx import pytest import pytest_asyncio @@ -57,6 +56,7 @@ TaskStatus, TaskStatusUpdateEvent, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.constants import ( PROTOCOL_VERSION_CURRENT, VERSION_HEADER, @@ -83,6 +83,9 @@ from starlette.applications import Starlette +pytestmark = pytest.mark.httpx2 + + # --- Test Constants --- TASK_FROM_STREAM = Task( @@ -245,7 +248,9 @@ def jsonrpc_setup(http_base_setup) -> TransportSetup: request_handler=mock_request_handler, rpc_url='/' ) app = Starlette(routes=[*agent_card_routes, *jsonrpc_routes]) - httpx_client = httpx.AsyncClient(transport=httpx.ASGITransport(app=app)) + httpx_client = httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport(app=app) + ) factory = ClientFactory( config=ClientConfig( httpx_client=httpx_client, @@ -265,7 +270,9 @@ def rest_setup(http_base_setup) -> TransportSetup: agent_card=agent_card, card_url='/' ) app = Starlette(routes=[*rest_routes, *agent_card_routes]) - httpx_client = httpx.AsyncClient(transport=httpx.ASGITransport(app=app)) + httpx_client = httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport(app=app) + ) factory = ClientFactory( config=ClientConfig( httpx_client=httpx_client, @@ -718,8 +725,8 @@ async def async_signer(card: AgentCard) -> AgentCard: request_handler=mock_request_handler, rpc_url='/' ) app = Starlette(routes=[*agent_card_routes, *jsonrpc_routes]) - httpx_client = httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), + httpx_client = httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport(app=app), headers={VERSION_HEADER: PROTOCOL_VERSION_CURRENT}, ) @@ -795,8 +802,8 @@ async def get_extended_agent_card_mock_2(*args, **kwargs) -> AgentCard: request_handler=mock_request_handler, rpc_url='/' ) app = Starlette(routes=[*agent_card_routes, *jsonrpc_routes]) - httpx_client = httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), + httpx_client = httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport(app=app), headers={VERSION_HEADER: PROTOCOL_VERSION_CURRENT}, ) @@ -876,8 +883,8 @@ async def async_signer(card: AgentCard) -> AgentCard: request_handler=mock_request_handler, rpc_url='/' ) app = Starlette(routes=[*agent_card_routes, *jsonrpc_routes]) - httpx_client = httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), + httpx_client = httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport(app=app), headers={VERSION_HEADER: PROTOCOL_VERSION_CURRENT}, ) diff --git a/tests/integration/test_copying_observability.py b/tests/integration/test_copying_observability.py index c0d195c08..0a3aa7124 100644 --- a/tests/integration/test_copying_observability.py +++ b/tests/integration/test_copying_observability.py @@ -1,6 +1,5 @@ from typing import NamedTuple -import httpx import pytest from a2a.client.client import Client, ClientConfig @@ -26,9 +25,13 @@ TaskState, ) from a2a.utils import TransportProtocol +from a2a.utils._httpx_compat import httpx_lib from starlette.applications import Starlette +pytestmark = pytest.mark.httpx2 + + class MockMutatingAgentExecutor(AgentExecutor): async def execute(self, context: RequestContext, event_queue: EventQueue): assert context.task_id is not None @@ -113,8 +116,8 @@ def setup_client(agent_card: AgentCard, use_copying: bool) -> ClientSetup: rpc_url='/', ) app = Starlette(routes=[*agent_card_routes, *jsonrpc_routes]) - httpx_client = httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), base_url='http://testserver' + httpx_client = httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport(app=app), base_url='http://testserver' ) factory = ClientFactory( config=ClientConfig( diff --git a/tests/integration/test_end_to_end.py b/tests/integration/test_end_to_end.py index d4276183d..51ba0a9f2 100644 --- a/tests/integration/test_end_to_end.py +++ b/tests/integration/test_end_to_end.py @@ -4,7 +4,6 @@ from typing import NamedTuple import grpc -import httpx import pytest import pytest_asyncio @@ -45,10 +44,14 @@ a2a_pb2_grpc, ) from a2a.utils import TransportProtocol +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.errors import InvalidParamsError from starlette.applications import Starlette +pytestmark = pytest.mark.httpx2 + + SUPPORTED_EXTENSION_URIS = [ 'https://example.com/ext/v1', 'https://example.com/ext/v2', @@ -237,8 +240,8 @@ def rest_setup(agent_card, base_e2e_setup) -> ClientSetup: agent_card=agent_card, card_url='/' ) app = Starlette(routes=[*rest_routes, *agent_card_routes]) - httpx_client = httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), base_url='http://testserver' + httpx_client = httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport(app=app), base_url='http://testserver' ) factory = ClientFactory( config=ClientConfig( @@ -264,8 +267,8 @@ def jsonrpc_setup(agent_card, base_e2e_setup) -> ClientSetup: rpc_url='/', ) app = Starlette(routes=[*agent_card_routes, *jsonrpc_routes]) - httpx_client = httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), base_url='http://testserver' + httpx_client = httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport(app=app), base_url='http://testserver' ) factory = ClientFactory( config=ClientConfig( diff --git a/tests/integration/test_plugins.py b/tests/integration/test_plugins.py index c5f1d47a7..85d6eb879 100644 --- a/tests/integration/test_plugins.py +++ b/tests/integration/test_plugins.py @@ -7,7 +7,6 @@ from typing import Any, NamedTuple import grpc -import httpx import pytest import pytest_asyncio @@ -48,9 +47,13 @@ TaskState, ) from a2a.utils import TransportProtocol +from a2a.utils._httpx_compat import httpx_lib from starlette.applications import Starlette +pytestmark = pytest.mark.httpx2 + + class Recorder(CompletePlugin, ExecutionPlugin, TaskObserverPlugin): """Records hooks and adds an ``x-trace`` header to outgoing calls.""" @@ -214,8 +217,8 @@ async def setup(request) -> AsyncGenerator[Setup, None]: ) else: config = ClientConfig( - httpx_client=httpx.AsyncClient( - transport=httpx.ASGITransport(app=http_app(handler, card)), + httpx_client=httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport(app=http_app(handler, card)), base_url='http://testserver', ), supported_protocol_bindings=[transport], @@ -291,8 +294,8 @@ async def test_v03_jsonrpc_requests_run_server_hooks(): agent_card=agent_card(), plugins=plugins.sequential(recorder), ) - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=http_app(handler, agent_card())), + async with httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport(app=http_app(handler, agent_card())), base_url='http://testserver', ) as http: response = await http.post( @@ -348,8 +351,8 @@ async def test_two_agent_chain_propagates_state_through_execution(): agent_card=agent_card(), plugins=plugins.sequential(downstream), ) - downstream_http = httpx.AsyncClient( - transport=httpx.ASGITransport( + downstream_http = httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport( app=http_app(downstream_handler, agent_card()) ), base_url='http://testserver', @@ -376,8 +379,8 @@ async def cancel(self, context, event_queue): task_store=InMemoryTaskStore(), agent_card=agent_card(), ) - async with httpx.AsyncClient( - transport=httpx.ASGITransport( + async with httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport( app=http_app(upstream_handler, agent_card()) ), base_url='http://testserver', diff --git a/tests/integration/test_samples_smoke.py b/tests/integration/test_samples_smoke.py index fcb49a003..44c550c6c 100644 --- a/tests/integration/test_samples_smoke.py +++ b/tests/integration/test_samples_smoke.py @@ -14,10 +14,17 @@ from pathlib import Path from typing import TYPE_CHECKING -import httpx import pytest import pytest_asyncio +from a2a.utils._httpx_compat import ( + REQUEST_ERROR, + httpx_lib, +) + + +pytestmark = pytest.mark.httpx2 + if TYPE_CHECKING: from collections.abc import AsyncGenerator @@ -41,13 +48,13 @@ def _free_port() -> int: async def _wait_for_agent_card(url: str) -> None: deadline = asyncio.get_running_loop().time() + STARTUP_TIMEOUT_S - async with httpx.AsyncClient(timeout=2.0) as client: + async with httpx_lib.AsyncClient(timeout=2.0) as client: while asyncio.get_running_loop().time() < deadline: try: response = await client.get(url) if response.status_code == 200: return - except httpx.RequestError: + except REQUEST_ERROR: pass await asyncio.sleep(0.2) raise TimeoutError(f'Agent did not become ready at {url}') diff --git a/tests/integration/test_scenarios.py b/tests/integration/test_scenarios.py index 9a51bd1e4..9ba665488 100644 --- a/tests/integration/test_scenarios.py +++ b/tests/integration/test_scenarios.py @@ -7,7 +7,6 @@ from typing import Any, NamedTuple import grpc -import httpx import pytest import pytest_asyncio @@ -54,6 +53,7 @@ TaskStatusUpdateEvent, ) from a2a.utils import TransportProtocol +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.constants import TERMINAL_TASK_STATES from a2a.utils.errors import ( InvalidAgentResponseError, @@ -65,6 +65,9 @@ from starlette.requests import Request +pytestmark = pytest.mark.httpx2 + + logger = logging.getLogger(__name__) @@ -184,14 +187,14 @@ def validate_state(event, expected_state): class RestSetup(NamedTuple): app: Starlette - httpx_client: httpx.AsyncClient + httpx_client: httpx_lib.AsyncClient @pytest_asyncio.fixture(scope='module') async def rest_setup() -> AsyncIterator[RestSetup]: app = Starlette() - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), base_url='http://testserver' + async with httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport(app=app), base_url='http://testserver' ) as httpx_client: yield RestSetup(app, httpx_client) diff --git a/tests/integration/test_stream_generator_cleanup.py b/tests/integration/test_stream_generator_cleanup.py index 3d9b1b171..7ff18356f 100644 --- a/tests/integration/test_stream_generator_cleanup.py +++ b/tests/integration/test_stream_generator_cleanup.py @@ -11,7 +11,6 @@ from typing import Any from uuid import uuid4 -import httpx import pytest from a2a.client.base_client import BaseClient @@ -33,9 +32,13 @@ SendMessageRequest, ) from a2a.utils import TransportProtocol +from a2a.utils._httpx_compat import httpx_lib from starlette.applications import Starlette +pytestmark = pytest.mark.httpx2 + + class _MessageExecutor(AgentExecutor): """Responds with a single Message event.""" @@ -88,8 +91,8 @@ def client(): ) return ClientFactory( config=ClientConfig( - httpx_client=httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), + httpx_client=httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport(app=app), base_url='http://test', ) ) diff --git a/tests/integration/test_tenant.py b/tests/integration/test_tenant.py index 0dc1c1f5e..8ee4db47f 100644 --- a/tests/integration/test_tenant.py +++ b/tests/integration/test_tenant.py @@ -1,6 +1,5 @@ from unittest.mock import AsyncMock, MagicMock, patch -import httpx import pytest from a2a.client import ClientConfig, ClientFactory @@ -19,11 +18,14 @@ SendMessageRequest, Task, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.constants import TransportProtocol -from httpx import ASGITransport, AsyncClient from starlette.applications import Starlette +pytestmark = pytest.mark.httpx2 + + class TestTenantDecorator: @pytest.fixture def agent_card(self): @@ -50,7 +52,7 @@ def agent_card(self): @pytest.mark.asyncio async def test_tenant_decorator_rest(self, agent_card): - mock_httpx = AsyncMock(spec=httpx.AsyncClient) + mock_httpx = AsyncMock(spec=httpx_lib.AsyncClient) mock_httpx.is_closed = False mock_httpx.build_request.return_value = MagicMock() mock_httpx.send.return_value = MagicMock( @@ -86,7 +88,7 @@ async def test_tenant_decorator_rest(self, agent_card): @pytest.mark.asyncio async def test_tenant_decorator_jsonrpc(self, agent_card): - mock_httpx = AsyncMock(spec=httpx.AsyncClient) + mock_httpx = AsyncMock(spec=httpx_lib.AsyncClient) mock_httpx.is_closed = False mock_httpx.build_request.return_value = MagicMock() mock_httpx.send.return_value = MagicMock( @@ -142,7 +144,7 @@ async def test_tenant_decorator_grpc(self, agent_card): @pytest.mark.asyncio async def test_tenant_decorator_explicit_override(self, agent_card): - mock_httpx = AsyncMock(spec=httpx.AsyncClient) + mock_httpx = AsyncMock(spec=httpx_lib.AsyncClient) mock_httpx.is_closed = False mock_httpx.build_request.return_value = MagicMock() mock_httpx.send.return_value = MagicMock( @@ -220,8 +222,8 @@ async def test_jsonrpc_tenant_context_population( """ # 1. Setup the client using the server app as the transport # We use ASGITransport so httpx calls go directly to the Starlette app - transport = ASGITransport(app=server_app) - async with AsyncClient( + transport = httpx_lib.ASGITransport(app=server_app) + async with httpx_lib.AsyncClient( transport=transport, base_url='http://testserver' ) as httpx_client: # Create the A2A client properly configured @@ -255,9 +257,9 @@ async def test_jsonrpc_tenant_context_population( async def test_reused_request_uses_each_clients_default_tenant() -> None: paths: list[str] = [] - async def respond(request: httpx.Request) -> httpx.Response: + async def respond(request: httpx_lib.Request) -> httpx_lib.Response: paths.append(request.url.path) - return httpx.Response( + return httpx_lib.Response( 200, json={ 'id': 'task', @@ -267,8 +269,8 @@ async def respond(request: httpx.Request) -> httpx.Response: ) request = GetTaskRequest(id='task') - async with httpx.AsyncClient( - transport=httpx.MockTransport(respond) + async with httpx_lib.AsyncClient( + transport=httpx_lib.MockTransport(respond) ) as http: factory = ClientFactory( ClientConfig( diff --git a/tests/integration/test_version_header.py b/tests/integration/test_version_header.py index 1e6367097..d2e074926 100644 --- a/tests/integration/test_version_header.py +++ b/tests/integration/test_version_header.py @@ -16,6 +16,9 @@ from starlette.testclient import TestClient +pytestmark = pytest.mark.httpx2 + + class DummyAgentExecutor(AgentExecutor): async def execute( self, context: RequestContext, event_queue: EventQueue diff --git a/tests/server/request_handlers/test_default_request_handler_v2.py b/tests/server/request_handlers/test_default_request_handler_v2.py index 84dd2a6d9..9ac52bc4b 100644 --- a/tests/server/request_handlers/test_default_request_handler_v2.py +++ b/tests/server/request_handlers/test_default_request_handler_v2.py @@ -8,7 +8,6 @@ from datetime import datetime, timezone from unittest.mock import AsyncMock, MagicMock, patch -import httpx import pytest from a2a.auth.user import UnauthenticatedUser, User @@ -73,9 +72,13 @@ TaskStatus, TaskStatusUpdateEvent, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.constants import TERMINAL_TASK_STATES +pytestmark = pytest.mark.httpx2 + + def create_default_agent_card(): """Provides a standard AgentCard with streaming and push notifications enabled for tests.""" return AgentCard( @@ -3224,7 +3227,7 @@ async def test_push_config_store_failure_does_not_fail_task(): task_store=task_store, push_config_store=FlakyPushConfigStore(), push_sender=BasePushNotificationSender( - httpx_client=AsyncMock(spec=httpx.AsyncClient), + httpx_client=AsyncMock(spec=httpx_lib.AsyncClient), config_store=FlakyPushConfigStore(), ), agent_card=create_default_agent_card(), diff --git a/tests/server/request_handlers/test_default_request_handler_v2_plugins.py b/tests/server/request_handlers/test_default_request_handler_v2_plugins.py index fd0c6dbde..3fdc194f7 100644 --- a/tests/server/request_handlers/test_default_request_handler_v2_plugins.py +++ b/tests/server/request_handlers/test_default_request_handler_v2_plugins.py @@ -5,7 +5,6 @@ from collections.abc import Callable from typing import Any -import httpx import pytest from a2a import plugins @@ -56,6 +55,13 @@ TaskState, TaskStatus, ) +from a2a.utils._httpx_compat import ( + HTTP_STATUS_ERROR, + httpx_lib, +) + + +pytestmark = pytest.mark.httpx2 CARD = AgentCard( @@ -573,17 +579,17 @@ def push_setup( ) -> tuple[ InMemoryPushNotificationConfigStore, BasePushNotificationSender, - list[httpx.Request], + list[httpx_lib.Request], ]: - received: list[httpx.Request] = [] + received: list[httpx_lib.Request] = [] - def handle(request: httpx.Request) -> httpx.Response: + def handle(request: httpx_lib.Request) -> httpx_lib.Response: received.append(request) - return httpx.Response(responses.get(str(request.url), 200)) + return httpx_lib.Response(responses.get(str(request.url), 200)) config_store = InMemoryPushNotificationConfigStore() sender = BasePushNotificationSender( - httpx.AsyncClient(transport=httpx.MockTransport(handle)), + httpx_lib.AsyncClient(transport=httpx_lib.MockTransport(handle)), config_store, plugins=manager, ) @@ -630,7 +636,7 @@ async def test_push_hooks_run_for_v2_deliveries(): await wait_for(lambda: len(recorder.hooks('on_push_sent')) >= 1) failed = recorder.hooks('on_push_sent')[0] assert failed.status_code == 500 - assert isinstance(failed.error, httpx.HTTPStatusError) + assert isinstance(failed.error, HTTP_STATUS_ERROR) @pytest.mark.asyncio @@ -677,13 +683,13 @@ async def test_push_url_validator_rejection_runs_no_hooks(): async def reject(url: str) -> bool: return False - received: list[httpx.Request] = [] + received: list[httpx_lib.Request] = [] recorder = Recorder() config_store = InMemoryPushNotificationConfigStore() sender = BasePushNotificationSender( - httpx.AsyncClient( - transport=httpx.MockTransport( - lambda r: received.append(r) or httpx.Response(200) + httpx_lib.AsyncClient( + transport=httpx_lib.MockTransport( + lambda r: received.append(r) or httpx_lib.Response(200) ) ), config_store, @@ -735,10 +741,10 @@ def test_push_sender_uses_global_manager_unless_given_one(): other = plugins.sequential() default = BasePushNotificationSender( - httpx.AsyncClient(), InMemoryPushNotificationConfigStore() + httpx_lib.AsyncClient(), InMemoryPushNotificationConfigStore() ) explicit = BasePushNotificationSender( - httpx.AsyncClient(), + httpx_lib.AsyncClient(), InMemoryPushNotificationConfigStore(), plugins=other, ) diff --git a/tests/server/routes/test_agent_card_routes.py b/tests/server/routes/test_agent_card_routes.py index f3cb03ed6..e8c73d960 100644 --- a/tests/server/routes/test_agent_card_routes.py +++ b/tests/server/routes/test_agent_card_routes.py @@ -19,6 +19,9 @@ from starlette.testclient import TestClient +pytestmark = pytest.mark.httpx2 + + @pytest.fixture def agent_card(): return AgentCard() diff --git a/tests/server/routes/test_fastapi_routes.py b/tests/server/routes/test_fastapi_routes.py index 817862039..4ce79ebb1 100644 --- a/tests/server/routes/test_fastapi_routes.py +++ b/tests/server/routes/test_fastapi_routes.py @@ -27,6 +27,9 @@ from fastapi.testclient import TestClient # noqa: E402 +pytestmark = pytest.mark.httpx2 + + @pytest.fixture def agent_card() -> AgentCard: return AgentCard(name='Test Agent', version='1.0.0') diff --git a/tests/server/routes/test_jsonrpc_dispatcher.py b/tests/server/routes/test_jsonrpc_dispatcher.py index 324d19327..1b2a25db7 100644 --- a/tests/server/routes/test_jsonrpc_dispatcher.py +++ b/tests/server/routes/test_jsonrpc_dispatcher.py @@ -38,6 +38,9 @@ ) +pytestmark = pytest.mark.httpx2 + + # --- JsonRpcDispatcher Tests --- diff --git a/tests/server/routes/test_jsonrpc_routes.py b/tests/server/routes/test_jsonrpc_routes.py index 4c25873a9..7a795cebd 100644 --- a/tests/server/routes/test_jsonrpc_routes.py +++ b/tests/server/routes/test_jsonrpc_routes.py @@ -9,6 +9,9 @@ from starlette.testclient import TestClient +pytestmark = pytest.mark.httpx2 + + @pytest.fixture def agent_card(): return AgentCard() diff --git a/tests/server/routes/test_rest_dispatcher.py b/tests/server/routes/test_rest_dispatcher.py index 3d7bb3986..5111831a7 100644 --- a/tests/server/routes/test_rest_dispatcher.py +++ b/tests/server/routes/test_rest_dispatcher.py @@ -3,7 +3,6 @@ from collections.abc import AsyncIterator from unittest.mock import AsyncMock, MagicMock -import httpx import pytest from a2a.server.context import ServerCallContext @@ -24,6 +23,7 @@ Task, TaskPushNotificationConfig, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.errors import ( UnsupportedOperationError, ) @@ -81,6 +81,9 @@ def rest_dispatcher_instance(mock_handler): from starlette.datastructures import Headers, QueryParams +pytestmark = pytest.mark.httpx2 + + def make_mock_request( method: str = 'GET', path_params: dict | None = None, @@ -333,8 +336,8 @@ async def test_list_tasks_rejects_invalid_boolean_query( self, mock_handler: AsyncMock, value: str ) -> None: app = Starlette(routes=create_rest_routes(mock_handler)) - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), + async with httpx_lib.AsyncClient( + transport=httpx_lib.ASGITransport(app=app), base_url='http://test', trust_env=False, ) as client: diff --git a/tests/server/routes/test_rest_routes.py b/tests/server/routes/test_rest_routes.py index a0450b2b0..e17f4021a 100644 --- a/tests/server/routes/test_rest_routes.py +++ b/tests/server/routes/test_rest_routes.py @@ -10,6 +10,9 @@ from starlette.testclient import TestClient +pytestmark = pytest.mark.httpx2 + + @pytest.fixture def agent_card(): return AgentCard() diff --git a/tests/server/tasks/test_inmemory_push_notifications.py b/tests/server/tasks/test_inmemory_push_notifications.py index 8acae7d9d..eed1b21f8 100644 --- a/tests/server/tasks/test_inmemory_push_notifications.py +++ b/tests/server/tasks/test_inmemory_push_notifications.py @@ -5,7 +5,7 @@ from unittest.mock import AsyncMock, MagicMock, patch -import httpx +import pytest from a2a.auth.user import User from a2a.server.context import ServerCallContext @@ -22,9 +22,13 @@ TaskState, TaskStatus, ) +from a2a.utils._httpx_compat import httpx_lib from google.protobuf.json_format import MessageToDict +pytestmark = pytest.mark.httpx2 + + # Suppress logging for cleaner test output, can be enabled for debugging # logging.disable(logging.CRITICAL) @@ -94,7 +98,7 @@ def _set_info_in_thread( class TestInMemoryPushNotifier(unittest.IsolatedAsyncioTestCase): def setUp(self) -> None: - self.mock_httpx_client = AsyncMock(spec=httpx.AsyncClient) + self.mock_httpx_client = AsyncMock(spec=httpx_lib.AsyncClient) self.config_store = InMemoryPushNotificationConfigStore() self.notifier = BasePushNotificationSender( httpx_client=self.mock_httpx_client, @@ -248,7 +252,7 @@ async def test_send_notification_success(self) -> None: await self.config_store.set_info(task_id, config, MINIMAL_CALL_CONTEXT) # Mock the post call to simulate success - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 200 self.mock_httpx_client.post.return_value = mock_response @@ -275,7 +279,7 @@ async def test_send_notification_with_token_success(self) -> None: await self.config_store.set_info(task_id, config, MINIMAL_CALL_CONTEXT) # Mock the post call to simulate success - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 200 self.mock_httpx_client.post.return_value = mock_response @@ -315,11 +319,11 @@ async def test_send_notification_http_status_error( await self.config_store.set_info(task_id, config, MINIMAL_CALL_CONTEXT) mock_response = MagicMock( - spec=httpx.Response + spec=httpx_lib.Response ) # Use MagicMock for status_code attribute mock_response.status_code = 404 mock_response.text = 'Not Found' - http_error = httpx.HTTPStatusError( + http_error = httpx_lib.HTTPStatusError( 'Not Found', request=MagicMock(), response=mock_response ) self.mock_httpx_client.post.side_effect = http_error @@ -344,7 +348,9 @@ async def test_send_notification_request_error( config = _create_sample_push_config(url='http://notify.me/req_error') await self.config_store.set_info(task_id, config, MINIMAL_CALL_CONTEXT) - request_error = httpx.RequestError('Network issue', request=MagicMock()) + request_error = httpx_lib.RequestError( + 'Network issue', request=MagicMock() + ) self.mock_httpx_client.post.side_effect = request_error await self.notifier.send_notification(task_id, task_data) @@ -373,7 +379,7 @@ async def test_send_notification_with_auth( # It only supports token-based auth via the token field await self.config_store.set_info(task_id, config, MINIMAL_CALL_CONTEXT) - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 200 self.mock_httpx_client.post.return_value = mock_response @@ -553,8 +559,8 @@ class TestPushNotificationDispatchAcrossOwners( """ def setUp(self) -> None: - self.mock_httpx_client = AsyncMock(spec=httpx.AsyncClient) - mock_response = AsyncMock(spec=httpx.Response) + self.mock_httpx_client = AsyncMock(spec=httpx_lib.AsyncClient) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 200 self.mock_httpx_client.post.return_value = mock_response diff --git a/tests/server/tasks/test_push_notification_sender.py b/tests/server/tasks/test_push_notification_sender.py index 4772581b7..5375c2c4b 100644 --- a/tests/server/tasks/test_push_notification_sender.py +++ b/tests/server/tasks/test_push_notification_sender.py @@ -3,7 +3,7 @@ from unittest.mock import AsyncMock, MagicMock, patch -import httpx +import pytest from a2a.server.tasks.base_push_notification_sender import ( BasePushNotificationSender, @@ -18,10 +18,14 @@ TaskStatus, TaskStatusUpdateEvent, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.push_url_validator import validate_push_notification_url from google.protobuf.json_format import MessageToDict +pytestmark = pytest.mark.httpx2 + + def _create_sample_task( task_id: str = 'task123', status_state: TaskState = TaskState.TASK_STATE_COMPLETED, @@ -46,7 +50,7 @@ def _create_sample_push_config( class TestBasePushNotificationSender(unittest.IsolatedAsyncioTestCase): def setUp(self) -> None: - self.mock_httpx_client = AsyncMock(spec=httpx.AsyncClient) + self.mock_httpx_client = AsyncMock(spec=httpx_lib.AsyncClient) self.mock_config_store = AsyncMock() self.sender = BasePushNotificationSender( httpx_client=self.mock_httpx_client, @@ -63,7 +67,7 @@ async def test_send_notification_success(self) -> None: config = _create_sample_push_config(url='http://notify.me/here') self.mock_config_store.get_info_for_dispatch.return_value = [config] - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 200 self.mock_httpx_client.post.return_value = mock_response @@ -89,7 +93,7 @@ async def test_send_notification_with_token_success(self) -> None: ) self.mock_config_store.get_info_for_dispatch.return_value = [config] - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 200 self.mock_httpx_client.post.return_value = mock_response @@ -114,7 +118,7 @@ async def _post_headers_for(self, **config_kwargs) -> dict[str, str] | None: _create_sample_push_config(**config_kwargs) ] self.mock_httpx_client.post.return_value = AsyncMock( - spec=httpx.Response, status_code=200 + spec=httpx_lib.Response, status_code=200 ) await self.sender.send_notification(task_data.id, task_data) @@ -206,10 +210,10 @@ async def test_send_notification_http_status_error( config = _create_sample_push_config(url='http://notify.me/http_error') self.mock_config_store.get_info_for_dispatch.return_value = [config] - mock_response = MagicMock(spec=httpx.Response) + mock_response = MagicMock(spec=httpx_lib.Response) mock_response.status_code = 404 mock_response.text = 'Not Found' - http_error = httpx.HTTPStatusError( + http_error = httpx_lib.HTTPStatusError( 'Not Found', request=MagicMock(), response=mock_response ) self.mock_httpx_client.post.side_effect = http_error @@ -240,7 +244,7 @@ async def test_send_notification_multiple_configs(self) -> None: config2, ] - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 200 self.mock_httpx_client.post.return_value = mock_response @@ -274,7 +278,7 @@ async def test_send_notification_status_update_event(self) -> None: config = _create_sample_push_config(url='http://notify.me/status') self.mock_config_store.get_info_for_dispatch.return_value = [config] - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 200 self.mock_httpx_client.post.return_value = mock_response @@ -298,7 +302,7 @@ async def test_send_notification_artifact_update_event(self) -> None: config = _create_sample_push_config(url='http://notify.me/artifact') self.mock_config_store.get_info_for_dispatch.return_value = [config] - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 200 self.mock_httpx_client.post.return_value = mock_response @@ -363,7 +367,7 @@ class TestPushUrlValidation(unittest.IsolatedAsyncioTestCase): push URLs must not reach non-public destinations.""" def setUp(self) -> None: - self.mock_httpx_client = AsyncMock(spec=httpx.AsyncClient) + self.mock_httpx_client = AsyncMock(spec=httpx_lib.AsyncClient) self.mock_config_store = AsyncMock() self.sender = BasePushNotificationSender( httpx_client=self.mock_httpx_client, @@ -375,7 +379,7 @@ async def _dispatch(self, url: str) -> None: task = _create_sample_task() config = _create_sample_push_config(url=url) self.mock_config_store.get_info_for_dispatch.return_value = [config] - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 200 self.mock_httpx_client.post.return_value = mock_response await self.sender.send_notification(task.id, task) @@ -441,7 +445,7 @@ async def test_default_hook_none_skips_validation(self) -> None: task = _create_sample_task() config = _create_sample_push_config(url='http://localhost:9000/hook') self.mock_config_store.get_info_for_dispatch.return_value = [config] - mock_response = AsyncMock(spec=httpx.Response) + mock_response = AsyncMock(spec=httpx_lib.Response) mock_response.status_code = 200 self.mock_httpx_client.post.return_value = mock_response await sender.send_notification(task.id, task) diff --git a/tests/server/test_integration.py b/tests/server/test_integration.py index c82fd6c99..0562e90ec 100644 --- a/tests/server/test_integration.py +++ b/tests/server/test_integration.py @@ -97,6 +97,9 @@ from google.protobuf.struct_pb2 import Struct, Value +pytestmark = pytest.mark.httpx2 + + TEXT_PART_DATA = Part(text='Hello') # For proto, Part.data takes a Value(struct_value=Struct) diff --git a/tests/utils/test_proto_utils.py b/tests/utils/test_proto_utils.py index 985dfc78e..8978c844d 100644 --- a/tests/utils/test_proto_utils.py +++ b/tests/utils/test_proto_utils.py @@ -7,7 +7,6 @@ from typing import Any, cast -import httpx import pytest from a2a.types.a2a_pb2 import ( @@ -24,6 +23,7 @@ TaskStatusUpdateEvent, ) from a2a.utils import proto_utils +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.errors import InvalidParamsError from google.protobuf.descriptor import FieldDescriptor from google.protobuf.json_format import MessageToDict, Parse, ParseError @@ -32,6 +32,9 @@ from starlette.datastructures import QueryParams +pytestmark = pytest.mark.httpx2 + + class TestToStreamResponse: """Tests for to_stream_response function.""" @@ -317,7 +320,7 @@ def test_repeated_fields_parsing(self, query_string: str): def _message_to_rest_params(self, message: ProtobufMessage) -> QueryParams: """Converts a message to REST query parameters.""" rest_dict = MessageToDict(message) - return httpx.Request( + return httpx_lib.Request( 'GET', 'http://api.example.com', params=rest_dict ).url.params diff --git a/uv.lock b/uv.lock index 3440dea59..cd3b23a50 100644 --- a/uv.lock +++ b/uv.lock @@ -4,7 +4,8 @@ requires-python = ">=3.10" resolution-markers = [ "python_full_version >= '3.14'", "python_full_version == '3.13.*'", - "python_full_version >= '3.11' and python_full_version < '3.13'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.11.*' or (python_full_version == '3.12.*' and sys_platform != 'emscripten')", "python_full_version < '3.11'", ] @@ -105,6 +106,9 @@ dev = [ { name = "uv-dynamic-versioning" }, { name = "uvicorn" }, ] +httpx2 = [ + { name = "httpx2", marker = "python_full_version >= '3.11'" }, +] [package.metadata] requires-dist = [ @@ -174,6 +178,7 @@ dev = [ { name = "uv-dynamic-versioning", specifier = ">=0.8.2" }, { name = "uvicorn", specifier = ">=0.35.0" }, ] +httpx2 = [{ name = "httpx2", marker = "python_full_version >= '3.11'", specifier = ">=2.0.0,<3" }] [[package]] name = "aiologic" @@ -251,7 +256,8 @@ version = "4.14.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, - { name = "idna" }, + { name = "idna", version = "3.15", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "idna", version = "3.20", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "typing-extensions", version = "4.15.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' and python_full_version < '3.13'" }, { name = "typing-extensions", version = "4.16.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, ] @@ -1129,6 +1135,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, ] +[[package]] +name = "httpcore2" +version = "2.16.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "h11" }, + { name = "truststore" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c0/61/afa9d6b7452f9eca73f73d45324eb0bb52f098fd5e6049bf6b8263be9b4e/httpcore2-2.16.0.tar.gz", hash = "sha256:c72cd0413563b17e1cd8354677dff887466f8ec2551679759e93126534428643", size = 69886, upload-time = "2026-10-21T07:09:45.31Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/af/c2/ce417c397afa5181f0e3c6ff01a4d01639414e1adef08730d97571297151/httpcore2-2.16.0-py3-none-any.whl", hash = "sha256:5c4358319f2602d984ad93182c9fee5160f22e9da7babdda870a5e7c4e2dc34f", size = 85070, upload-time = "2026-10-21T07:09:42.802Z" }, +] + [[package]] name = "httpx" version = "0.28.1" @@ -1137,7 +1156,8 @@ dependencies = [ { name = "anyio" }, { name = "certifi" }, { name = "httpcore" }, - { name = "idna" }, + { name = "idna", version = "3.15", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "idna", version = "3.20", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } wheels = [ @@ -1153,6 +1173,32 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d2/fd/6668e5aec43ab844de6fc74927e155a3b37bf40d7c3790e49fc0406b6578/httpx_sse-0.4.3-py3-none-any.whl", hash = "sha256:0ac1c9fe3c0afad2e0ebb25a934a59f4c7823b60792691f779fad2c5568830fc", size = 8960, upload-time = "2025-10-10T21:48:21.158Z" }, ] +[[package]] +name = "httpx2" +version = "2.16.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio", marker = "sys_platform != 'emscripten'" }, + { name = "httpcore2", marker = "sys_platform != 'emscripten'" }, + { name = "httpx2-jsfetch", marker = "python_full_version >= '3.12' and sys_platform == 'emscripten'" }, + { name = "idna", version = "3.20", source = { registry = "https://pypi.org/simple" } }, + { name = "truststore", marker = "sys_platform != 'emscripten'" }, + { name = "typing-extensions", version = "4.15.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/43/73/5ca2cedf5e4e50423d1c258877865a6b62793633b561c58499f8aeb33b7e/httpx2-2.16.0.tar.gz", hash = "sha256:0d54c98128e8f2ff7fbbde0fca8c359e5f032edeaaaac443cdb7f31f685bcd7f", size = 103116, upload-time = "2026-10-21T07:09:46.348Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7b/3d/2e4bc4fd1ef9770871669adb348d612a6e4786b303a23f9935b81c48dd60/httpx2-2.16.0-py3-none-any.whl", hash = "sha256:fd2c5d7909e8d86fe92d53020c310ca0e4e431b838c207c5754b9bbf0308d49a", size = 97880, upload-time = "2026-10-21T07:09:44.01Z" }, +] + +[[package]] +name = "httpx2-jsfetch" +version = "1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/c4/0e5636363151a2a1795e0a77617168b9ca438e1748ec05fc9b5687f93d64/httpx2_jsfetch-1.0.tar.gz", hash = "sha256:70a0e3eabfef7cce5ad9c629f7d01ca05e418f586646f4ddf14782e4c1454c60", size = 6872, upload-time = "2026-08-07T00:13:07.492Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9b/43/832f631d32e4f1211caa2ba368317739fe71f0b8530e4c9d15dc454bac2a/httpx2_jsfetch-1.0-py3-none-any.whl", hash = "sha256:cb916b707601e69a07721aabc8f3f6659be3a6893bc1ff5c6f9e02241df2da32", size = 6382, upload-time = "2026-08-07T00:13:06.567Z" }, +] + [[package]] name = "identify" version = "2.6.18" @@ -1166,11 +1212,29 @@ wheels = [ name = "idna" version = "3.15" source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] sdist = { url = "https://files.pythonhosted.org/packages/82/77/7b3966d0b9d1d31a36ddf1746926a11dface89a83409bf1483f0237aa758/idna-3.15.tar.gz", hash = "sha256:ca962446ea538f7092a95e057da437618e886f4d349216d2b1e294abfdb65fdc", size = 199245, upload-time = "2026-05-12T22:45:57.011Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/d2/23/408243171aa9aaba178d3e2559159c24c1171a641aa83b67bdd3394ead8e/idna-3.15-py3-none-any.whl", hash = "sha256:048adeaf8c2d788c40fee287673ccaa74c24ffd8dcf09ffa555a2fbb59f10ac8", size = 72340, upload-time = "2026-05-12T22:45:55.733Z" }, ] +[[package]] +name = "idna" +version = "3.20" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.14'", + "python_full_version == '3.13.*'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.11.*' or (python_full_version == '3.12.*' and sys_platform != 'emscripten')", +] +sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, +] + [[package]] name = "iniconfig" version = "2.3.0" @@ -1829,7 +1893,8 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "certifi" }, { name = "charset-normalizer" }, - { name = "idna" }, + { name = "idna", version = "3.15", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "idna", version = "3.20", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "urllib3" }, ] sdist = { url = "https://files.pythonhosted.org/packages/34/64/8860370b167a9721e8956ae116825caff829224fbca0ca6e7bf8ddef8430/requests-2.33.0.tar.gz", hash = "sha256:c7ebc5e8b0f21837386ad0e1c8fe8b829fa5f544d8df3b2253bff14ef29d7652", size = 134232, upload-time = "2026-03-25T15:10:41.586Z" } @@ -2088,7 +2153,8 @@ dependencies = [ { name = "attrs" }, { name = "cffi", marker = "implementation_name != 'pypy' and os_name == 'nt'" }, { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, - { name = "idna" }, + { name = "idna", version = "3.15", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "idna", version = "3.20", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "outcome" }, { name = "sniffio" }, { name = "sortedcontainers" }, @@ -2107,6 +2173,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/bb/4a/2e5583e544bc437d5e8e54b47db87430df9031b29b48d17f26d129fa60c0/trove_classifiers-2026.1.14.14-py3-none-any.whl", hash = "sha256:1f9553927f18d0513d8e5ff80ab8980b8202ce37ecae0e3274ed2ef11880e74d", size = 14197, upload-time = "2026-01-14T14:54:49.067Z" }, ] +[[package]] +name = "truststore" +version = "0.10.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ee/9f/c5201d42a484c061e528825fc8e2d565f5abd50a4ced6fb7d29c4ec99b2b/truststore-0.10.5.tar.gz", hash = "sha256:30d36967ccaded5cbb38d602c433f53600036c79d502f4533a49b60a03bbefcd", size = 28091, upload-time = "2026-10-12T22:27:31.808Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/e9/3a7820be2bb0fe53b6bc9c3be26d3d1158004e4c3ab953aa6840b955b1e9/truststore-0.10.5-py3-none-any.whl", hash = "sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951c", size = 19017, upload-time = "2026-10-12T22:27:30.377Z" }, +] + [[package]] name = "ty" version = "0.0.44" @@ -2160,7 +2235,8 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.14'", "python_full_version == '3.13.*'", - "python_full_version >= '3.11' and python_full_version < '3.13'", + "python_full_version == '3.12.*' and sys_platform == 'emscripten'", + "python_full_version == '3.11.*' or (python_full_version == '3.12.*' and sys_platform != 'emscripten')", ] sdist = { url = "https://files.pythonhosted.org/packages/72/94/1a15dd82efb362ac84269196e94cf00f187f7ed21c242792a923cdb1c61f/typing_extensions-4.15.0.tar.gz", hash = "sha256:0cea48d173cc12fa28ecabc3b837ea3cf6f38c6d1136f85cbaaf598984861466", size = 109391, upload-time = "2025-08-25T13:49:26.313Z" } wheels = [