20  Testing

Seventeen chapters have ended the same way: build the graph, run it, read the output, decide it looks right. That habit is the book’s method and it has served you well — but it is not testing. Reading output is a claim that holds only while you are watching. A test is the same claim written down so it holds when you are not: at three in the morning, on someone else’s branch, six months after you have forgotten why the router had two arms.

Agents make this harder than ordinary software, and the reason is worth naming before any code. A graph run has a nondeterministic part — what the model decides — wrapped in a completely deterministic one: your state shape, your reducers, your edges, your tool dispatch. Almost every bug you have hit in this book lived in the deterministic half. A tool returned the wrong shape (Chapter 7); a reducer overwrote instead of appending (Chapter 10); a router forgot its back-edge (Section 13.4). None of those needed a model to reproduce, and none of them should need one to catch.

So this chapter takes the model out. Eleven tests, no model server, and the whole suite finishes in a third of a second.

20.1 What we’re building

The doc-bot you already know — a model node, a tools node, a router between them, and a back-edge — packaged so it can be imported without running, and then approached at four altitudes:

flowchart LR
    subgraph L4["Level 4 — the whole graph"]
      direction LR
      START(["START"]) --> model{"model"}
      model -.->|tool_calls| tools["tools"]
      model -.->|none| END(["END"])
      tools --> model
    end
    L1["Level 1<br/>one node"] -.-> tools
    L2["Level 2<br/>the router"] -.-> model
    L3["Level 3<br/>plant a state<br/>as_node=&quot;model&quot;"] -.-> model

If you would rather run something before reading further, start at Level 2: a router test (Section 20.5) needs no model server and no checkpointer. Run it once, change the expected route, run it again, and come back — the scripted model that tests the whole loop is what the rest of this section sets up.

That is the whole system under test, and it is worth reading before the tests that poke at it — every assertion in this chapter is about one of these five names:

TOOLS = [search_docs, web_search]
BY_NAME = {t.name: t for t in TOOLS}


@dataclass
class Context:
    """Per-run values. The model is one of them -- that is the testing seam."""

    llm: BaseChatModel


class State(TypedDict):
    messages: Annotated[list, add_messages]
    tools_used: Annotated[list[str], operator.add]


def model(state: State, runtime: Runtime[Context]) -> dict:
    """Ask the model what to do next. Returns ONLY a messages delta."""
    reply = runtime.context.llm.bind_tools(TOOLS).invoke(state["messages"])
    return {"messages": [reply]}


def tools(state: State) -> dict:
    """Run whatever the model asked for. Needs no context, so a test can reach
    it through `graph.nodes["tools"]`."""
    calls = state["messages"][-1].tool_calls
    results, used = [], []
    for call in calls:
        output = BY_NAME[call["name"]].invoke(call["args"])
        results.append(ToolMessage(content=output, tool_call_id=call["id"]))
        used.append(call["name"])
    return {"messages": results, "tools_used": used}


def route(state: State) -> str:
    """Tool calls pending -> run them; otherwise the answer is final."""
    return "tools" if state["messages"][-1].tool_calls else END
def build_docbot() -> StateGraph:
    """The UNCOMPILED builder. Tests compile their own copy."""
    builder = StateGraph(State, context_schema=Context)
    builder.add_node("model", model)
    builder.add_node("tools", tools)
    builder.add_edge(START, "model")
    builder.add_conditional_edges(
        "model", route, {"tools": "tools", END: END}
    )
    builder.add_edge("tools", "model")
    return builder

flowchart TD
    START(["START"]) --> model{"model"}
    model -.->|tool_calls| tools["tools"]
    model -.->|none| END(["END"])
    tools --> model

search_docs and web_search are the doc-bot’s usual two, unchanged; BY_NAME is how a name becomes a callable, because the model only ever asks for a tool by name (Chapter 13). Building both from one list is what keeps the set the model is shown and the set your code can run from drifting apart.

Two details carry the chapter. build_docbot() returns the uncompiled builder, so each test compiles its own copy with its own checkpointer and nothing is decided at import time. And the model arrives through Context rather than being constructed inside model() — the seam the next section takes apart, which is why Context appears there a second time.

