> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 测试

在为你的 LangGraph 代理完成原型设计后，自然的下一步是添加测试。本指南涵盖了一些在编写单元测试时可以使用的有用模式。

请注意，本指南是针对 LangGraph 的，涵盖了具有自定义结构的图相关场景——如果你是初学者，请查看使用 LangChain 内置的 [`create_agent`](https://reference.langchain.com/python/langchain/agents/factory/create_agent) 的 [测试](/oss/python/langchain/test/) 文档。

## 前提条件

首先，确保你已安装 [`pytest`](https://docs.pytest.org/)：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
$ pip install -U pytest
```

## 入门

由于许多 LangGraph 代理依赖于状态，一个有用的模式是在每次使用图的测试之前创建你的图，然后在测试中使用新的检查点实例对其进行编译。

下面的示例展示了一个简单的线性图如何工作，该图依次经过 `node1` 和 `node2`。每个节点更新单个状态键 `my_key`：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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` 暴露对每个单独节点的引用。你可以利用这一点来测试代理中的单个节点。请注意，这将绕过编译图时传递的任何检查点：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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:
    # 在此示例中将被忽略
    checkpointer = MemorySaver()
    graph = create_graph()
    compiled_graph = graph.compile(checkpointer=checkpointer)
    # 仅调用节点 1
    result = compiled_graph.nodes["node1"].invoke(
        {"my_key": "initial_value"},
    )
    assert result["my_key"] == "hello from node1"
```

## 部分执行

对于由更大图组成的代理，你可能希望测试代理内的部分执行路径，而不是端到端的整个流程。在某些情况下，将[这些部分重构为子图](/oss/python/langgraph/use-subgraphs)在语义上可能是合理的，你可以像正常情况一样单独调用它们。

但是，如果你不希望更改代理图的整体结构，可以使用 LangGraph 的持久化机制来模拟代理在所需部分开始之前暂停的状态，并在所需部分结束时再次暂停。步骤如下：

1. 使用检查点编译你的代理（内存中的检查点 [`InMemorySaver`](https://reference.langchain.com/python/langgraph/checkpoints/#langgraph.checkpoint.memory.InMemorySaver) 对于测试来说就足够了）。
2. 使用 [`as_node`](/oss/python/langgraph/use-time-travel#from-a-specific-node) 参数调用你的代理的 [`update_state`](/oss/python/langgraph/use-time-travel) 方法，该参数设置为*你想要开始测试的节点之前*的节点名称。
3. 使用你用于更新状态的相同 `thread_id` 调用你的代理，并将 `interrupt_after` 参数设置为你想要停止的节点名称。

以下是一个仅在线性图中执行第二个和第三个节点的示例：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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"
          }
        },
        # 传递给节点 2 的状态 - 模拟节点 1 结束时的状态
        values={"my_key": "initial_value"},
        # 更新保存的状态，就好像它来自节点 1
        # 执行将从节点 2 恢复
        as_node="node1",
    )
    result = compiled_graph.invoke(
        # 通过传递 None 恢复执行
        None,
        config={"configurable": {"thread_id": "1"}},
        # 在节点 3 之后停止，这样节点 4 就不会运行
        interrupt_after="node3",
    )
    assert result["my_key"] == "hello from node3"
```

***

<div className="source-links">
  <Callout icon="terminal-2">
    [连接这些文档](/use-these-docs) 到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/langgraph/test.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
