|
|
Mocking External HTTP APIs in ADK Agent Tool Tests
Author: Venkata Sudhakar
ShopMax India's ADK agent tools call multiple external HTTP APIs: the logistics provider API for shipment tracking, the payment gateway for EMI eligibility, and the warehouse management system for stock levels. Testing tools that make HTTP calls requires intercepting those calls so tests run offline, are deterministic, and do not incur API costs or rate limit usage. Mocking HTTP APIs lets you simulate error responses, timeouts, and partial failures that are impossible to trigger reliably against a live API.
Use the responses library or unittest.mock.patch to intercept HTTP calls made by ADK tool functions. Register fixed responses for specific URLs, then assert that the tool correctly handles both success and error responses. Test network timeout paths by raising a requests.Timeout exception from the mock. Verify that the tool logs or retries on transient errors without propagating raw HTTP exceptions to the agent.
The example below mocks HTTP calls for ShopMax India's shipment tracking tool using a simple injectable HTTP client. Tests cover the success path, a 404 not found, a 500 server error, and a timeout scenario - all without network access.
It gives the following output,
.... (4 passed in 0.01s)
In production, ShopMax India should use a real HTTP client wrapper class that all tools accept as a dependency, making it trivial to swap the real client for a mock in tests. Record actual API responses from the logistics provider during a staging run and save them as fixture files - this gives you realistic mock data that matches the real API schema rather than hand-crafted dicts. Re-record fixtures quarterly or whenever the external API releases a new version to prevent schema drift.
|
|