Contract tests for ADK tools with pytest and fakes
Validate arguments and authorisation in code, not in the prompt, and test tools with timeouts, deterministic fakes, typed errors and call budgets.
By Invicly Tech, , in Google ADK with Python for AI Agents. About 11 minutes to read.
In short
A tool contract is the promise a tool makes: which arguments it accepts, who may call it, how long it may take and which results and errors it can return. You enforce that contract in Python code, because a prompt can be ignored or misread by the model. Then you prove it with fast pytest tests that call the tool directly with fake dependencies, so no model, network or Google account is needed.
Think of it like this: The prompt is a sign on the door saying staff only; the contract check is the lock. Tests are you trying the handle every morning.
Explained simply
A model can be persuaded, confused or just wrong. If the only thing stopping it from reading another person's ticket is a sentence in the instruction, that protection will fail one day. So the rules that matter live in code: the tool itself checks the ticket ID format and checks that the ticket belongs to the signed-in user.
A contract is the list of things a tool promises. It accepts only these arguments. It only shows the caller's own tickets. It answers within two seconds or returns a timeout error. It returns one of four known error codes. Writing this list down first makes the code and the tests easy to write.
You test the contract with pytest, by calling the tool function directly. You do not need a model or the internet. In place of the real ticket system you pass a fake: a tiny class that returns fixed data, or fails, or waits too long, whichever the test needs.
Two extra safety nets sit around the tool. A call budget stops a confused agent from calling tools in a loop. A log line per call, with the tool name, the outcome and how long it took, lets you see what really happened later.
Press Play on a diagram to walk through it one step at a time.
- 1Prompt
Guidance only: when to use the tool
- 2before_tool_callback
Call budget and logging before the tool runs
- 3Tool body
Argument validation and ownership check
- 4Dependency
Ticket store behind a timeout
- 5pytest
Calls the tool directly with fakes and asserts the contract
- Arguments
- Bad format returns INVALID_ARGUMENT
- Lowercase ID is normalised
- Authorisation
- Owner sees ticket
- Other user gets NOT_FOUND
- Dependencies
- Slow store returns UPSTREAM_TIMEOUT
- Broken store maps to a code
- Budget
- Third call is refused
- New invocation resets the count
- Logging
- One line per call
- No ticket text in logs
In depth
Validation and authorisation inside the tool
Check every argument the model sends as if it came from an untrusted web form. Normalise it, check its format with a pattern, and check numbers against a range. Then authorise: compare the ticket's owner with tool_context.user_id. Your server sets that ID from the signed-in session when it calls the runner, so the model cannot change it. Return the same NOT_FOUND result for a missing ticket and for someone else's ticket, so the tool does not reveal which IDs exist. Put these checks in the tool body or in a shared helper used by every tool, not only in a callback, so they also hold when the tool is reused in another agent.
- Format: ^T-\d{4}$
- Ownership: owner == tool_context.user_id
- Same answer for missing and forbidden
- Never trust a user ID from arguments
Timeouts and injected dependencies
Build the tool with a factory function that takes the ticket store as an argument and returns the tool. Production passes the real client; tests pass a fake. Inside the tool, wrap the store call in asyncio.wait_for with a short timeout, such as 2 seconds, and turn asyncio.TimeoutError into error_code UPSTREAM_TIMEOUT. Catch the store's own known errors and map them to codes too. Let truly unexpected exceptions propagate so they show up in logs and tests rather than being hidden. A fake store can now return data, return None, raise, or sleep longer than the timeout, which covers every branch of the contract in a few milliseconds.
- Returns fixed records
- Tests ok and NOT_FOUND
- Tests ownership
- Instant
- Sleeps longer than the timeout
- Tests UPSTREAM_TIMEOUT
- Use a short timeout in tests
- Under 0.2 s per test
- Raises a known client error
- Tests error mapping
- No stack trace in the result
- Checks the log line
Call budgets with a before_tool_callback
An agent can loop: call a tool, dislike the answer, call it again. A before_tool_callback runs before every tool call and receives the tool, the arguments and the ToolContext. Keep a counter in tool_context.state under a temp: key, such as temp:tool_calls. temp: keys live only for the current invocation, so the budget resets with each new user message. If the counter passes the limit, return a dictionary such as status error with error_code TOOL_BUDGET_EXCEEDED. ADK then skips the real tool and gives that dictionary to the model, which can apologise and stop. Combine this with RunConfig max_llm_calls, which caps model calls for the whole run.
Observability: one log line per call
Use an after_tool_callback, or a small wrapper, to log each call: invocation ID, tool name, outcome status, error code and duration in milliseconds. Log the ticket ID only if your policy allows it, and never log full ticket text or user messages by default. These lines answer the questions you will ask later: which tool was slow, which error is common, did the budget trigger. In tests, use pytest's caplog fixture to assert that a log line was written with the expected error code.
- invocation_id, tool, status, error_code, ms
- No message bodies in logs by default
- Assert logs with caplog
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Validate arguments in the tool~35m
- 2Check authorisation from session state~35m
- 3Add timeouts and call budgets~35m
- 4Fake dependencies in pytest~35m
- 5Log each tool call~35m
Key points
- Validate format and range of every argument inside the tool; the model can send anything.
- Authorise with tool_context.user_id, which comes from the runner, never from an argument the model chose.
- Wrap slow dependencies in a timeout and return a typed error such as UPSTREAM_TIMEOUT.
- Count tool calls per run in a before_tool_callback with a temp: state key, and refuse calls over budget.
- Inject the ticket store so tests can pass a deterministic fake that returns, fails or hangs on demand.
Key terms
Tap a card to flip it. 0/6 known
Examples
from types import SimpleNamespace
from support_agent.tools import make_ticket_tool
class FakeStore:
async def get(self, ticket_id):
return {"T-1001": {"owner": "user-a", "status": "open"}}.get(ticket_id)
async def test_other_users_ticket_is_hidden():
tool = make_ticket_tool(FakeStore())
ctx = SimpleNamespace(user_id="user-b", state={})
result = await tool("T-1001", ctx)
assert result == {"status": "error", "error_code": "NOT_FOUND"}A pytest test (with pytest-asyncio or anyio) calling the tool directly. No model and no ADK runner are needed.
A tool factory with an injected store and a timeout
make_ticket_tool takes any object with an async get method. The returned function is a normal ADK tool. Tests pass a fake; production passes the real client.
import asyncio, re
from google.adk.tools import ToolContext
def make_ticket_tool(store, timeout_s: float = 2.0):
async def get_ticket_status(ticket_id: str, tool_context: ToolContext) -> dict:
"""Get the status of one ticket owned by the signed-in user. Format T-1234."""
ticket_id = ticket_id.strip().upper()
if not re.fullmatch(r"T-\d{4}", ticket_id):
return {"status": "error", "error_code": "INVALID_ARGUMENT"}
try:
t = await asyncio.wait_for(store.get(ticket_id), timeout_s)
except asyncio.TimeoutError:
return {"status": "error", "error_code": "UPSTREAM_TIMEOUT"}
if t is None or t["owner"] != tool_context.user_id:
return {"status": "error", "error_code": "NOT_FOUND"}
return {"status": "ok", "ticket_id": ticket_id, "ticket_status": t["status"]}
return get_ticket_statusA per-run call budget
The callback counts calls in a temp: key and refuses the third one. Attach it with Agent(..., before_tool_callback=tool_budget). Returning None lets the call go ahead.
from google.adk.tools import BaseTool, ToolContext
MAX_TOOL_CALLS = 2
def tool_budget(tool: BaseTool, args: dict, tool_context: ToolContext):
used = tool_context.state.get("temp:tool_calls", 0) + 1
tool_context.state["temp:tool_calls"] = used
if used > MAX_TOOL_CALLS:
return {"status": "error", "error_code": "TOOL_BUDGET_EXCEEDED"}
return NoneQuick reference
- Rules in code, guidance in the prompt.
- Authorise with tool_context.user_id; never with an argument.
- asyncio.wait_for(dep(), timeout) and map TimeoutError to UPSTREAM_TIMEOUT.
- before_tool_callback returning a dict skips the tool and uses the dict as the result.
- Count calls under a temp: key so the budget resets each invocation.
- Build tools with a factory so tests can inject fakes.
- Test with pytest by calling the tool directly; no model or network.
- Log tool, status, error_code and duration; not message bodies.
Common mistakes
- Putting the rule only in the instruction, such as only look up the user's own tickets, and trusting the model to follow it.
- Testing tools only through a live model, which makes tests slow, costly and flaky.
- Using a plain state key for the call counter, so the count leaks into the next turn instead of resetting.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a pytest test that a lowercase ID like t-1001 is accepted and normalised by the tool from the factory example.
- Exercise 2medium
Add a SlowStore fake and a test proving the tool returns UPSTREAM_TIMEOUT within half a second.
- Exercise 3hard
Test the call budget callback: the first two calls return None, the third returns TOOL_BUDGET_EXCEEDED, and a fresh state dict starts again at zero.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Do I need pytest-asyncio to test async tools?
- You need some async test support. pytest-asyncio or the anyio pytest plugin both work; mark async tests as their docs describe, or run the coroutine with asyncio.run in a plain test.
- Should I test tools through a real model too?
- Yes, but separately and less often. Fast contract tests run on every commit; live-model checks of tool choice belong to the evaluation module.
- Is max_llm_calls enough as a budget?
- It caps model calls for the whole run, which indirectly limits tool calls. A tool call counter is still useful because one model turn can request several tools at once.