Each level buys a different thing. One node in isolation tells you what a node returns. The router in isolation tells you which edge a state takes. A planted state lets you test the middle of a run without paying for its beginning. The whole graph tells you the pieces are wired to each other and not merely correct apart. You want all four, and you want them in that order, because when the level-4 test goes red the level-1 tests are what tell you where.

20.2 A test is not an evaluation

The two get confused constantly, and running them on the same schedule is how a build turns flaky. A test asks did my code do what I wired it to do — the answer is yes or no, the same yes or no on every machine as long as the model is scripted out of it, and a red one means someone broke something. An evaluation asks is the model’s behaviour good enough — the answer is a number, it moves between runs on identical code, and it is compared to a threshold rather than to the truth.

Everything in this chapter is the first kind. Chapter 32 is the second kind, and Chapter 33 lays the two side by side once you have both in hand. The practical consequence is a scheduling rule you can adopt today: tests run on every commit and block the merge; evaluations run on a schedule and open a conversation — until an evaluation set has been grown and calibrated enough to gate a release, which is the third row of the table Chapter 32 ends its gate with.

20.3 The seam: a model the test writes

A test cannot assert on a real model’s output, because a real model is the thing that is allowed to vary. So the test supplies its own — one that says exactly what the test needs said:

from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel


1class ScriptedModel(FakeMessagesListChatModel):
2    def bind_tools(self, tools, **kwargs):
        return self


def searches_then_answers() -> ScriptedModel:
3    return ScriptedModel(responses=[
        AIMessage(content="", tool_calls=[
            {"name": "search_docs", "args": {"query": "kafka batch"}, "id": "c1"},
        ]),
        AIMessage(content="Set spring.kafka.listener.type=batch."),
    ])
1
FakeMessagesListChatModel ships with langchain-core. It hands back its responses in order, one per call, and ignores what it was asked.
2
Two lines that are easy to miss, and without which every test here dies on NotImplementedError: the base class does not implement bind_tools, and model() calls it. Returning self is the right answer — the script decides the reply, so the tool schemas have nothing to contribute.
3
A script, not a mock. It never looks at the question: ask about Kafka, ask about Redis, ask nonsense, and these same two replies come back. What lines it up with the run is call order — the first reply to the first call, the second to the second. Here that is a tool call, then an answer, so the doc-bot’s loop goes model → tools → model → END and the messages land as ["human", "ai", "tool", "ai"], which is what Section 20.7 asserts on. Nothing here checks that the model was called in a particular way; the script just makes the model’s half of the run knowable so the assertions can be about your half.
TipTry it: swap in a mock, and find out what the fake is for

Replace the scripted model with a bare MagicMock() and run the suite. Most of it goes red on one repeated error — NotImplementedError: Unsupported message type — and what survives is the set of tests that never put a model’s output into the graph. That list is worth having: it is exactly the tests that do not really depend on a model.

Now try to fix it, and watch where a mock is easy to get wrong. The node calls runtime.context.llm.bind_tools(TOOLS).invoke(...) — two layers. Configure only the inner one (mock.invoke.return_value = AIMessage(content="done")) and it fails the same way: bind_tools(TOOLS) returns a fresh child mock whose .invoke() hands back a MagicMock, and coercion rejects it again. Configure both — mock.bind_tools.return_value = mock alongside the invoke return — and it works: route reads the real AIMessage’s tool_calls (an empty list), takes the END branch, and the run finishes in a single model call.

So a correct mock is entirely possible; the catch is that you have to mock exactly the layers your code touches, and get each one’s return type right. That is why the library ships fakes: not because a mock can’t work, but because the chat-model interface is wide and a fake covers it once. BaseChatModel exposes 75 public methods on the pinned langchain-core 1.6.9 — invoke, stream, batch, an async twin of each, bind_tools, with_structured_output, the callback plumbing — and a stand-in has to behave on every one your code or the runtime happens to reach for. Writing that by hand is a project of its own.

You don’t have to: you only need to provide _generate — given the messages so far, return the reply. Here is the whole of FakeMessagesListChatModel, trimmed of its type annotations and an optional sleep:

