Test the Graph Without a Live Model

A graph that calls a language model looks hard to test, because the model can phrase its answer differently every time. Most of a graph is ordinary code, though: the nodes, the routing functions, the tool loop and the state they build up. That code can be tested the way any Python code is tested, quickly and with the same result on every run, as long as each test checks what the code decides and gets a scripted stand-in where the live model would be.

What a test should check

Before writing a test, sort what happens in a run into two groups. The first group is decided by code you wrote: which nodes ran and in what order, which tool was called with which arguments, and which keys the final state holds. Given the same model replies, this code always does the same thing. The second group is decided by the model: the exact words of its answer. A live model may word the same answer differently on the next run, so a test that compares those words fails for reasons that have nothing to do with your code.

So a good test asserts on structure. The tests in the official LangChain documentation work this way: they count the AI messages that carry tool calls, check the name of the tool that was called, and look at the final answer only with a substring check such as "Tokyo" in answer. Whether an answer is well written is a different question, judged by evaluations over many runs, not by a unit test.

What a run produces, and who decides it
What the run producesDecided byAssert on it?
The nodes that ran, in orderEdges and routing functionsYes, exactly
The tool calls made: name, arguments, countThe tool node and the scripted repliesYes, exactly
The keys and values of the final stateThe updates your nodes returnYes, exactly
The wording of the final answerThe modelNo, at most a substring

True or false?

A test of a graph that uses a model should compare the final answer with the exact text it expects.

False. The exact text comes from the model and can change between runs. A test checks the path, the tool calls and the state keys, which your code controls, and at most looks for a word in the answer.

If the model replies are fixed, the order in which the nodes run is fully determined by the edges and routing functions.

True. Routing functions are plain code that read the state. Given the same replies, they choose the same branches every time, so the path is something a test can assert exactly.

Testing one node on its own

A node is a plain function: it receives the current state and returns a dictionary with only the keys it changes. That makes the smallest test of all possible. Build a state by hand that holds exactly the situation you want to test, call the function, and check the update it returns. Nothing else in the graph runs, so when such a test fails, the fault is in this one node.

Take a hand-written tool node. It reads the last message, runs every tool call in it, and returns one tool message per call. To test it, the hand-made state needs only one AI message with one prepared tool call:

A tool node and a test that calls it directly
from langchain.messages import AIMessage, ToolCall, ToolMessage

def get_weather(city: str) -> str:
    """Return the current weather for a city."""
    return f"Sunny in {city}"

TOOLS = {"get_weather": get_weather}

def run_tools(state):
    last = state["messages"][-1]
    results = []
    for call in last.tool_calls:
        output = TOOLS[call["name"]](**call["args"])
        results.append(ToolMessage(content=output, tool_call_id=call["id"]))
    return {"messages": results}

def test_run_tools_answers_each_call():
    call = ToolCall(name="get_weather", args={"city": "Tokyo"}, id="call_1")
    state = {"messages": [AIMessage(content="", tool_calls=[call])]}

    update = run_tools(state)

    assert list(update) == ["messages"]
    [reply] = update["messages"]
    assert reply.tool_call_id == "call_1"
    assert "Tokyo" in reply.content

The test checks three things the node is responsible for: it changes only the messages key, it answers the call with a tool message whose tool_call_id matches the call, and the tool really received the argument. It does not check the state after merging, because merging is the job of the reducer and the runtime, not of this node.

A node can also be reached through the compiled graph. A compiled graph keeps its nodes in graph.nodes, a dictionary by node name, and graph.nodes["tools"].invoke(state) runs that one node and returns its update. This route skips any checkpointer the graph was compiled with, so it needs no thread id and saves nothing.

True or false?

Calling a node through graph.nodes saves a checkpoint, just like a normal run of the graph.

False. Invoking a single node through graph.nodes bypasses the checkpointer passed at compile time. It returns the update and nothing is saved.

A node test only needs the state keys that the node actually reads.

True. The node is a function of the state it is given. A hand-made state with just the keys it reads is enough, which keeps the test short and its purpose clear.

Testing a routing function, one state per branch

A conditional edge picks the next node at run time by calling a routing function: it reads the state and returns the name of the next node, or the end of the graph. The routing function is where the graph makes its decisions, so it deserves a test for every value it can return. If a branch has no test, nothing tells you when a change sends runs down the wrong path.

The routing function of a tool loop has two branches: when the last message asks for a tool, go to the tool node; when it does not, stop. That means two hand-made states, one per branch:

  • model
  • tools
  • END
  • model to tools: state 1: last message has a tool call
  • model to END: state 2: last message is plain text
