跳到主要内容
在您完成 LangGraph 代理原型设计后,下一步自然是添加测试。本指南介绍了一些在编写单元测试时可以使用的有用模式。 请注意,本指南是 LangGraph 特定的,涵盖了具有自定义结构的图的场景——如果您刚开始使用,请查看此部分,它使用了 LangChain 内置的create_agent

先决条件

首先,请确保已安装pytest
$ pip install -U pytest

入门

由于许多 LangGraph 代理依赖于状态,因此一种有用的模式是在每个测试中使用它们之前创建图,然后在测试中使用新的检查点实例对其进行编译。 下面的示例展示了如何使用一个简单的线性图来实现这一点,该图通过 node1node2 进行。每个节点都更新单个状态键 my_key
import pytest

from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver

def create_graph() -> StateGraph:
    class MyState(TypedDict):
        my_key: str

    graph = StateGraph(MyState)
    graph.add_node("node1", lambda state: {"my_key": "hello from node1"})
    graph.add_node("node2", lambda state: {"my_key": "hello from node2"})
    graph.add_edge(START, "node1")
    graph.add_edge("node1", "node2")
    graph.add_edge("node2", END)
    return graph

def test_basic_agent_execution() -> None:
    checkpointer = MemorySaver()
    graph = create_graph()
    compiled_graph = graph.compile(checkpointer=checkpointer)
    result = compiled_graph.invoke(
        {"my_key": "initial_value"},
        config={"configurable": {"thread_id": "1"}}
    )
    assert result["my_key"] == "hello from node2"

测试单个节点和边

已编译的 LangGraph 代理将每个单独的节点作为 graph.nodes 暴露。您可以利用这一点来测试代理中的单个节点。请注意,这将绕过编译图时传入的任何检查点。
import pytest

from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver

def create_graph() -> StateGraph:
    class MyState(TypedDict):
        my_key: str

    graph = StateGraph(MyState)
    graph.add_node("node1", lambda state: {"my_key": "hello from node1"})
    graph.add_node("node2", lambda state: {"my_key": "hello from node2"})
    graph.add_edge(START, "node1")
    graph.add_edge("node1", "node2")
    graph.add_edge("node2", END)
    return graph

def test_individual_node_execution() -> None:
    # Will be ignored in this example
    checkpointer = MemorySaver()
    graph = create_graph()
    compiled_graph = graph.compile(checkpointer=checkpointer)
    # Only invoke node 1
    result = compiled_graph.nodes["node1"].invoke(
        {"my_key": "initial_value"},
    )
    assert result["my_key"] == "hello from node1"

部分执行

对于由大型图组成的代理,您可能希望测试代理中的部分执行路径,而不是整个端到端流程。在某些情况下,将这些部分重构为子图可能在语义上更有意义,您可以像往常一样单独调用它们。 但是,如果您不想更改代理图的整体结构,您可以使用 LangGraph 的持久化机制来模拟一种状态,即您的代理在所需部分开始之前暂停,并在所需部分结束时再次暂停。步骤如下:
  1. 使用检查点编译您的代理(内存中的检查点InMemorySaver足以用于测试)。
  2. 调用代理的update_state方法,其中as_node参数设置为您要开始测试的节点之前的节点的名称。
  3. 使用用于更新状态的相同 thread_id 和设置为您要停止的节点名称的 interrupt_after 参数调用您的代理。
这是一个仅在线性图中执行第二个和第三个节点的示例。
import pytest

from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver

def create_graph() -> StateGraph:
    class MyState(TypedDict):
        my_key: str

    graph = StateGraph(MyState)
    graph.add_node("node1", lambda state: {"my_key": "hello from node1"})
    graph.add_node("node2", lambda state: {"my_key": "hello from node2"})
    graph.add_node("node3", lambda state: {"my_key": "hello from node3"})
    graph.add_node("node4", lambda state: {"my_key": "hello from node4"})
    graph.add_edge(START, "node1")
    graph.add_edge("node1", "node2")
    graph.add_edge("node2", "node3")
    graph.add_edge("node3", "node4")
    graph.add_edge("node4", END)
    return graph

def test_partial_execution_from_node2_to_node3() -> None:
    checkpointer = MemorySaver()
    graph = create_graph()
    compiled_graph = graph.compile(checkpointer=checkpointer)
    compiled_graph.update_state(
        config={
          "configurable": {
            "thread_id": "1"
          }
        },
        # The state passed into node 2 - simulating the state at
        # the end of node 1
        values={"my_key": "initial_value"},
        # Update saved state as if it came from node 1
        # Execution will resume at node 2
        as_node="node1",
    )
    result = compiled_graph.invoke(
        # Resume execution by passing None
        None,
        config={"configurable": {"thread_id": "1"}},
        # Stop after node 3 so that node 4 doesn't run
        interrupt_after="node3",
    )
    assert result["my_key"] == "hello from node3"

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.