class FakeMessagesListChatModel(BaseChatModel):
    responses: list[BaseMessage]      # the script, in order
    i: int = 0                        # how far into it we are

    def _generate(self, messages, **kwargs) -> ChatResult:
        response = self.responses[self.i]       # note: `messages` is never read
        if self.i < len(self.responses) - 1:    # walk the script, then start over
            self.i += 1
        else:
            self.i = 0
        generation = ChatGeneration(message=response)
        return ChatResult(generations=[generation])

    @property
    def _llm_type(self) -> str:                 # also required: a name for traces
        return "fake-messages-list-chat-model"

Thirty-two lines in the real file, and the load-bearing one ignores its input. That is exactly what makes it a script rather than a mock.

It is also why the fakes arrive as a family rather than one class: each answers that same question differently. ParrotFakeChatModel returns ChatGeneration(message=messages[-1]) — whatever you just sent it. GenericFakeChatModel adds a _stream so a test can watch tokens arrive one at a time.

The reason a script can be dropped in at all is a decision made ten chapters ago. The doc-bot’s Context carries the model:

@dataclass
class Context:
    llm: BaseChatModel

model() reads runtime.context.llm instead of constructing a ChatOpenAI of its own, so a test changes the model by passing a different context= and not one node changes. That is what Section 14.8 meant by a seam, cashed in. A doc-bot that built its model inside the node could still be tested — you would monkeypatch or patch the constructor to keep the network out — but that is a sharper tool aimed at a smaller target. The injected seam is the cleaner default, and the reason you do not have to reach for the patch here.

20.4 Level 1: one node, no graph

A compiled graph will hand you its nodes. graph.nodes["tools"] is the tools node, and it will run on a state you hand it, with no graph around it and no checkpointer underneath:

def test_tools_node_returns_a_delta_not_a_state():
    graph = build_docbot().compile()
    ai = AIMessage(content="", tool_calls=[
        {"name": "search_docs", "args": {"query": "kafka"}, "id": "c1"},
    ])

1    prior = {"messages": [ai], "tools_used": ["web_search"]}
    out = graph.nodes["tools"].invoke(prior)

    assert set(out) == {"messages", "tools_used"}
2    assert out["tools_used"] == ["search_docs"]
    assert len(out["messages"]) == 1
    assert isinstance(out["messages"][0], ToolMessage)
    assert "spring.kafka.listener.type=batch" in out["messages"][0].content
1
A history to be a delta against. With tools_used=[] the two implementations this test exists to tell apart — returning used, and returning state["tools_used"] + used — produce the identical result, and the test passes on both.
2
The assertions that earn this level its place. What comes back is the node’s return value — this turn only — not a merged state. There is no graph here to do the merging, so add_messages never ran and operator.add never ran.

Note what the test did not need: a model, a checkpointer, a thread, or the model node. It is a unit test of a function that happens to live in a graph.

Below even this sits the tool itself: search_docs.invoke({"query": "kafka"}) runs it with no graph and no state at all. A tool is an ordinary function wearing a schema, and both halves deserve a line of test — the schema is the contract the model reads (Section 13.6), and it is the half that breaks silently.

WarningGotcha: graph.nodes[...] cannot hand a node its context

The trick above works on tools and fails on model, and the failure is worth seeing once:

graph.nodes["model"].invoke({"messages": [], "tools_used": []})
# ValueError: Missing required config key 'N/A' for 'model'.

model reads runtime.context.llm, and there is no way to supply a context through this call. graph.nodes is a plain dict of PregelNodes, and a PregelNode’s invoke is (input, config=None, **kwargs): no context parameter, no configurable key that stands in for one, and a context= passed anyway is swallowed by the **kwargs. The error message compounds it by naming a config key when the missing thing is the runtime context.

The fix is not a workaround, it is a change of altitude. Your nodes are plain Python functions — model is declared def model(state: State, runtime: Runtime[Context]) -> dict — so import it and call it, passing the two arguments the graph would have passed:

out = model(
    {"messages": [HumanMessage("How do I configure Kafka?")], "tools_used": []},
    Runtime(context=Context(llm=searches_then_answers())),
)
1assert set(out) == {"messages"}
assert out["messages"][0].tool_calls[0]["name"] == "search_docs"
1
One key. model never writes tools_used, and the delta is the proof — which the graph.nodes[...] route could not have told you here anyway.