A routing function and one test per branch
from langchain.messages import AIMessage, ToolCall
from langgraph.graph import END

def route_after_model(state):
    last = state["messages"][-1]
    return "tools" if last.tool_calls else END

def test_goes_to_tools_when_the_model_asks_for_one():
    call = ToolCall(name="get_weather", args={"city": "Tokyo"}, id="call_1")
    state = {"messages": [AIMessage(content="", tool_calls=[call])]}
    assert route_after_model(state) == "tools"

def test_ends_when_the_model_answers():
    state = {"messages": [AIMessage(content="It is sunny in Tokyo.")]}
    assert route_after_model(state) == END

Each test is one line of setup and one assertion, and each runs almost instantly, because no model and no graph is involved. A routing function with more branches, for example one that reads a category a model chose, gets one state per category. If your function has a fallback, add one more state for the case that is easy to forget: a value that matches none of the expected ones.

True or false?

Testing a routing function requires compiling the graph that uses it.

False. A routing function is a plain function of the state. It is called directly with a hand-made state, and its return value is compared with the expected node name or END.

A scripted fake model for whole runs

Node tests and routing tests check the parts. A whole run checks that the parts are wired together correctly: the loop really goes from the model to the tools and back, and stops when it should. For that the graph has to call a model, and here a fake chat model takes the place of the live one. A fake chat model is an object with the same interface as a real chat model that returns replies you prepared, one per call, in a fixed order.

LangChain ships one, GenericFakeChatModel. It takes an iterator of replies, each an AIMessage or a string, and returns the next one each time it is invoked. An AIMessage comes back exactly as you wrote it, so a prepared reply can carry tool calls. It does not read the messages it is given and does not care which tools are bound: the script alone decides what the model says. Two details matter in practice:

  • A model node that offers tools calls bind_tools on its model, and this fake does not implement that method. The documented fix is a small subclass whose bind_tools returns the model itself.
  • It does not start over when its replies run out. Once the script is used up, the next call fails. A run that asks the model one more time than you expected therefore breaks the test instead of passing quietly. (FakeListChatModel, the other fake, does cycle through its replies, but it returns strings only, so it cannot script tool calls.)

For a fake to replace the live model, the graph must not create its model itself. A function that receives the model and returns the graph builder lets the program pass in the real model and a test pass in the fake:

A graph that takes its model as an argument
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langgraph.graph import StateGraph, MessagesState, START, END

class ScriptedModel(GenericFakeChatModel):
    def bind_tools(self, tools, **kwargs):
        return self

def build_graph(model):
    model_with_tools = model.bind_tools([get_weather])

    def call_model(state):
        return {"messages": [model_with_tools.invoke(state["messages"])]}

    builder = StateGraph(MessagesState)
    builder.add_node("model", call_model)
    builder.add_node("tools", run_tools)
    builder.add_edge(START, "model")
    builder.add_conditional_edges("model", route_after_model, ["tools", END])
    builder.add_edge("tools", "model")
    return builder

A scripted run of a question about the weather needs two replies: first a tool call, then a plain answer. The picture shows who talks to whom, in order. The fake model is called twice, and between the two calls the tool node does real work with the arguments the script provided.

A scripted run of the tool loop
  • Test
  • model node
  • fake model
  • tools node
  • Test to model node: question
  • model node to fake model: invoke
  • fake model to model node: reply 1: tool call
  • model node to tools node: route: tools
  • tools node to model node: tool message
  • model node to fake model: invoke
  • fake model to model node: reply 2: answer
  • model node to Test: route: END

To record the path, the test streams the run in updates mode, which yields one chunk per node that ran. With version="v2", every chunk is a small dict with the same shape in every mode: its type names the mode and its data holds the payload. In updates mode, data holds that node's update under the node's name, so adding its keys to a list builds the path step by step. After the run, the test reads the final state and checks the tool calls and the keys:

A whole run on the scripted model
from langchain.messages import AIMessage, HumanMessage, ToolCall, ToolMessage
from langgraph.checkpoint.memory import InMemorySaver

