Use this file to discover all available pages before exploring further.
集成测试验证你的智能体是否能与模型 API 和外部服务正确协作。与使用虚拟对象和模拟的单元测试不同,集成测试会进行实际的网络调用,以确认组件能够协同工作、凭据有效且延迟可接受。由于大语言模型(LLM)的响应是非确定性的,集成测试需要与传统软件测试不同的策略。本指南介绍如何组织、编写和运行智能体的集成测试。关于为 LangChain 本身贡献代码时的通用测试基础设施,请参阅贡献代码。
集成测试需要真实的 API 凭据。从环境变量加载它们,这样密钥就不会进入源代码管理。使用 conftest.py fixture 验证所需的密钥是否可用:
import osimport pytest@pytest.fixture(autouse=True)def check_api_keys(): if not os.environ.get("OPENAI_API_KEY"): pytest.skip("OPENAI_API_KEY not set")
def test_agent_calls_weather_tool(): agent = create_agent("claude-sonnet-4-6", tools=[get_weather]) result = agent.invoke({ "messages": [HumanMessage(content="What's the weather in SF?")] }) messages = result["messages"] tool_calls = [ tc for msg in messages if hasattr(msg, "tool_calls") for tc in (msg.tool_calls or []) ] assert any(tc["name"] == "get_weather" for tc in tool_calls) assert isinstance(messages[-1], AIMessage) assert len(messages[-1].content) > 0
@pytest.mark.vcr()def test_agent_trajectory(): agent = create_agent("claude-sonnet-4-6", tools=[get_weather]) result = agent.invoke({ "messages": [HumanMessage(content="What's the weather in SF?")] }) assert any( tc["name"] == "get_weather" for msg in result["messages"] if hasattr(msg, "tool_calls") for tc in (msg.tool_calls or []) )