Runtime takes every field as a keyword with a default, so Runtime(context=…) is the whole construction; its stream_writer and heartbeat are no-ops that a test never notices. Reach for graph.nodes[...] when you specifically want the node as the graph will call it, and for the function when you want the function.

20.5 Level 2: a router is a function

Conditional edges have caused more quiet misbehaviour in this book than any other construct, and they are the cheapest thing in the graph to test, because a router is a function from state to a node name:

@pytest.mark.parametrize("last, expected", [
    (AIMessage(content="", tool_calls=[
        {"name": "search_docs", "args": {"query": "k"}, "id": "c1"}]), "tools"),
    (AIMessage(content="Here is the answer."), END),
])
def test_route_picks_the_edge(last, expected):
    assert route({"messages": [last], "tools_used": []}) == expected

parametrize runs the body once per row and reports them as separate tests, so a red build names the arm that broke rather than the function that contains it. When a router grows a third branch, this is the test that costs one line to extend — and the one that notices when the new condition quietly swallows an old arm.

What it does not check is that "tools" is still a node. The test hard-codes the name and so does the router, so both stay wrong together. You do not need a test for that one: compile() refuses a branch whose target does not exist, and says so precisely — At 'model' node, 'route' branch found unknown target 'tools'.

20.6 Level 3: start in the middle

Here is the level that changes how you test graphs.

Suppose you want to check what happens after the model has asked for search_docs. Getting there means running the model node, which means scripting a model, which means the test now depends on two things instead of one. For a two-node graph that is tolerable. For the RAG pipeline coming in Chapter 27, or a real agent ten supersteps deep, it is how test suites turn into second-run integration tests nobody trusts.

update_state writes a checkpoint directly, and its as_node= argument says which node to pretend wrote it. This is also the first test that takes a compiled parameter — a pytest fixture, meaning a function pytest runs for you and passes in, once per test that names it:

@pytest.fixture
def compiled():
    return build_docbot().compile(checkpointer=InMemorySaver())

A fresh graph, and a fresh checkpointer, for every test that asks. Both halves of that matter, and the Gotcha at the end of the chapter is about what goes wrong when the checkpointer is shared instead.

def test_partial_path_from_a_planted_state(compiled):
    config = {"configurable": {"thread_id": "partial"}}
    planted = AIMessage(content="", tool_calls=[
        {"name": "search_docs", "args": {"query": "redis pool"}, "id": "c9"},
    ])

1    compiled.update_state(config, {"messages": [planted]}, as_node="model")

2    assert compiled.get_state(config).next == ("tools",)

3    out = compiled.invoke(None, config, context=Context(llm=ScriptedModel(
        responses=[AIMessage(content="Use lettuce.pool.max-active.")])))

    assert out["tools_used"] == ["search_docs"]
    assert "lettuce.pool.max-active" in out["messages"][-1].content
1
as_node="model" is the whole trick. The write lands on the thread as though model had produced it, which means the graph’s outgoing edges from model apply to it.
2
And they have already been applied: next is ("tools",). The router ran on the planted state, at update_state time, without the model node ever executing. That single assertion tests a routing decision at its real position in the graph, which is something neither Level 1 nor Level 2 can do.
3
Two things ride on this one call. invoke(None, …) means continue from the checkpoint, the same resume you first used in Chapter 8; passing a state here would start a new run instead. And context= has to come along again, because runtime context is per-run and not checkpointed — resume without it and runtime.context is None, so model dies on runtime.context.llm. The state came out of storage; the dependencies did not. That is the same split Section 14.8 drew and Chapter 26’s secrets Gotcha leans on: what is in State is written down, and what is in context never is.

The technique generalizes past testing: as_node is how you reproduce a customer’s bug report without reproducing the twenty turns that led to it.

NoteDeep Dive: interrupt_after is a different tool here than in Chapter 9

Section 9.4 used interrupt() to stop a run and ask a human. interrupt_after is the other kind of stop: a static one, named at call time by the caller, that needs no cooperation from the graph:

