Skip to content
/

Test it without a model

Ready for real workChapter 11 of 156 min read

Every run so far has called the model, which costs money and gives a different memo each time. So this chapter answers: how do you test the desk without a model?


In a test, a stand-in takes the agent's place and hands the desk a memo you chose:

Drawing diagram…
InputToolResultA stand-in in the agent's place
  • Stand-in: a small function that answers in place of the agent, with an answer the test picks.
  • monkeypatch: pytest's tool for swapping a name for a stand-in during one test.

Set up#

If you closed the terminal, go back into the folder and switch the environment on, then install pytest:

Terminal
$ cd document-desk
$ source env/bin/activate
(env)$ pip install pytest

A test needs names it can import, so the agent moves into its own file. Let's save this as agents.py:

agents.py
# agents.py
from crewai import Agent


def write_memo(text):
    writer = Agent(
        role="Contract analyst",
        goal="Tell a manager what could cost them money",
        backstory="You read contracts for a small company.",
    )
    answer = writer.kickoff(
        "Write a memo of at most 60 words about the risks in this contract. "
        "Give the last day to send notice that stops the renewal, as a full date.\n\n" + text
    )
    return answer.raw

The desk calls agents.write_memo, and checks the memo the way chapter 10 did. Let's save this as desk.py:

desk.py
# desk.py
from datetime import date, timedelta

from crewai.flow.flow import Flow, listen, start
from dotenv import load_dotenv
from pydantic import BaseModel, ConfigDict

import agents

load_dotenv()


class DeskState(BaseModel):
    model_config = ConfigDict(validate_assignment=True)

    text: str = ""
    memo: str = ""


class Desk(Flow[DeskState]):
    suppress_flow_events = True

    @start()
    def read_document(self):
        with open("inbox/acme-saas-agreement.md") as file:
            self.state.text = file.read()

    @listen(read_document)
    def review_contract(self):
        self.state.memo = agents.write_memo(self.state.text)

    @listen(review_contract)
    def check_memo(self):
        deadline = date(2027, 2, 28) - timedelta(days=60)
        written = f"{deadline:%B} {deadline.day}, {deadline.year}"
        forms = [written, f"{deadline.day} {deadline:%B %Y}", str(deadline)]
        if any(form in self.state.memo for form in forms):
            return "the memo has the deadline"
        return f"Notice is due by {written}, and the memo doesn't say so."

Way 1: test with the real agent#

The test runs the desk, and expects the finding. Let's save this as test_desk.py:

test_desk.py
# test_desk.py
from desk import Desk


def test_a_wrong_deadline_is_found():
    assert Desk().kickoff() == "Notice is due by December 30, 2026, and the memo doesn't say so."
Terminal
(env)$ python -m pytest -q
Output
.                                                                        [100%]...1 passed, 4 warnings in 5.63s

Each dot is a test that passed, and ... stands for warnings CrewAI prints about its own deprecated settings. It passed, but only because the agent wrote a wrong date. The test can't choose the memo, so it checks the agent as much as your code:

Drawing diagram…
InputAgentResultThe test depends on the model

On a day the agent gets December 30 right, this test fails, though your code is fine. And every run calls the model with your key.

Way 2: a stand-in for the agent#

monkeypatch.setattr(agents, "write_memo", ...) puts a stand-in in place of write_memo for one test, and puts the real one back after. lambda text: "..." is a one-line function that takes the text and gives back that memo, so each test picks its memo. Change test_desk.py:

test_desk.py
# test_desk.py
import agents
from desk import Desk


def test_a_wrong_deadline_is_found(monkeypatch):
    monkeypatch.setattr(agents, "write_memo", lambda text: "Send notice by December 31, 2026.")
    assert Desk().kickoff() == "Notice is due by December 30, 2026, and the memo doesn't say so."


def test_a_right_deadline_passes(monkeypatch):
    monkeypatch.setattr(agents, "write_memo", lambda text: "Send notice by December 30, 2026.")
    assert Desk().kickoff() == "the memo has the deadline"
Terminal
(env)$ python -m pytest -q
Output
..                                                                       [100%]2 passed in 2.59s

Two tests now, one for each memo, and no model was called. The stand-in answers in place of the agent:

Drawing diagram…
InputToolResultThe stand-in hands over the memo

A stand-in in the wrong place#

Python also lets desk.py import the function by itself. Add the import to desk.py:

Python
from agents import write_memo

Change review_contract in desk.py:

Python
    @listen(read_document)
    def review_contract(self):
        self.state.memo = write_memo(self.state.text)
Terminal
(env)$ python -m pytest -q
Output
.F                                                                       [100%]...>       assert Desk().kickoff() == "the memo has the deadline"E       assert "Notice is du...esn't say so." == 'the memo has the deadline'E         E         - the memo has the deadlineE         + Notice is due by December 30, 2026, and the memo doesn't say so....FAILED test_desk.py::test_a_right_deadline_passes - assert "Notice is du...es...1 failed, 1 passed, 8 warnings in 8.82s

The right-date test failed: the desk said the deadline was missing, though the stand-in's memo has it. ... stands for lines we left out. The stand-in never ran, and the real agent wrote the memo:

Drawing diagram…
InputToolResultTwo names for one function

from agents import write_memo gives desk.py a name of its own when the file loads. The test swaps the name inside agents, which desk.py no longer looks at. Calling agents.write_memo looks the name up on every call, so the swap is seen.

Change review_contract in desk.py back:

Python
    @listen(read_document)
    def review_contract(self):
        self.state.memo = agents.write_memo(self.state.text)
Terminal
(env)$ python -m pytest -q
Output
..                                                                       [100%]2 passed in 2.96s

The folder keeps agents.py, desk.py and test_desk.py for the next chapter.

The two ways side by side#

Compare what each test run needs:

Drawing diagram…
InputResultWhat a test run needs

Test your own code with stand-ins for the agents, so each test picks what the agent said and needs no key.

Drawing diagram…
InputResultA stand-in or the real agent?

What comes next#

The desk finds what's wrong, but nobody looks before a report is filed:

Drawing diagram…
InputToolResultFiled with no one looking

Who agrees to the report before it's filed?