测试
测试是开发过程中至关重要的环节,它能确保你的代码按预期工作并达到期望的质量标准。
在 LangChain 生态系统中,我们主要有两种测试类型:单元测试和集成测试。
对于实现了 LangChain 标准抽象的集成,我们提供了一套标准测试(包括单元测试和集成测试),这有助于在不同组件之间保持兼容性,并确保高使用率组件的可靠性。
单元测试
定义:单元测试旨在验证代码中最小的单元——单个函数或方法——并确保它们在隔离环境中按预期工作。它们不依赖于外部系统或集成。
示例:测试 convert_langchain_aimessage_to_dict 函数,以确认它能正确地将 AI 消息转换为字典格式:
from langchain_core.messages import AIMessage, ToolCall, convert_to_openai_messages
def test_convert_to_openai_messages():
ai_message = AIMessage(
content="Let me call that tool for you!",
tool_calls=[
ToolCall(name='parrot_multiply_tool', id='1', args={'a': 2, 'b': 3}),
]
)
result = convert_to_openai_messages(ai_message)
expected = {
"role": "assistant",
"tool_calls": [
{
"type": "function",
"id": "1",
"function": {
"name": "parrot_multiply_tool",
"arguments": '{"a": 2, "b": 3}',
},
}
],
"content": "Let me call that tool for you!",
}
assert result == expected # 确保转换结果与预期一致
集成测试
定义:集成测试用于验证多个组 件或系统是否能协同工作并达到预期。对于依赖外部服务的工具或集成,这些测试通常用于确保端到端的功能。
示例:测试 ParrotMultiplyTool,该工具可访问一个将两个数字相乘并加上 80 的 API 服务:
def test_integration_with_service():
tool = ParrotMultiplyTool()
result = tool.invoke({"a": 2, "b": 3})
assert result == 86
标准测试
定义:标准测试是由 LangChain 提供的一组预定义测试,用于确保所有工具和集成的稳定性和可靠性。它们包括 为 LangChain 组件量身定制的单元测试和集成测试模板。
示例:继承 LangChain 的 ToolsUnitTests 或 ToolsIntegrationTests 以自动运行标准测试:
from langchain_tests.unit_tests import ToolsUnitTests
class TestParrotMultiplyToolUnit(ToolsUnitTests):
@property
def tool_constructor(self):
return ParrotMultiplyTool
def tool_invoke_params_example(self):
return {"a": 2, "b": 3}
API Reference:ToolsUnitTests
要了解更多信息,请查阅我们关于如何为集成添加标准测试的指南。