compiled.invoke(
    {"messages": [HumanMessage("How do I configure Kafka?")], "tools_used": []},
    config,
    context=Context(llm=searches_then_answers()),
    interrupt_after=["model"],
)

snapshot = compiled.get_state(config)
assert snapshot.next == ("tools",)          # stopped before running them
assert snapshot.values["tools_used"] == []  # so nothing ran yet

interrupt_after can also be baked into compile(), and a graph compiled that way really does carry the gate into production. Passing it per call instead is what makes it a test instrument: the shipped graph has no gate, and a test can still freeze a run at any node boundary and read the thread there. A dynamic interrupt() has no such choice — it has to be in the node, which means it is in production too.

20.7 Level 4: the whole graph

Finally, the real topology, end to end, with the model scripted:

def test_the_whole_loop_searches_then_answers(compiled):
    out = compiled.invoke(
        {"messages": [HumanMessage("How do I configure Kafka?")], "tools_used": []},
        {"configurable": {"thread_id": "whole"}},
        context=Context(llm=searches_then_answers()),
    )

1    assert out["tools_used"] == ["search_docs"]
2    assert [m.type for m in out["messages"]] == ["human", "ai", "tool", "ai"]
3    assert not out["messages"][-1].tool_calls
1
What actually ran. The scripted model asked for search_docs; this records that the tool node really executed it.
2
The shape of the exchange: ask, call, result, answer — four messages, in order.
3
The run finished clean, with no tool request left unexecuted. Read the two names carefully: tool_calls is an attribute of the AIMessage — what the model asked for — while tools_used in 1 is this graph’s own state field, what the tool node did. Different halves of the same turn, and only AIMessage carries tool_calls at all.

Assertion 3 is the one the other two cannot replace. A broken topology usually shows up in the shape of the exchange, which 2 already pins; what it cannot see is a run whose shape is right and whose last step is still unfinished — the model asked for a tool and the router sent it to END anyway.

What each assertion is actually guarding.
If this breaks What the run looks like Which assertion fails
the tools → model back-edge stops after the tool: ["human", "ai", "tool"] 2 — 3 never gets its turn, and could not have helped anyway: a ToolMessage has no .tool_calls to read
the loop’s turn count a message too few, or too many 2
the router’s arm shape is still ["human", "ai", "tool", "ai"] — but the last ai is holding a tool call nobody ran 3

Assertion 3 also proves less than it looks. It proves the loop ends when the model lets it, which is guaranteed here because the script is two messages long. A real model on a bad day asks for a tool, reads the result, and asks for the same tool again. The scripted model makes that case cheap to arrange, and it is the one production failure in this book that costs real money:

def test_the_loop_cannot_run_away(compiled):
    class NeverStops(ScriptedModel):
        def invoke(self, *args, **kwargs):
            return AIMessage(content="", tool_calls=[
                {"name": "search_docs", "args": {"query": "x"}, "id": "c"}])

    with pytest.raises(GraphRecursionError):
        compiled.invoke(
            {"messages": [HumanMessage("Hello!")], "tools_used": []},
            {"configurable": {"thread_id": "runaway"}, "recursion_limit": 6},
            context=Context(llm=NeverStops(responses=[])),
        )

flowchart LR
    START(["START"]) --> model{"model"}
    model -.->|tool_calls — every turn| tools["tools"]
    tools -->|back-edge| model
    model -.->|none| END(["END"])
    model --> boom["GraphRecursionError<br/>after the 6th superstep,<br/>before a 7th is scheduled"]
    classDef never fill:none,stroke:#bbb,color:#999,stroke-dasharray:4 4;
    classDef bad fill:#fde2e2,stroke:#c0392b;
    class END never;
    class boom bad;

Chapter 6 introduced recursion_limit as a fuse and nothing since has checked that it is reachable. This is that check: a scripted model that never stops asking for a tool, and an assertion that the fuse blows instead of the run spinning. It is the only test here that exercises the fuse at all — which is not the same as proving no input can hang the bot.

NeverStops is shaped unlike the other scripts here: rather than data — ScriptedModel(responses=[…]) — it overrides invoke, so each call builds a fresh AIMessage and the fake keeps pumping out new turns.

