From 3d63bf19c399716fd2ce6a47dcf61df95c6f74f7 Mon Sep 17 00:00:00 2001 From: Iwaniukooo11 Date: Wed, 4 Nov 2026 16:24:41 +0000 Subject: [PATCH 1/9] feat: add compatibility layer to support both httpx and httpx2 clients --- src/a2a/client/card_resolver.py | 16 +++-- src/a2a/client/client.py | 5 +- src/a2a/client/client_factory.py | 3 +- src/a2a/client/transports/http_helpers.py | 46 ++++++------ src/a2a/client/transports/jsonrpc.py | 5 +- src/a2a/client/transports/rest.py | 7 +- src/a2a/compat/v0_3/jsonrpc_transport.py | 7 +- src/a2a/compat/v0_3/rest_transport.py | 22 ++++-- .../tasks/base_push_notification_sender.py | 5 +- src/a2a/utils/_httpx_compat.py | 70 +++++++++++++++++++ 10 files changed, 135 insertions(+), 51 deletions(-) create mode 100644 src/a2a/utils/_httpx_compat.py 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 bda7bd29e..64f5081fe 100644 --- a/src/a2a/client/transports/http_helpers.py +++ b/src/a2a/client/transports/http_helpers.py @@ -4,10 +4,17 @@ from contextlib import contextmanager from typing import Any, NoReturn -import httpx - 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: @@ -16,25 +23,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 @@ -51,10 +57,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: @@ -66,9 +71,9 @@ async def send_http_request( 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. """ @@ -106,11 +111,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]: @@ -135,7 +139,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() @@ -174,7 +178,7 @@ class _SSEEventSource: def __init__( self, - client: httpx.AsyncClient, + client: AsyncClient, method: str, url: str, **kwargs: Any, @@ -189,9 +193,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 ba1f4c098..6892d93b9 100644 --- a/src/a2a/client/transports/rest.py +++ b/src/a2a/client/transports/rest.py @@ -34,6 +34,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 @@ -95,7 +96,7 @@ class RestTransport(ClientTransport): def __init__( self, - httpx_client: httpx.AsyncClient, + httpx_client: AsyncClient, agent_card: AgentCard, url: str, is_shared_httpx: bool = False, @@ -351,7 +352,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() @@ -401,7 +402,7 @@ async def _send_stream_request( event: StreamResponse = parse_lenient(sse_data, StreamResponse()) yield event - 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 362946736..bb55932d9 100644 --- a/src/a2a/compat/v0_3/rest_transport.py +++ b/src/a2a/compat/v0_3/rest_transport.py @@ -44,6 +44,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.telemetry import SpanKind, trace_class @@ -62,7 +70,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, @@ -299,10 +307,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: @@ -355,15 +363,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 = {} @@ -415,7 +423,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..04d1e0cd0 --- /dev/null +++ b/src/a2a/utils/_httpx_compat.py @@ -0,0 +1,70 @@ +"""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. +""" + +import httpx + + +# Declare catch-tuple types explicitly so conditional assignment doesn't widen +# them to `BaseException` + the types are open gor httpx2 errors. +HTTP_STATUS_ERROR: tuple[type[httpx.HTTPStatusError], ...] +REQUEST_ERROR: tuple[type[httpx.RequestError], ...] +TIMEOUT_EXCEPTION: tuple[type[httpx.TimeoutException], ...] +STREAM_CLOSED: tuple[type[httpx.StreamClosed], ...] +RESPONSE_NOT_READ: tuple[type[httpx.ResponseNotRead], ...] + +try: + import httpx2 # ty: ignore[unresolved-import] + + 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, + ) + + AsyncClient = httpx.AsyncClient | httpx2.AsyncClient + Request = httpx.Request | httpx2.Request + Response = httpx.Response | httpx2.Response + HTTPStatusError = httpx.HTTPStatusError | httpx2.HTTPStatusError +except ImportError: + HTTP_STATUS_ERROR = (httpx.HTTPStatusError,) + REQUEST_ERROR = (httpx.RequestError,) + TIMEOUT_EXCEPTION = (httpx.TimeoutException,) + STREAM_CLOSED = (httpx.StreamClosed,) + RESPONSE_NOT_READ = (httpx.ResponseNotRead,) + + AsyncClient = httpx.AsyncClient + Request = httpx.Request + Response = httpx.Response + HTTPStatusError = httpx.HTTPStatusError + + +__all__ = [ + 'HTTP_STATUS_ERROR', + 'REQUEST_ERROR', + 'RESPONSE_NOT_READ', + 'STREAM_CLOSED', + 'TIMEOUT_EXCEPTION', + 'AsyncClient', + 'HTTPStatusError', + 'Request', + 'Response', +] From beb86d711b0f3c041e64fa3b7b21d53bdf49e486 Mon Sep 17 00:00:00 2001 From: Iwaniukooo11 Date: Mon, 9 Nov 2026 13:28:21 +0000 Subject: [PATCH 2/9] test: add tests for httpx compat --- src/a2a/utils/_httpx_compat.py | 5 ++ tests/client/test_base_client_plugins.py | 8 +-- tests/client/test_card_resolver.py | 32 ++++----- tests/client/test_client_factory.py | 22 +++--- tests/client/transports/test_http_helpers.py | 18 ++--- .../client/transports/test_jsonrpc_client.py | 34 ++++----- tests/client/transports/test_rest_client.py | 72 +++++++++---------- tests/compat/v0_3/test_jsonrpc_transport.py | 14 ++-- tests/compat/v0_3/test_rest_routes_compat.py | 24 +++---- tests/compat/v0_3/test_rest_transport.py | 58 +++++++-------- .../push_notifications/agent_app.py | 7 +- .../test_default_push_notification_support.py | 26 +++---- tests/integration/push_notifications/utils.py | 7 +- tests/integration/test_agent_card.py | 6 +- .../test_client_server_integration.py | 22 +++--- .../integration/test_copying_observability.py | 6 +- tests/integration/test_end_to_end.py | 10 +-- tests/integration/test_plugins.py | 18 ++--- tests/integration/test_samples_smoke.py | 10 ++- tests/integration/test_scenarios.py | 8 +-- .../test_stream_generator_cleanup.py | 6 +- tests/integration/test_tenant.py | 15 ++-- .../test_default_request_handler_v2.py | 4 +- ...test_default_request_handler_v2_plugins.py | 29 ++++---- tests/server/routes/test_rest_dispatcher.py | 6 +- .../tasks/test_inmemory_push_notifications.py | 23 +++--- .../tasks/test_push_notification_sender.py | 27 ++++--- tests/utils/test_proto_utils.py | 4 +- 28 files changed, 269 insertions(+), 252 deletions(-) diff --git a/src/a2a/utils/_httpx_compat.py b/src/a2a/utils/_httpx_compat.py index 04d1e0cd0..23c42ceb1 100644 --- a/src/a2a/utils/_httpx_compat.py +++ b/src/a2a/utils/_httpx_compat.py @@ -19,6 +19,8 @@ try: import httpx2 # ty: ignore[unresolved-import] + httpx_lib = httpx2 + HTTP_STATUS_ERROR = ( httpx.HTTPStatusError, httpx2.HTTPStatusError, @@ -45,6 +47,8 @@ Response = httpx.Response | httpx2.Response HTTPStatusError = httpx.HTTPStatusError | httpx2.HTTPStatusError except ImportError: + httpx_lib = httpx + HTTP_STATUS_ERROR = (httpx.HTTPStatusError,) REQUEST_ERROR = (httpx.RequestError,) TIMEOUT_EXCEPTION = (httpx.TimeoutException,) @@ -67,4 +71,5 @@ 'HTTPStatusError', 'Request', 'Response', + 'httpx_lib', ] diff --git a/tests/client/test_base_client_plugins.py b/tests/client/test_base_client_plugins.py index 2704f9291..ab05b41d5 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,7 @@ TaskStatus, TaskStatusUpdateEvent, ) +from a2a.utils._httpx_compat import httpx_lib class Recorder(plugins.ClientPlugin): @@ -312,9 +312,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..dd2b96e15 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,14 @@ 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 @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 +57,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 +198,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 +249,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 +281,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 +329,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 +370,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 +445,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 +473,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..1ec4e1ebc 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,6 +19,7 @@ AgentCard, AgentInterface, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.constants import ( TransportProtocol, ) @@ -48,7 +48,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 +73,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 +105,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 +139,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 +151,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 +200,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 +227,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 +360,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 +402,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 +433,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/transports/test_http_helpers.py b/tests/client/transports/test_http_helpers.py index ddda42adb..64e8b3492 100644 --- a/tests/client/transports/test_http_helpers.py +++ b/tests/client/transports/test_http_helpers.py @@ -1,4 +1,3 @@ -import httpx import pytest from a2a.client.client import ClientCallContext @@ -10,6 +9,7 @@ parse_sse_stream, send_http_stream_request, ) +from a2a.utils._httpx_compat import httpx_lib def test_default_sse_error_handler(): @@ -31,7 +31,7 @@ async def mock_aiter_lines(): yield 'data: \n' yield '\n' - response = httpx.Response(200) + response = httpx_lib.Response(200) response.aiter_lines = mock_aiter_lines # type: ignore events = [e async for e in parse_sse_stream(response)] @@ -43,9 +43,9 @@ async def mock_aiter_lines(): @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', @@ -72,9 +72,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'] == { @@ -86,7 +86,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' @@ -104,7 +104,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 493d99d48..1eff9d2c7 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 httpx_lib.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 @@ -185,7 +185,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 +197,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 +448,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_lines.return_value = async_iterable_from_list( @@ -472,10 +472,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_lines.side_effect = httpx.RequestError( + mock_response.aiter_lines.side_effect = httpx_lib.RequestError( 'Simulated request error', request=MagicMock() ) mock_aconnect_sse.return_value.__aenter__.return_value = mock_response @@ -492,10 +492,10 @@ 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_lines.side_effect = httpx.TimeoutException( + mock_response.aiter_lines.side_effect = httpx_lib.TimeoutException( 'Timeout' ) mock_aconnect_sse.return_value.__aenter__.return_value = mock_response @@ -573,12 +573,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_lines.return_value = async_iterable_from_list([]) @@ -810,7 +810,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_lines.return_value = async_iterable_from_list( @@ -948,7 +948,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_lines.return_value = async_iterable_from_list(lines) diff --git a/tests/client/transports/test_rest_client.py b/tests/client/transports/test_rest_client.py index 558a21a8c..586b4b28e 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 from a2a.client.client import ClientCallContext @@ -27,6 +26,7 @@ TaskPushNotificationConfig, TaskState, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.constants import TransportProtocol from a2a.utils.errors import A2A_ERROR_MAPPING, MethodNotFoundError from google.protobuf import json_format @@ -35,7 +35,7 @@ @pytest.fixture def mock_httpx_client() -> AsyncMock: - client = AsyncMock(spec=httpx.AsyncClient) + client = AsyncMock(spec=httpx_lib.AsyncClient) client.is_closed = False return client @@ -87,10 +87,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_lines.side_effect = httpx.TimeoutException( + mock_response.aiter_lines.side_effect = httpx_lib.TimeoutException( 'Read timed out' ) mock_aconnect_sse.return_value.__aenter__.return_value = mock_response @@ -120,11 +120,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] @@ -145,9 +145,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, ) @@ -180,12 +180,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, ) @@ -207,11 +207,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_httpx_client.send.return_value = mock_response @@ -245,10 +245,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) @@ -279,12 +279,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_httpx_client.send.return_value = mock_response @@ -324,7 +324,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_lines.return_value = async_iterable_from_list([]) @@ -369,12 +369,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_lines.return_value = async_iterable_from_list([]) @@ -413,7 +413,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 @@ -460,7 +460,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': [ @@ -475,7 +475,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 @@ -503,14 +503,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 @@ -608,10 +608,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={}), ) @@ -640,10 +640,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={}), ) @@ -674,10 +674,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={}), ) @@ -728,7 +728,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_lines.return_value = async_iterable_from_list([]) @@ -766,9 +766,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={ @@ -811,7 +811,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_lines.return_value = async_iterable_from_list( diff --git a/tests/compat/v0_3/test_jsonrpc_transport.py b/tests/compat/v0_3/test_jsonrpc_transport.py index 13d91162a..74e2b9e08 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,13 @@ TaskPushNotificationConfig, TaskState, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.errors import InvalidParamsError @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 +435,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 +526,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 +553,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 d7edda4b9..008bb5930 100644 --- a/tests/compat/v0_3/test_rest_routes_compat.py +++ b/tests/compat/v0_3/test_rest_routes_compat.py @@ -20,10 +20,10 @@ 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 @@ -98,15 +98,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( @@ -141,7 +141,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( @@ -176,7 +176,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', @@ -203,7 +203,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') @@ -218,7 +218,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"}}' @@ -238,7 +238,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', @@ -304,7 +304,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', @@ -320,7 +320,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 e627b444f..5067291fe 100644 --- a/tests/compat/v0_3/test_rest_transport.py +++ b/tests/compat/v0_3/test_rest_transport.py @@ -2,7 +2,6 @@ from unittest.mock import AsyncMock, MagicMock, patch -import httpx import pytest from a2a.client.errors import A2AClientError @@ -27,12 +26,13 @@ TaskPushNotificationConfig, TaskStatus, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.errors import InvalidParamsError, MethodNotFoundError @pytest.fixture def mock_httpx_client(): - client = AsyncMock(spec=httpx.AsyncClient) + client = AsyncMock(spec=httpx_lib.AsyncClient) client.is_closed = False return client @@ -55,7 +55,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'} } @@ -79,7 +79,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): @@ -233,31 +233,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 @@ -448,17 +448,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 ) @@ -469,14 +469,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 ) @@ -485,14 +485,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 ) @@ -570,17 +570,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 ) @@ -599,14 +599,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 ) @@ -615,17 +615,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 ) @@ -667,7 +667,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( 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..e7c34fb0d 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 @@ -61,12 +61,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 +91,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 +127,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 +135,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 +195,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 +280,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 +389,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 + httpx_lib.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 +407,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 +543,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..280a36998 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,6 +15,7 @@ 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 @@ -115,8 +115,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..6d085f855 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, @@ -245,7 +245,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 +267,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 +722,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 +799,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 +880,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..72f8c082a 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,6 +25,7 @@ TaskState, ) from a2a.utils import TransportProtocol +from a2a.utils._httpx_compat import httpx_lib from starlette.applications import Starlette @@ -113,8 +113,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..19c525887 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,6 +44,7 @@ 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 @@ -237,8 +237,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 +264,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..41e17cc2e 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,6 +47,7 @@ TaskState, ) from a2a.utils import TransportProtocol +from a2a.utils._httpx_compat import httpx_lib from starlette.applications import Starlette @@ -214,8 +214,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 +291,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 +348,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 +376,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..7a8911980 100644 --- a/tests/integration/test_samples_smoke.py +++ b/tests/integration/test_samples_smoke.py @@ -14,10 +14,14 @@ 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, +) + if TYPE_CHECKING: from collections.abc import AsyncGenerator @@ -41,13 +45,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..2d0d427cf 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, @@ -184,14 +184,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..1d988c9a1 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,6 +32,7 @@ SendMessageRequest, ) from a2a.utils import TransportProtocol +from a2a.utils._httpx_compat import httpx_lib from starlette.applications import Starlette @@ -88,8 +88,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 64038f1e9..35f7311cc 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 @@ -18,8 +17,8 @@ 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 @@ -49,7 +48,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 +85,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 +141,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( @@ -219,9 +218,9 @@ async def test_jsonrpc_tenant_context_population( via the JSON-RPC transport. """ # 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( + # We use httpx_lib.ASGITransport so httpx calls go directly to the Starlette app + 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 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 3eb90353b..277cf0962 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,6 +72,7 @@ TaskStatus, TaskStatusUpdateEvent, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.constants import TERMINAL_TASK_STATES @@ -2974,7 +2974,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 222607110..3b8b8f85a 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 @@ -55,6 +54,10 @@ TaskState, TaskStatus, ) +from a2a.utils._httpx_compat import ( + HTTP_STATUS_ERROR, + httpx_lib, +) CARD = AgentCard( @@ -514,17 +517,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, ) @@ -571,7 +574,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 @@ -618,13 +621,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, @@ -676,10 +679,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_rest_dispatcher.py b/tests/server/routes/test_rest_dispatcher.py index 3d7bb3986..9d5f19785 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, ) @@ -333,8 +333,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/tasks/test_inmemory_push_notifications.py b/tests/server/tasks/test_inmemory_push_notifications.py index 8acae7d9d..42761f2c6 100644 --- a/tests/server/tasks/test_inmemory_push_notifications.py +++ b/tests/server/tasks/test_inmemory_push_notifications.py @@ -5,8 +5,6 @@ from unittest.mock import AsyncMock, MagicMock, patch -import httpx - from a2a.auth.user import User from a2a.server.context import ServerCallContext from a2a.server.tasks.base_push_notification_sender import ( @@ -22,6 +20,7 @@ TaskState, TaskStatus, ) +from a2a.utils._httpx_compat import httpx_lib from google.protobuf.json_format import MessageToDict @@ -94,7 +93,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 +247,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 +274,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 +314,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 +343,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 +374,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 +554,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..a94422f20 100644 --- a/tests/server/tasks/test_push_notification_sender.py +++ b/tests/server/tasks/test_push_notification_sender.py @@ -3,8 +3,6 @@ from unittest.mock import AsyncMock, MagicMock, patch -import httpx - from a2a.server.tasks.base_push_notification_sender import ( BasePushNotificationSender, ) @@ -18,6 +16,7 @@ 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 @@ -46,7 +45,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 +62,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 +88,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 +113,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 +205,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 +239,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 +273,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 +297,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 +362,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 +374,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 +440,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/utils/test_proto_utils.py b/tests/utils/test_proto_utils.py index d2a1e101b..61774e4c8 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 @@ -317,7 +317,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 From 0337bfd266e22ee10fd79cad1cca15272417bb15 Mon Sep 17 00:00:00 2001 From: Iwaniukooo11 Date: Tue, 10 Nov 2026 10:38:54 +0000 Subject: [PATCH 3/9] test: add httpx2 markers --- pyproject.toml | 2 + tests/client/test_base_client.py | 3 + tests/client/test_base_client_plugins.py | 3 + tests/client/test_card_resolver.py | 3 + tests/client/test_client_factory.py | 3 + tests/client/test_errors.py | 3 + tests/client/transports/test_http_helpers.py | 3 + .../client/transports/test_jsonrpc_client.py | 3 + tests/client/transports/test_rest_client.py | 3 + tests/compat/v0_3/test_jsonrpc_app_compat.py | 3 + tests/compat/v0_3/test_jsonrpc_transport.py | 3 + tests/compat/v0_3/test_rest_routes_compat.py | 3 + tests/compat/v0_3/test_rest_transport.py | 3 + .../test_default_push_notification_support.py | 3 + tests/integration/test_agent_card.py | 3 + .../test_client_server_integration.py | 3 + .../integration/test_copying_observability.py | 3 + tests/integration/test_end_to_end.py | 3 + tests/integration/test_plugins.py | 3 + tests/integration/test_samples_smoke.py | 3 + tests/integration/test_scenarios.py | 3 + .../test_stream_generator_cleanup.py | 3 + tests/integration/test_tenant.py | 3 + tests/integration/test_version_header.py | 3 + .../test_default_request_handler_v2.py | 3 + ...test_default_request_handler_v2_plugins.py | 3 + tests/server/routes/test_agent_card_routes.py | 3 + tests/server/routes/test_fastapi_routes.py | 3 + .../server/routes/test_jsonrpc_dispatcher.py | 3 + tests/server/routes/test_jsonrpc_routes.py | 3 + tests/server/routes/test_rest_dispatcher.py | 3 + tests/server/routes/test_rest_routes.py | 3 + .../tasks/test_inmemory_push_notifications.py | 5 ++ .../tasks/test_push_notification_sender.py | 5 ++ tests/server/test_integration.py | 3 + tests/utils/test_proto_utils.py | 3 + uv.lock | 88 +++++++++++++++++-- 37 files changed, 193 insertions(+), 6 deletions(-) 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/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 ab05b41d5..dbb375e7e 100644 --- a/tests/client/test_base_client_plugins.py +++ b/tests/client/test_base_client_plugins.py @@ -37,6 +37,9 @@ from a2a.utils._httpx_compat import httpx_lib +pytestmark = pytest.mark.httpx2 + + class Recorder(plugins.ClientPlugin): def __init__(self) -> None: self.calls: list[tuple[str, Any]] = [] diff --git a/tests/client/test_card_resolver.py b/tests/client/test_card_resolver.py index dd2b96e15..88144600c 100644 --- a/tests/client/test_card_resolver.py +++ b/tests/client/test_card_resolver.py @@ -33,6 +33,9 @@ from google.protobuf.json_format import ParseError +pytestmark = pytest.mark.httpx2 + + @pytest.fixture def mock_httpx_client(): """Fixture providing a mocked async httpx client.""" diff --git a/tests/client/test_client_factory.py b/tests/client/test_client_factory.py index 1ec4e1ebc..269090c83 100644 --- a/tests/client/test_client_factory.py +++ b/tests/client/test_client_factory.py @@ -25,6 +25,9 @@ ) +pytestmark = pytest.mark.httpx2 + + @pytest.fixture def base_agent_card() -> AgentCard: """Provides a base AgentCard for tests.""" 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 64e8b3492..dcecb33d8 100644 --- a/tests/client/transports/test_http_helpers.py +++ b/tests/client/transports/test_http_helpers.py @@ -12,6 +12,9 @@ from a2a.utils._httpx_compat import httpx_lib +pytestmark = pytest.mark.httpx2 + + def test_default_sse_error_handler(): with pytest.raises( A2AClientError, match='SSE stream error event received: error_msg' diff --git a/tests/client/transports/test_jsonrpc_client.py b/tests/client/transports/test_jsonrpc_client.py index 1eff9d2c7..1e0fce0fb 100644 --- a/tests/client/transports/test_jsonrpc_client.py +++ b/tests/client/transports/test_jsonrpc_client.py @@ -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 diff --git a/tests/client/transports/test_rest_client.py b/tests/client/transports/test_rest_client.py index 586b4b28e..f5a4cc344 100644 --- a/tests/client/transports/test_rest_client.py +++ b/tests/client/transports/test_rest_client.py @@ -33,6 +33,9 @@ from google.protobuf.timestamp_pb2 import Timestamp +pytestmark = pytest.mark.httpx2 + + @pytest.fixture def mock_httpx_client() -> AsyncMock: client = AsyncMock(spec=httpx_lib.AsyncClient) diff --git a/tests/compat/v0_3/test_jsonrpc_app_compat.py b/tests/compat/v0_3/test_jsonrpc_app_compat.py index aec4a56ee..e748a0e74 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 74e2b9e08..56a17e084 100644 --- a/tests/compat/v0_3/test_jsonrpc_transport.py +++ b/tests/compat/v0_3/test_jsonrpc_transport.py @@ -29,6 +29,9 @@ from a2a.utils.errors import InvalidParamsError +pytestmark = pytest.mark.httpx2 + + @pytest.fixture def mock_httpx_client(): client = AsyncMock(spec=httpx_lib.AsyncClient) diff --git a/tests/compat/v0_3/test_rest_routes_compat.py b/tests/compat/v0_3/test_rest_routes_compat.py index 008bb5930..ce3a17ca2 100644 --- a/tests/compat/v0_3/test_rest_routes_compat.py +++ b/tests/compat/v0_3/test_rest_routes_compat.py @@ -29,6 +29,9 @@ from starlette.requests import Request +pytestmark = pytest.mark.httpx2 + + logger = logging.getLogger(__name__) diff --git a/tests/compat/v0_3/test_rest_transport.py b/tests/compat/v0_3/test_rest_transport.py index 5067291fe..95fb37723 100644 --- a/tests/compat/v0_3/test_rest_transport.py +++ b/tests/compat/v0_3/test_rest_transport.py @@ -30,6 +30,9 @@ from a2a.utils.errors import InvalidParamsError, MethodNotFoundError +pytestmark = pytest.mark.httpx2 + + @pytest.fixture def mock_httpx_client(): client = AsyncMock(spec=httpx_lib.AsyncClient) 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 e7c34fb0d..211c8d6cb 100644 --- a/tests/integration/push_notifications/test_default_push_notification_support.py +++ b/tests/integration/push_notifications/test_default_push_notification_support.py @@ -32,6 +32,9 @@ ) +pytestmark = pytest.mark.httpx2 + + _TEST_USER_HEADER = 'x-test-user' diff --git a/tests/integration/test_agent_card.py b/tests/integration/test_agent_card.py index 280a36998..155603e8c 100644 --- a/tests/integration/test_agent_card.py +++ b/tests/integration/test_agent_card.py @@ -21,6 +21,9 @@ from starlette.applications import Starlette +pytestmark = pytest.mark.httpx2 + + class DummyAgentExecutor(AgentExecutor): """An agent executor that does nothing for integration testing.""" diff --git a/tests/integration/test_client_server_integration.py b/tests/integration/test_client_server_integration.py index 6d085f855..15c8bea5c 100644 --- a/tests/integration/test_client_server_integration.py +++ b/tests/integration/test_client_server_integration.py @@ -83,6 +83,9 @@ from starlette.applications import Starlette +pytestmark = pytest.mark.httpx2 + + # --- Test Constants --- TASK_FROM_STREAM = Task( diff --git a/tests/integration/test_copying_observability.py b/tests/integration/test_copying_observability.py index 72f8c082a..0a3aa7124 100644 --- a/tests/integration/test_copying_observability.py +++ b/tests/integration/test_copying_observability.py @@ -29,6 +29,9 @@ 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 diff --git a/tests/integration/test_end_to_end.py b/tests/integration/test_end_to_end.py index 19c525887..51ba0a9f2 100644 --- a/tests/integration/test_end_to_end.py +++ b/tests/integration/test_end_to_end.py @@ -49,6 +49,9 @@ from starlette.applications import Starlette +pytestmark = pytest.mark.httpx2 + + SUPPORTED_EXTENSION_URIS = [ 'https://example.com/ext/v1', 'https://example.com/ext/v2', diff --git a/tests/integration/test_plugins.py b/tests/integration/test_plugins.py index 41e17cc2e..85d6eb879 100644 --- a/tests/integration/test_plugins.py +++ b/tests/integration/test_plugins.py @@ -51,6 +51,9 @@ 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.""" diff --git a/tests/integration/test_samples_smoke.py b/tests/integration/test_samples_smoke.py index 7a8911980..44c550c6c 100644 --- a/tests/integration/test_samples_smoke.py +++ b/tests/integration/test_samples_smoke.py @@ -23,6 +23,9 @@ ) +pytestmark = pytest.mark.httpx2 + + if TYPE_CHECKING: from collections.abc import AsyncGenerator diff --git a/tests/integration/test_scenarios.py b/tests/integration/test_scenarios.py index 2d0d427cf..9ba665488 100644 --- a/tests/integration/test_scenarios.py +++ b/tests/integration/test_scenarios.py @@ -65,6 +65,9 @@ from starlette.requests import Request +pytestmark = pytest.mark.httpx2 + + logger = logging.getLogger(__name__) diff --git a/tests/integration/test_stream_generator_cleanup.py b/tests/integration/test_stream_generator_cleanup.py index 1d988c9a1..7ff18356f 100644 --- a/tests/integration/test_stream_generator_cleanup.py +++ b/tests/integration/test_stream_generator_cleanup.py @@ -36,6 +36,9 @@ from starlette.applications import Starlette +pytestmark = pytest.mark.httpx2 + + class _MessageExecutor(AgentExecutor): """Responds with a single Message event.""" diff --git a/tests/integration/test_tenant.py b/tests/integration/test_tenant.py index 35f7311cc..28a01cf5e 100644 --- a/tests/integration/test_tenant.py +++ b/tests/integration/test_tenant.py @@ -22,6 +22,9 @@ from starlette.applications import Starlette +pytestmark = pytest.mark.httpx2 + + class TestTenantDecorator: @pytest.fixture def agent_card(self): 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 277cf0962..ff0fa2b9f 100644 --- a/tests/server/request_handlers/test_default_request_handler_v2.py +++ b/tests/server/request_handlers/test_default_request_handler_v2.py @@ -76,6 +76,9 @@ 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( 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 3b8b8f85a..bab5840ad 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 @@ -60,6 +60,9 @@ ) +pytestmark = pytest.mark.httpx2 + + CARD = AgentCard( name='plugin_test_agent', version='1.0', 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 9d5f19785..5111831a7 100644 --- a/tests/server/routes/test_rest_dispatcher.py +++ b/tests/server/routes/test_rest_dispatcher.py @@ -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, 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 42761f2c6..eed1b21f8 100644 --- a/tests/server/tasks/test_inmemory_push_notifications.py +++ b/tests/server/tasks/test_inmemory_push_notifications.py @@ -5,6 +5,8 @@ from unittest.mock import AsyncMock, MagicMock, patch +import pytest + from a2a.auth.user import User from a2a.server.context import ServerCallContext from a2a.server.tasks.base_push_notification_sender import ( @@ -24,6 +26,9 @@ 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) diff --git a/tests/server/tasks/test_push_notification_sender.py b/tests/server/tasks/test_push_notification_sender.py index a94422f20..5375c2c4b 100644 --- a/tests/server/tasks/test_push_notification_sender.py +++ b/tests/server/tasks/test_push_notification_sender.py @@ -3,6 +3,8 @@ from unittest.mock import AsyncMock, MagicMock, patch +import pytest + from a2a.server.tasks.base_push_notification_sender import ( BasePushNotificationSender, ) @@ -21,6 +23,9 @@ 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, 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 61774e4c8..3d8bf66fd 100644 --- a/tests/utils/test_proto_utils.py +++ b/tests/utils/test_proto_utils.py @@ -32,6 +32,9 @@ from starlette.datastructures import QueryParams +pytestmark = pytest.mark.httpx2 + + class TestToStreamResponse: """Tests for to_stream_response function.""" 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 = [ From 8b3c4bb9b1ddf307fe925487a34b53be9e943b45 Mon Sep 17 00:00:00 2001 From: Iwaniukooo11 Date: Tue, 10 Nov 2026 10:42:49 +0000 Subject: [PATCH 4/9] test: add new job in CI --- .github/workflows/unit-tests.yml | 82 +++++++++++++++++++------------- 1 file changed, 50 insertions(+), 32 deletions(-) diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 6126903eb..805ca9d76 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -5,22 +5,20 @@ on: branches: [main] pull_request: paths: - - 'src/**' - - 'tests/**' - - 'pyproject.toml' - - 'uv.lock' - - 'scripts/run_db_tests.sh' - - 'scripts/docker-compose.test.yml' + - src/** + - tests/** + - pyproject.toml + - uv.lock + - scripts/run_db_tests.sh + - scripts/docker-compose.test.yml # Self-callout: re-run when this workflow changes so YAML edits are validated in PRs. - - '.github/workflows/unit-tests.yml' + - .github/workflows/unit-tests.yml permissions: contents: read - jobs: test: name: Test with Python ${{ matrix.python-version }} runs-on: ubuntu-latest - if: github.repository == 'a2aproject/a2a-python' services: postgres: @@ -29,10 +27,10 @@ jobs: POSTGRES_USER: a2a POSTGRES_PASSWORD: a2a_password POSTGRES_DB: a2a_test - ports: - - 5432:5432 + ports: [5432:5432] options: >- - --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 + --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries + 5 mysql: image: mysql:8.0 env: @@ -40,69 +38,60 @@ jobs: MYSQL_DATABASE: a2a_test MYSQL_USER: a2a MYSQL_PASSWORD: a2a_password - ports: - - 3306:3306 + ports: [3306:3306] options: >- - --health-cmd="mysqladmin ping -h localhost -u root -proot" --health-interval=10s --health-timeout=5s --health-retries=5 - + --health-cmd="mysqladmin ping -h localhost -u root -proot" --health-interval=10s + --health-timeout=5s --health-retries=5 strategy: matrix: python-version: ['3.10', '3.11', '3.12', '3.13', '3.14'] steps: - name: Checkout code - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - name: Set up test environment variables run: | echo "POSTGRES_TEST_DSN=postgresql+asyncpg://a2a:a2a_password@localhost:5432/a2a_test" >> $GITHUB_ENV echo "MYSQL_TEST_DSN=mysql+aiomysql://a2a:a2a_password@localhost:3306/a2a_test" >> $GITHUB_ENV - - name: Install uv for Python ${{ matrix.python-version }} - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 + 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 - # Coverage comparison for PRs (only on Python 3.14 to avoid duplicate work) - name: Checkout Base Branch if: github.event_name == 'pull_request' && matrix.python-version == '3.14' - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 with: ref: ${{ github.event.pull_request.base.ref || 'main' }} clean: true - - name: Install dependencies run: uv sync --locked - - name: Run coverage (Base) if: github.event_name == 'pull_request' && matrix.python-version == '3.14' run: | uv run pytest --cov=a2a --cov-report=json --cov-report=html:coverage mv coverage.json /tmp/coverage-base.json - - name: Checkout PR Branch (Restore) if: github.event_name == 'pull_request' && matrix.python-version == '3.14' - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 with: clean: true - - name: Run coverage (PR) if: github.event_name == 'pull_request' && matrix.python-version == '3.14' run: | uv run pytest --cov=a2a --cov-report=json --cov-report=html:coverage --cov-report=term --cov-fail-under=88 mv coverage.json coverage-pr.json cp /tmp/coverage-base.json coverage-base.json - - name: Save Metadata if: github.event_name == 'pull_request' && matrix.python-version == '3.14' run: | echo ${{ github.event.number }} > ./PR_NUMBER echo ${{ github.event.pull_request.base.ref || 'main' }} > ./BASE_BRANCH - - name: Upload Coverage Artifacts - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 if: github.event_name == 'pull_request' && matrix.python-version == '3.14' with: name: coverage-data @@ -118,14 +107,43 @@ jobs: - name: Run tests (Standard) if: matrix.python-version != '3.14' || github.event_name != 'pull_request' run: uv run pytest --cov=a2a --cov-report term --cov-fail-under=88 - - name: Upload Artifact (base) - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 if: github.event_name != 'pull_request' && matrix.python-version == '3.14' with: name: coverage-report path: coverage retention-days: 14 - - 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.13'] + 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 From 8d16ead627da7f5942f57a85a4e282e7cac81093 Mon Sep 17 00:00:00 2001 From: Iwaniukooo11 Date: Thu, 12 Nov 2026 09:12:28 +0000 Subject: [PATCH 5/9] fix conflict --- tests/client/transports/test_rest_client.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/tests/client/transports/test_rest_client.py b/tests/client/transports/test_rest_client.py index 3d3cca586..14eb1fa37 100644 --- a/tests/client/transports/test_rest_client.py +++ b/tests/client/transports/test_rest_client.py @@ -36,6 +36,7 @@ TaskState, TaskStatus, ) +from a2a.utils._httpx_compat import httpx_lib from a2a.utils.constants import ( PROTOCOL_VERSION_CURRENT, VERSION_HEADER, @@ -46,9 +47,6 @@ MethodNotFoundError, TaskNotFoundError, ) -from a2a.utils._httpx_compat import httpx_lib -from a2a.utils.constants import TransportProtocol -from a2a.utils.errors import A2A_ERROR_MAPPING, MethodNotFoundError from google.protobuf import json_format from google.protobuf.timestamp_pb2 import Timestamp from starlette.applications import Starlette @@ -806,8 +804,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') From 13733b8b71aed6cf46079138051dfad8fc35fcc7 Mon Sep 17 00:00:00 2001 From: Iwaniukooo11 Date: Mon, 16 Nov 2026 13:26:38 +0000 Subject: [PATCH 6/9] address review comments --- .github/workflows/unit-tests.yml | 3 +- src/a2a/utils/_httpx_compat.py | 101 +++++++++++++++++-------------- 2 files changed, 58 insertions(+), 46 deletions(-) diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 805ca9d76..2261739e8 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -124,7 +124,8 @@ jobs: if: github.repository == 'a2aproject/a2a-python' strategy: matrix: - python-version: ['3.13'] + # Starts at 3.11, the floor httpx2 supports; 3.10 has no httpx2 to test. + python-version: ['3.11', '3.12', '3.13', '3.14'] steps: - name: Checkout code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 diff --git a/src/a2a/utils/_httpx_compat.py b/src/a2a/utils/_httpx_compat.py index 23c42ceb1..48bb8b94b 100644 --- a/src/a2a/utils/_httpx_compat.py +++ b/src/a2a/utils/_httpx_compat.py @@ -5,60 +5,71 @@ `httpx2` is installed. """ +from typing import TYPE_CHECKING + import httpx -# Declare catch-tuple types explicitly so conditional assignment doesn't widen -# them to `BaseException` + the types are open gor httpx2 errors. -HTTP_STATUS_ERROR: tuple[type[httpx.HTTPStatusError], ...] -REQUEST_ERROR: tuple[type[httpx.RequestError], ...] -TIMEOUT_EXCEPTION: tuple[type[httpx.TimeoutException], ...] -STREAM_CLOSED: tuple[type[httpx.StreamClosed], ...] -RESPONSE_NOT_READ: tuple[type[httpx.ResponseNotRead], ...] +AsyncClient = httpx.AsyncClient +Request = httpx.Request +Response = httpx.Response -try: +if TYPE_CHECKING: import httpx2 # ty: ignore[unresolved-import] - httpx_lib = httpx2 - - 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, - ) - - AsyncClient = httpx.AsyncClient | httpx2.AsyncClient - Request = httpx.Request | httpx2.Request - Response = httpx.Response | httpx2.Response - HTTPStatusError = httpx.HTTPStatusError | httpx2.HTTPStatusError -except ImportError: httpx_lib = httpx - HTTP_STATUS_ERROR = (httpx.HTTPStatusError,) - REQUEST_ERROR = (httpx.RequestError,) - TIMEOUT_EXCEPTION = (httpx.TimeoutException,) - STREAM_CLOSED = (httpx.StreamClosed,) - RESPONSE_NOT_READ = (httpx.ResponseNotRead,) + HTTPStatusError = httpx.HTTPStatusError | httpx2.HTTPStatusError + + 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 + + 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 + + HTTPStatusError = httpx.HTTPStatusError - 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__ = [ From 3d286c168315a30be30e32eba71cad3db896ce7f Mon Sep 17 00:00:00 2001 From: Iwaniukooo11 Date: Mon, 16 Nov 2026 13:35:44 +0000 Subject: [PATCH 7/9] drop unrelated yaml reformatting --- .github/workflows/unit-tests.yml | 63 ++++++++++++++++++++------------ 1 file changed, 40 insertions(+), 23 deletions(-) diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 2261739e8..5c707c5ff 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -5,20 +5,22 @@ on: branches: [main] pull_request: paths: - - src/** - - tests/** - - pyproject.toml - - uv.lock - - scripts/run_db_tests.sh - - scripts/docker-compose.test.yml + - 'src/**' + - 'tests/**' + - 'pyproject.toml' + - 'uv.lock' + - 'scripts/run_db_tests.sh' + - 'scripts/docker-compose.test.yml' # Self-callout: re-run when this workflow changes so YAML edits are validated in PRs. - - .github/workflows/unit-tests.yml + - '.github/workflows/unit-tests.yml' permissions: contents: read + jobs: test: name: Test with Python ${{ matrix.python-version }} runs-on: ubuntu-latest + if: github.repository == 'a2aproject/a2a-python' services: postgres: @@ -27,10 +29,10 @@ jobs: POSTGRES_USER: a2a POSTGRES_PASSWORD: a2a_password POSTGRES_DB: a2a_test - ports: [5432:5432] + ports: + - 5432:5432 options: >- - --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries - 5 + --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 mysql: image: mysql:8.0 env: @@ -38,60 +40,69 @@ jobs: MYSQL_DATABASE: a2a_test MYSQL_USER: a2a MYSQL_PASSWORD: a2a_password - ports: [3306:3306] + ports: + - 3306:3306 options: >- - --health-cmd="mysqladmin ping -h localhost -u root -proot" --health-interval=10s - --health-timeout=5s --health-retries=5 + --health-cmd="mysqladmin ping -h localhost -u root -proot" --health-interval=10s --health-timeout=5s --health-retries=5 + strategy: matrix: python-version: ['3.10', '3.11', '3.12', '3.13', '3.14'] steps: - name: Checkout code - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 - name: Set up test environment variables run: | echo "POSTGRES_TEST_DSN=postgresql+asyncpg://a2a:a2a_password@localhost:5432/a2a_test" >> $GITHUB_ENV echo "MYSQL_TEST_DSN=mysql+aiomysql://a2a:a2a_password@localhost:3306/a2a_test" >> $GITHUB_ENV + - name: Install uv for Python ${{ matrix.python-version }} - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 + 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 + # Coverage comparison for PRs (only on Python 3.14 to avoid duplicate work) - name: Checkout Base Branch if: github.event_name == 'pull_request' && matrix.python-version == '3.14' - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 with: ref: ${{ github.event.pull_request.base.ref || 'main' }} clean: true + - name: Install dependencies run: uv sync --locked + - name: Run coverage (Base) if: github.event_name == 'pull_request' && matrix.python-version == '3.14' run: | uv run pytest --cov=a2a --cov-report=json --cov-report=html:coverage mv coverage.json /tmp/coverage-base.json + - name: Checkout PR Branch (Restore) if: github.event_name == 'pull_request' && matrix.python-version == '3.14' - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 with: clean: true + - name: Run coverage (PR) if: github.event_name == 'pull_request' && matrix.python-version == '3.14' run: | uv run pytest --cov=a2a --cov-report=json --cov-report=html:coverage --cov-report=term --cov-fail-under=88 mv coverage.json coverage-pr.json cp /tmp/coverage-base.json coverage-base.json + - name: Save Metadata if: github.event_name == 'pull_request' && matrix.python-version == '3.14' run: | echo ${{ github.event.number }} > ./PR_NUMBER echo ${{ github.event.pull_request.base.ref || 'main' }} > ./BASE_BRANCH + - name: Upload Coverage Artifacts - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 if: github.event_name == 'pull_request' && matrix.python-version == '3.14' with: name: coverage-data @@ -107,35 +118,40 @@ jobs: - name: Run tests (Standard) if: matrix.python-version != '3.14' || github.event_name != 'pull_request' run: uv run pytest --cov=a2a --cov-report term --cov-fail-under=88 + - name: Upload Artifact (base) - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 if: github.event_name != 'pull_request' && matrix.python-version == '3.14' with: name: coverage-report path: coverage retention-days: 14 + - name: Show coverage summary in log run: uv run coverage report - # httpx2 testing - Running test on httpx2 for marked tests + # 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: - # Starts at 3.11, the floor httpx2 supports; 3.10 has no httpx2 to test. python-version: ['3.11', '3.12', '3.13', '3.14'] steps: - name: Checkout code - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 + - name: Install uv for Python ${{ matrix.python-version }} - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 + 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 @@ -146,5 +162,6 @@ jobs: 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 From a5877a47e17422d71095bf4c2c51307cba727f08 Mon Sep 17 00:00:00 2001 From: Iwaniukooo11 Date: Mon, 16 Nov 2026 14:02:58 +0000 Subject: [PATCH 8/9] use compat layer in stream media type tests --- tests/client/transports/test_stream_media_type.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) 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, From 6b69c00a9019b2ae6d7ecd8ff48d5ecc5f5351fc Mon Sep 17 00:00:00 2001 From: Iwaniukooo11 Date: Mon, 16 Nov 2026 16:42:10 +0000 Subject: [PATCH 9/9] fix: Resolved typing issues --- .github/workflows/linter.yaml | 4 ++-- src/a2a/client/transports/http_helpers.py | 5 ++++- src/a2a/client/transports/rest.py | 2 +- src/a2a/utils/_httpx_compat.py | 20 ++++++++++++++------ 4 files changed, 21 insertions(+), 10 deletions(-) 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/src/a2a/client/transports/http_helpers.py b/src/a2a/client/transports/http_helpers.py index 8d7b050a9..17e882b24 100644 --- a/src/a2a/client/transports/http_helpers.py +++ b/src/a2a/client/transports/http_helpers.py @@ -3,7 +3,7 @@ from collections.abc import AsyncGenerator, Callable, Iterator from contextlib import contextmanager -from typing import Any, NoReturn +from typing import TYPE_CHECKING, Any, NoReturn from a2a.client.client import ClientCallContext from a2a.client.errors import A2AClientError, A2AClientTimeoutError @@ -209,6 +209,9 @@ class _SSEEventSource: collision (see https://bugs.python.org/issue38559). """ + if TYPE_CHECKING: + _request: Request + def __init__( self, client: AsyncClient, diff --git a/src/a2a/client/transports/rest.py b/src/a2a/client/transports/rest.py index ceb082886..9d2b6ec2b 100644 --- a/src/a2a/client/transports/rest.py +++ b/src/a2a/client/transports/rest.py @@ -306,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, diff --git a/src/a2a/utils/_httpx_compat.py b/src/a2a/utils/_httpx_compat.py index 48bb8b94b..36ba679a4 100644 --- a/src/a2a/utils/_httpx_compat.py +++ b/src/a2a/utils/_httpx_compat.py @@ -5,21 +5,22 @@ `httpx2` is installed. """ -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any import httpx -AsyncClient = httpx.AsyncClient -Request = httpx.Request -Response = httpx.Response - if TYPE_CHECKING: + from typing import TypeAlias + import httpx2 # ty: ignore[unresolved-import] httpx_lib = httpx - HTTPStatusError = httpx.HTTPStatusError | httpx2.HTTPStatusError + 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] @@ -38,6 +39,9 @@ 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 = ( @@ -60,9 +64,13 @@ 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,)