|
|
Testing ADK Agent Custom OAuth and API Key Authentication
Author: Venkata Sudhakar
ADK agents that call external APIs must be tested for correct authentication behavior - both when valid credentials are provided and when they are missing or expired. ShopMax India's payment and logistics agents use a mix of API keys for internal services and OAuth tokens for third-party providers, and the authentication layer must be tested independently of the agent logic to keep tests fast and deterministic.
The testing pattern is to wrap the external API call in a tool function that reads credentials from a context object injected at test time. In unit tests, the context carries a fake API key or a pre-signed fake token. The test then asserts that the tool correctly attaches the credential to the outgoing request header and raises an AuthError when the credential is absent or expired. The unittest.mock.patch decorator intercepts the actual HTTP call so no real network request is made.
The example below defines a payment gateway tool that reads an API key from context, mocks the HTTP call, and runs three tests: valid key succeeds, missing key raises AuthError, and expired OAuth token raises AuthError with a token-expired message.
It gives the following output,
Payment Rs 4999.0 approved with API key
3 passed in 0.09s
Never hardcode credentials in test files - use pytest fixtures that read from environment variables or a secrets manager stub. For OAuth flows, test token refresh logic separately by simulating a 401 response from the mock and asserting the tool retries with a refreshed token. Rotate test API keys regularly and add a CI check that flags any key pattern committed to the repo.
|
|