WarningGotcha: a fresh checkpointer per test, or the tests start testing each other

A checkpointer keyed by thread_id is shared mutable state, and a test suite is the one place you are guaranteed to reuse ids. Build it inside the test — the compiled fixture from Section 20.6 is the tidy way — and never at module scope, where the second test resumes the first one’s thread and gets four messages where it expected two. No test errors; the suite just starts depending on the order its tests happen to run in, which is the failure mode hardest to read, because every test still passes on its own. It is also why build_docbot() returns the uncompiled builder: a module-level compiled graph is a module-level checkpointer waiting to happen.

20.8 Running it

The doc-bot lives in code/ch18_docbot.py and its suite in code/ch18_test_docbot.py. pytest (pip install pytest==9.1.1) is the book’s one dev-time dependency — nothing the doc-bot ships imports it:

$ pytest code/ch18_test_docbot.py -v

ch18_test_docbot.py::test_tools_node_returns_a_delta_not_a_state PASSED  [  9%]
ch18_test_docbot.py::test_model_node_is_a_plain_function_and_takes_a_scripted_model PASSED [ 18%]
ch18_test_docbot.py::test_nodes_dict_cannot_supply_context PASSED        [ 27%]
ch18_test_docbot.py::test_route_picks_the_edge[last0-tools] PASSED       [ 36%]
ch18_test_docbot.py::test_route_picks_the_edge[last1-__end__] PASSED     [ 45%]
ch18_test_docbot.py::test_partial_path_from_a_planted_state PASSED       [ 54%]
ch18_test_docbot.py::test_interrupt_after_stops_the_run_for_inspection PASSED [ 63%]
ch18_test_docbot.py::test_the_whole_loop_searches_then_answers PASSED    [ 72%]
ch18_test_docbot.py::test_no_tool_call_means_no_tools_node PASSED        [ 81%]
ch18_test_docbot.py::test_the_loop_cannot_run_away PASSED                [ 90%]
ch18_test_docbot.py::test_each_test_gets_its_own_checkpointer PASSED     [100%]

============================== 11 passed in 0.35s ==============================

Eleven tests, no model server, no network, a third of a second. That number is the point of the chapter. A suite this fast runs on every save; a suite that needs a GPU and ninety seconds runs when someone remembers, which is to say in the pull request where it is least welcome.

20.9 The operational rule

Test the deterministic half, and script the other half so it stops being a variable.

  • Put the model in Context, not in the node. Every other habit here depends on that one, and it costs nothing on the day you write the node.
  • Assert on structure, never on prose — which tools ran, in what order, what shape came back, whether the loop ended. Text belongs in an assertion only when your own test wrote the text.
  • Plant states instead of reaching them. update_state(as_node=…) turns a multi-superstep setup into one line, and tests the routing decision where it really happens.
  • Build the checkpointer inside the test. Shared savers make suites that pass alone and fail together.

These all call invoke. A graph with an async def node in it answers ainvoke only, and every test here works against ainvoke once pytest can run an async def — which needs a plugin (pytest-asyncio), the one piece of test tooling this book leaves you to install yourself.

What none of this tells you is whether the doc-bot is any good. Every test in this chapter would still pass if the model answered every question with the wrong document, because the script would be the one answering. That question needs real model output, a dataset, and a number; Chapter 32 is where we ask it, once Part III has built a retrieval pipeline worth measuring.

That closes Part II. The doc-bot can decide, remember, speak in real time, be guarded at its seams, and now prove that the half of it you wrote still works. What it cannot yet do is survive contact with production. Nodes fail, networks time out, the model returns garbage on the one request that mattered — and so far a single failure takes the whole run down. Part III — Graphs in Production is about making the graph robust and operable: catching and retrying errors so one bad call does not sink a run, serving the graph over HTTP so something other than a __main__ block can call it, adding observability so you can see what happened after the fact, reaching external tools over MCP, opening up the persistence internals we have leaned on since Chapter 8, and building the production RAG pipeline that finally replaces the stubbed search_docs with real retrieval. The graph can think, and can be held to it; next we make it hold up.

New pieces in this chapter

