Module 08 · Lesson 8.1
Unit Tests for Tools and Agent Components
On this page
- What you will learn
- What a unit test is and why agents need them
- What to test in an agent without calling a model
- Python's built-in unittest module in five minutes
- Example: unit tests for lookup_order and the safety gate
- Write clear tests: one behaviour per test
- Turn a quick check script into a real test
- Conclusion and your next step
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
Think about a bike shop that checks every bike before it leaves. The mechanic does not take it on a long ride first. They squeeze the brakes, spin the wheels and check the bolts. These quick checks find most faults in a minute.
An AI agent has parts like that too. Its tools, its argument checks and its safety gate are ordinary code, and you can check them quickly, without any AI model. This lesson shows you how to write unit tests for them with Python's built-in unittest module. You will also learn what makes a test easy to read and trust. Most of the lesson needs no coding. The example at the end runs eight tests in a blink.
What you will learn
- Explain what a unit test is and why an agent's ordinary code should have them.
- List which agent components you can test without calling a model.
- Write and run a
unittesttest class withassertEqual,assertInandsetUp. - Turn a quick check script into a named test that checks one behaviour.
Before you start
- Modules 1 to 7, especially Designing Tool Schemas and Validating Arguments and the lab from the previous module, Practical Lab: Threat-Model and Harden an Agent.
- No coding experience is needed for most of this lesson.
- Optional: Python 3.10 or later, if you want to run the example yourself.
What a unit test is and why agents need them
A unit test is a small program that runs one piece of your code with a chosen input and checks that the result is what you expected. The "unit" is that one piece, for example a single function. If the result is wrong, the test fails and tells you where to look.
Imagine a vending machine. A unit test is like pressing one button and checking that the right snack drops. You do not need a customer, a coin shop or a delivery truck. You test one button at a time.
Agents need this because they mix two kinds of code. The model is unpredictable: the same question can get slightly different answers. Everything around it is ordinary code: tools, checks, the approval step. Ordinary code gives the same output for the same input, so you can test it with exact answers.
- Unit test
- A small automatic check of one piece of code. It gives the same verdict every time you run it.
- Test case
- One single check inside your tests. Example: "an unknown order number returns an error".
- Assertion
- The line in a test that states what must be true. If it is not true, the test fails.
- Fixture
- The set-up a test needs before it runs, such as an empty queue or a fresh list of sample orders.
What to test in an agent without calling a model
Open your agent project from the earlier labs and look for functions that never talk to a model. Those are your best unit-test targets. They are fast, free and give the same answer every time.
| Component | What to check | Example test |
|---|---|---|
A tool such as lookup_order | Right answer for known input, a clear error for unknown input. | QF-9999 returns {"error": "order not found"}. |
The safety gate run_tool | Unknown tools, extra arguments and bad values are refused before any tool runs. | An order id of ../etc is refused. |
| The approval step | A write only creates a pending request. Nothing is final until a person approves. | request_return adds one pending item and nothing else. |
| A grounding check | Replies that cite a page that was never retrieved are flagged. See Vector Search, Metadata Filters and Source Grounding. | A reply citing KB-14 after a search that found only KB-03 is a problem. |
| A plan validator | Bad plans are rejected before step one runs. | A plan with nine steps is refused. |
| A redaction or output check | Private text is removed. Forbidden words are caught. | An email address in a log line becomes [email]. |
What not to unit test
- The wording of a model's answer. It changes from run to run. Test it later with evaluations.
- Whether the model picks the right tool. That needs scenario tests, covered in the next lesson.
- Google's or another vendor's servers. You cannot fix them, and a test that needs them will fail when the network is slow.
Python's built-in unittest module in five minutes
Python ships with a test tool called unittest. You do not need to install anything. The ideas are few:
- A test class groups related tests. It extends
unittest.TestCase. - A test method is a function inside the class. Its name must start with
test, or Python will not run it. - Inside a test you call assert methods, such as
self.assertEqual(a, b). They fail the test when the claim is false. setUpis a special method that runs before every single test. Use it to reset shared data.
| Assert method | Passes when |
|---|---|
self.assertEqual(a, b) | a equals b. |
self.assertIn(item, things) | item appears inside things, such as a word inside a message. |
self.assertIsNone(x) | x is None, which is Python's way of saying "nothing". |
self.assertTrue(x) | x is true. |
self.assertRaises(SomeError) | The code inside a with block raises that error. |
How to run your tests
Open a terminal in the folder that holds your test file. Then run one of these two commands:
python test_tools.py -v
python -m unittest test_tools -vThe first runs the file directly. The second asks Python to find and run the tests in a module. The -v flag means verbose: it prints one line per test. Without it you only see a dot for each test that passed and an F for each that failed.
Example: unit tests for lookup_order and the safety gate
This file is self-contained. It holds a small copy of the Quillfeather tools from the Module 3 lab, followed by the tests. In your own project you would import the real functions instead. A copy keeps this example runnable on its own. Save everything below, in order, as test_tools.py.
Part 1: the data and two tools
import re
import unittest
ORDERS = {
"QF-1042": {"status": "dispatched", "estimated_delivery": "2026-11-18"},
"QF-1044": {"status": "delivered", "estimated_delivery": "2026-11-09"},
}
REASONS = ["damaged", "wrong_size", "changed_mind"]
PENDING = {}
def lookup_order(order_id):
return ORDERS.get(order_id, {"error": "order not found"})
def request_return(order_id, reason):
order = ORDERS.get(order_id)
if order is None:
return {"error": "order not found"}
if order["status"] != "delivered":
return {"error": "only delivered orders can be returned"}
PENDING[f"{order_id}:{reason}"] = {"order_id": order_id, "reason": reason}
return {"return_request": "waiting for staff approval"}Part 1 of 4. Fictional data and two tools.
Part 2: the safety gate
TOOLS = {"lookup_order": (lookup_order, {"order_id"}), "request_return": (request_return, {"order_id", "reason"})}
def run_tool(name, args):
if name not in TOOLS:
return {"error": f"unknown tool {name}"}
function, allowed = TOOLS[name]
if set(args) != allowed:
return {"error": f"arguments must be exactly {sorted(allowed)}"}
if not re.fullmatch(r"QF-\d{4}", str(args["order_id"])):
return {"error": "order_id must look like QF-1234"}
if name == "request_return" and args["reason"] not in REASONS:
return {"error": f"reason must be one of {REASONS}"}
return function(**args)Part 2 of 4. Add this below part 1. The gate checks every call before a tool runs.
Part 3: tests for lookup_order
class TestLookupOrder(unittest.TestCase):
def test_known_order_returns_its_status(self):
self.assertEqual(lookup_order("QF-1042")["status"], "dispatched")
def test_unknown_order_returns_an_error(self):
self.assertEqual(lookup_order("QF-9999"), {"error": "order not found"})Part 3 of 4. Add this below part 2. Two tests, one behaviour each.
Part 4: tests for the safety gate
class TestSafetyGate(unittest.TestCase):
def setUp(self):
PENDING.clear() # every test starts with an empty queue
def test_unknown_tool_is_refused(self):
self.assertIn("unknown tool", run_tool("delete_order", {})["error"])
def test_extra_argument_is_refused(self):
result = run_tool("lookup_order", {"order_id": "QF-1042", "admin": True})
self.assertIn("arguments must be exactly", result["error"])
def test_bad_order_id_is_refused(self):
self.assertIn("must look like", run_tool("lookup_order", {"order_id": "../etc"})["error"])
def test_bad_reason_is_refused(self):
result = run_tool("request_return", {"order_id": "QF-1044", "reason": "bored"})
self.assertIn("reason must be one of", result["error"])
def test_return_waits_for_approval(self):
run_tool("request_return", {"order_id": "QF-1044", "reason": "damaged"})
self.assertEqual(list(PENDING), ["QF-1044:damaged"])
def test_dispatched_order_cannot_be_returned(self):
result = run_tool("request_return", {"order_id": "QF-1042", "reason": "damaged"})
self.assertEqual(result, {"error": "only delivered orders can be returned"})
self.assertEqual(PENDING, {})
if __name__ == "__main__":
unittest.main()Part 4 of 4. Add this below part 3.
What each part does
import unittestloads the test tool.import reis only for the order-id pattern in the gate.ORDERS,REASONSandPENDINGare made-up shop data and the waiting list of return requests.PENDINGstands in for the approval queue from the Module 3 lab.run_toolis the safety gate: it refuses an unknown tool, wrong arguments, a badly formed order id and an unknown reason, before the real tool runs.class TestLookupOrder(unittest.TestCase)is a test class. Each method that starts withtest_is one test.self.assertEqual(lookup_order("QF-1042")["status"], "dispatched")runs the tool and states what the answer must be.self.assertIn("unknown tool", ...)checks that the error message contains a phrase. It is gentler than an exact match, so a small rewording of the message does not break the test.def setUp(self): PENDING.clear()empties the waiting list before every test, so no test can be affected by another.test_dispatched_order_cannot_be_returnedchecks two things about one rule: the error message, and that nothing was added toPENDING.unittest.main()at the bottom runs all the tests when you run the file.
test_known_order_returns_its_status (__main__.TestLookupOrder.test_known_order_returns_its_status) ... ok
test_unknown_order_returns_an_error (__main__.TestLookupOrder.test_unknown_order_returns_an_error) ... ok
test_bad_order_id_is_refused (__main__.TestSafetyGate.test_bad_order_id_is_refused) ... ok
test_bad_reason_is_refused (__main__.TestSafetyGate.test_bad_reason_is_refused) ... ok
test_dispatched_order_cannot_be_returned (__main__.TestSafetyGate.test_dispatched_order_cannot_be_returned) ... ok
test_extra_argument_is_refused (__main__.TestSafetyGate.test_extra_argument_is_refused) ... ok
test_return_waits_for_approval (__main__.TestSafetyGate.test_return_waits_for_approval) ... ok
test_unknown_tool_is_refused (__main__.TestSafetyGate.test_unknown_tool_is_refused) ... ok
----------------------------------------------------------------------
Ran 8 tests in 0.001s
OKEight lines saying ok, then a final OK. The time on the "Ran 8 tests" line will differ on your machine. Tests run in alphabetical order, which is why TestLookupOrder comes before TestSafetyGate.
What a failing test looks like
To see a failure, change "dispatched" to "delivered" in the first test and run the file again. That test line now ends with FAIL instead of ok, and Python prints the line that failed, followed by a message like this:
AssertionError: 'dispatched' != 'delivered'Read it as "the real answer was the first value and the test expected the second". Change the value back, and the file passes again.
Write clear tests: one behaviour per test
A test is a message to a future reader, often you in six months. When it fails, the reader should know what broke without opening the code.
- Test one behaviour per test. A test called
test_bad_reason_is_refusedhas one job. If it fails, you know exactly which rule broke. - Name the behaviour, not the function.
test_extra_argument_is_refusedsays more thantest_run_tool_2. - Keep tests independent. One test must never depend on another having run first. This is what
setUpis for. - Test the sad paths too. Bad ids, missing orders and wrong reasons are where agents fail. Include at least as many of those as happy paths.
- Use fixed data. Never depend on the real clock, a random number or a live service. Use fixed dates and made-up orders, as the Quillfeather examples do.
- Check the message loosely. Use
assertInfor a key phrase when the exact wording is not important.
Turn a quick check script into a real test
In earlier lessons you wrote small scripts that printed True or False, or PASS and FAIL. They were a good start. Here is one, for the order lookup:
def lookup_order(order_id):
return {"QF-1042": {"status": "dispatched"}}.get(order_id, {"error": "order not found"})
print(lookup_order("QF-1042")["status"] == "dispatched")
print(lookup_order("QF-9999") == {"error": "order not found"})True
TrueThis script has three weaknesses. It prints, but it does not stop or report when something is wrong, so a False is easy to miss. The checks have no names. And you cannot run just one of them.
Step 1: Put each check in its own method
One
print(...)line becomes onetest_...method.Step 2: Name the behaviour
test_unknown_order_returns_an_errorreplaces a bare comparison.Step 3: Replace the print with an assert
Use
self.assertEqual(actual, expected), with the real result first and the expected result second.Step 4: Move set-up into setUp
Anything every test needs, such as an empty queue, goes there.
That is exactly how the two tests in TestLookupOrder above were made. The checks are the same. They now have names, a clear verdict and one run command.
Conclusion and your next step
Most of an agent is ordinary code, and ordinary code can be tested with exact answers. Unit tests for tools, the safety gate, validators and grounding checks run in a moment, cost nothing and point at the exact line when something breaks. Keep each test small, name the behaviour it protects and include the sad paths.
Your next step: pick the safety gate in your own agent project and write five unittest tests for it, including two that must be refused. Then continue to Scenario-Based and End-to-End Agent Tests, where you run the whole agent against scripted model replies.
For related reading, see Tool Errors, Retries, Timeouts and Idempotency, which lists the failures worth testing, or AI Code Review: Catching Bugs Before They Ship.
Common errors and how to fix them
Python reports "Ran 0 tests".
Why it happens: The test methods do not start with test, or the class does not extend unittest.TestCase.
Fix: Rename each method to start with test_ and check the class line reads class Name(unittest.TestCase):.
A test passes alone but fails when all tests run.
Why it happens: Tests share data, such as a pending queue, and one test leaves it changed.
Fix: Reset shared data in setUp so every test starts clean.
The test file cannot import your project code.
Why it happens: You ran Python from a different folder, so it cannot find the project files.
Fix: Open the terminal in the project folder and run python -m unittest from there.
A test breaks whenever someone rewords an error message.
Why it happens: The test compares the whole message text exactly.
Fix: Use assertIn with a key phrase, or test a fixed error code instead of prose.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Write unit tests for a grounding check
Write a unittest test class for the function grounding_problem(sources, retrieved_ids) described below. Write at least four tests, then run them.
You will need
sourcesis a list of page ids that the reply cites, for example["KB-03"].retrieved_idsis the set of page ids the search returned.- If the reply cites any page that is not in
retrieved_ids, the function returns the messagecites a passage that was not retrieved. - If the search returned pages but the reply cites none, it returns
answers after a search but cites no source. - In every other case it returns
None.
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- Write the function first, from the three rules, in the same file.
- Use
assertIsNonewhen the function should return nothing, andassertEqualfor a message. - Pass a set such as
{"KB-03", "KB-04"}forretrieved_ids, and an empty setset()for "nothing retrieved".
Show a model answer
A strong answer has four test methods in one class. test_cited_passage_was_retrieved calls the function with ["KB-03"] and {"KB-03", "KB-04"} and uses assertIsNone. test_cited_passage_was_not_retrieved passes ["KB-14"] with {"KB-03"} and expects the first message. test_no_sources_after_a_search_is_a_problem passes [] with {"KB-03"} and expects the second message. test_no_search_and_no_sources_is_fine passes [] and set() and expects None. The function itself first checks set(sources) <= set(retrieved_ids), then checks retrieved_ids and not sources, and otherwise returns None. The last test matters because it stops a future change from flagging every answer that needed no search.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. The gate is ordinary code and gives the same result every time, so exact checks work. Model wording and model choices vary between runs. They are tempting to check here, but they need scenario tests and evaluations.
Show the answer and explanation
Answer: A. Independent tests give the same verdict in any order. Speed is not the reason, which makes the second option tempting.
setUpis optional, so the third is wrong.Show the answer and explanation
Answer: B. It names the behaviour, so a failure message tells you which rule broke.
test_run_toolnames the function, but the gate has many rules, so it does not say which one failed.
Frequently asked questions
What is a unit test in simple words?
It is a tiny program that runs one piece of your code with a chosen input and checks that the answer is correct. Think of pressing one button on a machine and checking what comes out. It runs in a fraction of a second and gives the same verdict every time.
Should I use unittest or pytest?
Either works. unittest is built into Python, so it needs no installation, and that is why this lesson uses it. pytest is a popular add-on that needs less typing and can also run unittest tests. The ideas you learn here carry over to both.
Can I unit test the AI model itself?
Not in the same way. A model's answers vary, so exact checks are fragile. Unit test the code around the model. Check the model's behaviour with scenario tests and evaluation datasets, which later lessons cover.
How many unit tests are enough?
Enough that you would be nervous to change a tool without running them. A practical start is one good-input test and one bad-input test per tool, plus one test for every rule in the safety gate. Add a new test every time you find a bug.
- Written by
- PromptFable Editorial
- Last updated 18 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- unittest: Unit testing framework(opens in a new tab)
Python Software Foundation · Official documentation · Test cases, assert methods, setUp and the command line for running tests.
- re: Regular expression operations(opens in a new tab)
Python Software Foundation · Official documentation · Background for the `re.fullmatch` check on order ids.
- Building effective agents(opens in a new tab)
Anthropic · Official documentation · Advice on keeping agents simple, including testing them carefully.
- Demystifying evals for AI agents(opens in a new tab)
Anthropic · Official documentation · Why agents also need evaluations beyond ordinary tests.
- LLM06:2025 Excessive Agency(opens in a new tab)
OWASP Foundation · Official documentation · Why limits on what tools may do are worth testing.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.