标准测试确保您的集成按预期工作。
在为自己创建自定义类或发布LangChain集成时,添加测试以确保其按预期工作是必要的。LangChain提供了全面的 测试集 为每种集成类型提供测试。本指南将向您展示如何为每种集成类型添加LangChain的标准测试套件。
设置
首先,安装所需的依赖项:
langchain-core
定义我们想要导入的接口以定义自定义组件
langchain-tests
提供标准测试和 pytest 运行它们所需的插件
pip install -U langchain-core
pip install -U langchain-tests
uv add langchain-core
uv add langchain-tests
中有2个命名空间 langchain-tests package:
Unit tests
位置: langchain_tests.unit_tests
旨在隔离测试组件,且不访问外部服务
Integration tests
位置: langchain_tests.integration_tests
旨在测试组件访问外部服务的能力(特别是组件设计要交互的外部服务)
两种类型的测试都实现为 pytest 基于类的测试套件。
实现标准测试
根据您的集成类型,您需要实现单元测试、集成测试或两者都要实现。
通过为您的集成类型继承标准测试套件,您可以获得该类型的完整标准测试集合。对于测试运行成功,只有在模型支持被测试的能力时,给定测试才应该通过。否则,测试应该被跳过。
由于不同的集成提供独特的功能集,LangChain提供的大多数标准测试 **默认是可选加入的** 以防止误报。因此,您需要覆盖属性以指示您的集成支持哪些功能——请参阅下面的示例进行说明。
# Indicate that a chat model supports image inputs
class TestChatParrotLinkStandard(ChatModelIntegrationTests):
# ... other required properties
@property
def supports_image_inputs(self) -> bool:
return True # (The default is False)
要查看可配置功能的完整列表及其默认值,请访问 API参考 了解标准测试。
以下是一些流行集成中标准测试的示例实现:
Unit tests
ChatOpenAI
单元测试
ChatAnthropic
单元测试
ChatGenAI
单元测试
Integration tests
ChatOpenAI
集成测试
ChatAnthropic
集成测试
ChatGenAI
集成测试
Sandbox integration tests
确保您的集成通过标准测试套件。 请参阅 Daytona 集成 作为示例。
Daytona
Sandbox 集成测试
Sandbox 集成
Deep Agents sandbox 集成使用 SandboxIntegrationTests 从 langchain_tests.integration_tests. 将其子类化并提供 sandbox fixture 来生成 SandboxBackendProtocol instance. 使用 Daytona 集成测试 作为参考实现。 请参阅 贡献 sandbox 集成 了解发布指南。
运行测试
如果从模板引导集成, Makefile 提供了一个包含运行单元和集成测试目标的 Makefile:
make test
make integration_test
否则,如果您遵循推荐的目录结构,可以使用以下命令运行测试:
# Run all tests
uv run --group test pytest tests/unit_tests/
uv run --group test --group test_integration pytest -n auto tests/integration_tests/
# For certain unit tests, you may need to set certain flags and environment variables:
TIKTOKEN_CACHE_DIR=tiktoken_cache uv run --group test pytest --disable-socket --allow-unix-socket tests/unit_tests/
# Run a specific test file
uv run --group test pytest tests/integration_tests/test_chat_models.py
# Run a specific test function in a file
uv run --group test pytest tests/integration_tests/test_chat_models.py::test_chat_completions
# Run a specific test function within a class
uv run --group test pytest tests/integration_tests/test_chat_models.py::TestChatParrotLinkIntegration::test_chat_completions
故障排除
有关可用标准测试套件的完整列表,以及有关包含哪些测试以及如何排除常见问题的信息,请参阅 标准测试 API 参考.