Piece Usage
Type
FakeMessagesListChatModel A chat model that replays a scripted list of messages. ScriptedModel(responses=[AIMessage(...), ...]); from langchain_core.language_models.fake_chat_models — subclass it to add bind_tools, which the base class does not implement
API
graph.nodes[name] One node of a compiled graph, runnable on its own. graph.nodes["tools"].invoke(state); returns the node’s delta and bypasses the checkpointer. Its invoke is (input, config, **kwargs), so it cannot take a Runtime context — and a context= keyword is swallowed by the **kwargs rather than rejected
Runtime(context=…) Build a runtime by hand so a node function can be called directly. model(state, Runtime(context=Context(llm=fake))); every field is keyword-with-default
update_state(…, as_node=…) Write a checkpoint as though a given node produced it. graph.update_state(config, {"messages": [ai]}, as_node="model"); the outgoing edges of that node run, so get_state().next shows the routing decision
invoke(None, …, context=…) Resume a parked thread, supplying its dependencies again. compiled.invoke(None, config, context=Context(llm=fake)); None continues from the checkpoint (Chapter 8), and context= is required even on a resume because it is per-run and never checkpointed
invoke(…, interrupt_after=[…]) Stop a run after named nodes, decided by the caller. graph.invoke(inp, config, interrupt_after=["model"]); static, per-call, and invisible to the shipped graph — unlike the dynamic interrupt() of Chapter 9
pytest.fixture A fresh object per test. @pytest.fixture def compiled(): return build_docbot().compile(checkpointer=InMemorySaver())
pytest.mark.parametrize One test body, one row per case, reported separately. @pytest.mark.parametrize("last, expected", [...])
pytest.raises Assert that a call fails, and how. with pytest.raises(ValueError, match="Missing required config key"):; also how you pin that a runaway loop really does hit GraphRecursionError

Code in this chapter

File What it runs
code/ch18_docbot.py The doc-bot packaged to be imported rather than run: build_docbot() hands back the builder, so each test compiles its own copy.
code/ch18_test_docbot.py Tests at four altitudes, none of them touching a model server, all of them finishing in milliseconds.

Challenge

🥉 Bronze — make a green suite go red

A test you have never seen fail is a test you have not written yet. Break the doc-bot in three ways, one at a time, and note which test catches each — and how fast you could locate the fault from the failure alone:

  1. Delete the tools → model back-edge.
  2. Change route to return "tools" whenever messages is non-empty.
  3. Make the tools node return {"tools_used": used} and drop the messages.

You’ve got it when each break turns at least one test red, and you can say which altitude caught it. One of the three turns five tests red at once, and that is worth a sentence to yourself about why: breadth is not an address. The router break reddens every altitude that runs the graph; the tools break reddens two, and one of them names the node. The level-1 tests are what turn a red suite into a place to look.

office hours Worked solution with tests: code/answers/ch18_break_the_suite.py.

🥈 Silver — test the failure paths

The suite only tests the doc-bot working. Add two tests for it not working:

  1. The model asks for a tool that does not exist ({"name": "delete_everything"}). What does tools do today? Decide what it should do, then write the test that pins your decision.
  2. search_docs finds nothing. Assert the run still terminates, and that the ToolMessage carries the “No matching local documents” text rather than an empty string.

The first one is the interesting half: an agent’s tool dispatch is reachable by anything the model can emit, and Chapter 21’s retries will not save you from a KeyError in your own dictionary lookup.

office hours Worked solution with tests: code/answers/ch18_failure_paths.py.

🥇 Gold — a test that survives a real model

Scripted models prove the wiring; they cannot prove the tools’ descriptions are good enough that a real model reaches for the right one. Write one test — marked so the default run skips it — that uses the real local model and asserts only this: "search_docs" in out["tools_used"] for a question the local docs plainly cover.

You’ve got it when pytest runs the fast suite by default and the slow one only on request. Hints: @pytest.mark.slow plus a markers entry, and -m slow to select it. Then sit with the uncomfortable part — that assertion can fail on a day when nothing in your repository changed. That is not a flaky test to be fixed; it is a measurement wearing a test’s clothes, and Chapter 32 is where it belongs.

office hours Worked solution with tests: code/answers/ch18_real_model_test.py.