def test_weather_question_calls_the_tool_once():
    model = ScriptedModel(messages=iter([
        AIMessage(content="", tool_calls=[
            ToolCall(name="get_weather", args={"city": "Tokyo"}, id="call_1"),
        ]),
        AIMessage(content="It is sunny in Tokyo."),
    ]))
    graph = build_graph(model).compile(checkpointer=InMemorySaver())
    config = {"configurable": {"thread_id": "weather-1"}}

    path = []
    for chunk in graph.stream(
        {"messages": [HumanMessage("What is the weather in Tokyo?")]},
        config,
        stream_mode="updates",
        version="v2",
    ):
        path.extend(chunk["data"])

    assert path == ["model", "tools", "model"]

    messages = graph.get_state(config).values["messages"]
    calls = [m for m in messages if isinstance(m, AIMessage) and m.tool_calls]
    assert len(calls) == 1
    assert calls[0].tool_calls[0]["name"] == "get_weather"
    assert calls[0].tool_calls[0]["args"] == {"city": "Tokyo"}
    assert isinstance(messages[2], ToolMessage)
    assert "Tokyo" in messages[-1].text

Every assertion here is about something code decided. The path comes from the edges and the routing function. The tool message in third place comes from the tool node. Even the tool name and arguments, though they come from the script, are worth asserting: they prove that the tool call travelled through the state unchanged. The only check on the answer text is a substring, and with a fake model even that is fixed. The same test runs without a key, without a network and without cost, and gives the same result every time.

True or false?

If the tool returns an unexpected result, the fake model adjusts its next reply to it.

False. The fake model ignores its input and returns the next prepared reply. The script fixes what the model says; the test checks what your code does with it.

A scripted run that calls the model more times than the script has replies fails instead of passing.

True. GenericFakeChatModel takes the next reply from its iterator and does not start over, so an extra call raises an error. An unexpected extra loop turn shows up as a failing test.

GenericFakeChatModel can be passed to a model node that calls bind_tools without any change.

False. It does not implement bind_tools. A small subclass whose bind_tools returns the model itself makes it usable in a node that binds tools.

A fresh graph and checkpointer in every test

A checkpointer saves the state of a thread after every step, and a later run with the same thread id starts from that saved state. That is what keeps a conversation going between runs. In a test suite, the same behaviour causes trouble. InMemorySaver, the in-memory checkpointer meant for development and tests, keeps every thread for as long as the object exists. If two tests share one compiled graph and both use the thread id "1", the second test does not start from its own input alone: it starts from the messages the first test left behind. Its result then depends on which tests ran before it, and a test that passes alone fails in the full suite.

Shared between tests
  • test A
  • test B
  • one InMemorySaver thread "1" from test A
  • test A to one InMemorySaver: writes thread "1"
  • test B to one InMemorySaver: reads old messages
Built inside each test
  • test A
  • test B
  • saver A empty at start
  • saver B empty at start
  • test A to saver A
  • test B to saver B

The LangGraph testing guide recommends the remedy: create the graph in each test that uses it, and compile it there with a new checkpointer instance. A function that returns the uncompiled builder, like build_graph above, makes that a single line. Building a small graph takes very little time, so there is nothing to gain by sharing one.

The fake model needs the same care, for a different reason. Its iterator is used up as the run consumes replies, and a used-up iterator cannot be reused. In pytest, a test can receive what it needs from a fixture: a function marked @pytest.fixture whose return value is passed to every test that names it as a parameter. A fixture's scope says how often it is built. The default, function, builds a new one for every test, so each test gets a fresh model. A module or session scope would hand the same half-used script to the next test.

Fixtures that build everything fresh for each test
import pytest
from langgraph.checkpoint.memory import InMemorySaver

@pytest.fixture
def model():
    return ScriptedModel(messages=iter([
        AIMessage(content="It is sunny in Tokyo."),
    ]))

@pytest.fixture
def graph(model):
    return build_graph(model).compile(checkpointer=InMemorySaver())

def test_plain_answer_needs_no_tool(graph):
    config = {"configurable": {"thread_id": "1"}}
    result = graph.invoke({"messages": [HumanMessage("Hi")]}, config)
    assert len(result["messages"]) == 2
    assert not result["messages"][-1].tool_calls

You may see MemorySaver in examples, including the testing guide itself. It is the same class under its older name, kept for backward compatibility; InMemorySaver is the current one. With a fresh graph, a fresh checkpointer and a fresh script in every test, each test sees only what it set up, and the suite gives the same result in any order.

True or false?

Two tests that use the same thread id are independent as long as each one compiles its own graph with a new InMemorySaver.

True. Saved threads live inside the checkpointer object. A new InMemorySaver starts empty, so the same thread id in another test names a different, empty conversation.

Giving the fake model fixture session scope makes the tests faster and changes nothing else.

False. All tests would share one iterator of replies. The first test uses up part of the script, and later tests get the wrong replies or none at all.