Skip to content

Module 08 · Lesson 8.1

Unit Tests for Tools and Agent Components

40 minUpdated 18 Nov 2026Part of Testing and Evaluation · AI Agent Development
On this page
  1. What you will learn
  2. What a unit test is and why agents need them
  3. What to test in an agent without calling a model
  4. Python's built-in unittest module in five minutes
  5. Example: unit tests for lookup_order and the safety gate
  6. Write clear tests: one behaviour per test
  7. Turn a quick check script into a real test
  8. Conclusion and your next step
  9. Common errors and fixes
  10. Validation checklist
  11. Hands-on exercise
  12. Knowledge check
  13. Frequently asked questions
  14. 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 unittest test class with assertEqual, assertIn and setUp.
  • Turn a quick check script into a named test that checks one behaviour.

Before you start

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.

ComponentWhat to checkExample test
A tool such as lookup_orderRight answer for known input, a clear error for unknown input.QF-9999 returns {"error": "order not found"}.
The safety gate run_toolUnknown tools, extra arguments and bad values are refused before any tool runs.An order id of ../etc is refused.
The approval stepA write only creates a pending request. Nothing is final until a person approves.request_return adds one pending item and nothing else.
A grounding checkReplies 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 validatorBad plans are rejected before step one runs.A plan with nine steps is refused.
A redaction or output checkPrivate text is removed. Forbidden words are caught.An email address in a log line becomes [email].
Each row is ordinary code. None of these tests needs an API key or an internet connection.

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.
  • setUp is a special method that runs before every single test. Use it to reset shared data.
Assert methodPasses 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.
Five assert methods are enough for most agent tests. The unittest documentation (opens in a new tab) lists the rest.

How to run your tests

Open a terminal in the folder that holds your test file. Then run one of these two commands:

Text
python test_tools.py -v
python -m unittest test_tools -v

The 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

Pythontest_tools.py
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

Pythontest_tools.py
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

Pythontest_tools.py
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

Pythontest_tools.py
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 unittest loads the test tool. import re is only for the order-id pattern in the gate.
  • ORDERS, REASONS and PENDING are made-up shop data and the waiting list of return requests. PENDING stands in for the approval queue from the Module 3 lab.
  • run_tool is 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 with test_ 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_returned checks two things about one rule: the error message, and that nothing was added to PENDING.
  • unittest.main() at the bottom runs all the tests when you run the file.
Output of python test_tools.py -vCaptured from a real run
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

OK

Eight 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:

Text
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_refused has one job. If it fails, you know exactly which rule broke.
  • Name the behaviour, not the function. test_extra_argument_is_refused says more than test_run_tool_2.
  • Keep tests independent. One test must never depend on another having run first. This is what setUp is 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 assertIn for 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:

Pythonold_check.py
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"})
Expected outputCaptured from a real run
True
True

This 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.

  1. Step 1: Put each check in its own method

    One print(...) line becomes one test_... method.

  2. Step 2: Name the behaviour

    test_unknown_order_returns_an_error replaces a bare comparison.

  3. Step 3: Replace the print with an assert

    Use self.assertEqual(actual, expected), with the real result first and the expected result second.

  4. 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

  • sources is a list of page ids that the reply cites, for example ["KB-03"]. retrieved_ids is the set of page ids the search returned.
  • If the reply cites any page that is not in retrieved_ids, the function returns the message cites 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 assertIsNone when the function should return nothing, and assertEqual for a message.
  • Pass a set such as {"KB-03", "KB-04"} for retrieved_ids, and an empty set set() 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.

  1. 1.Which agent component is the best target for a unit test?
    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.

  2. 2.Why does the example use setUp to clear the pending queue?
    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. setUp is optional, so the third is wrong.

  3. 3.What is the best name for a test that checks a bad order id is refused?
    Show the answer and explanation

    Answer: B. It names the behaviour, so a failure message tells you which rule broke. test_run_tool names 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.

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.