Skip to main content
标准测试确保你的集成按预期工作。 在创建自定义类供自己使用或用于发布到 LangChain 集成时,需要添加测试以确保其按预期工作。LangChain 为每种集成类型提供了全面的 标准测试集。本指南将向您展示如何为每种集成类型添加 LangChain 的标准测试套件。

设置

首先安装所需的依赖项:

langchain-core

定义我们想要导入以定义自定义组件的接口

langchain-tests

提供运行标准测试所需的 pytest 插件
由于新版本的 langchain-tests 中添加的测试可能会破坏您的 CI/CD 管道,我们建议锁定到最新版本的 langchain-tests 以避免意外更改。
pip install -U langchain-core
pip install -U langchain-tests
langchain-tests 包中有 2 个命名空间:
位置langchain_tests.unit_tests设计用于在不访问外部服务的情况下单独测试组件查看 API 参考
位置langchain_tests.integration_tests设计用于在访问外部服务(特别是组件设计要交互的外部服务)的情况下进行测试查看 API 参考
这两种类型的测试都实现为基于类的 pytest 测试套件。

实现标准测试

根据您的集成类型,您需要实现单元测试和/或集成测试中的一种或两种。 通过继承您集成类型的标准化测试套件,您可以获得该类型的所有标准测试。对于一次成功的测试运行,给定的测试仅在模型支持被测功能时才应通过,否则应跳过测试。 由于不同的集成提供了独特的功能集,大多数由 LangChain 提供的标准测试默认为 选择性参与 以防止误报。因此,您需要覆盖属性以指示您的集成支持哪些功能 - 见下例以了解示例说明。
tests/integration_tests/test_standard.py
# 指示聊天模型支持图像输入

class TestChatParrotLinkStandard(ChatModelIntegrationTests):
    # ... 其他必需的属性

    @property
    def supports_image_inputs(self) -> bool:
        return True  # (默认为 False)
应将这些子目录中的测试组织在您的包根目录下:
  • tests/unit_tests 用于单元测试
  • tests/integration_tests 用于集成测试
要查看可配置功能及其默认值的完整列表,请访问标准测试的 API 参考 以下是一些来自流行集成的标准测试示例实现:

ChatOpenAI

单元测试

ChatAnthropic

单元测试

ChatGenAI

单元测试

沙盒集成

Deep Agents 的沙盒集成使用 langchain_tests.integration_tests 中的 SandboxIntegrationTests。继承它并提供一个 sandbox 固定表达式,该固定表达式返回一个 SandboxBackendProtocol 实例。 请参见 Daytona 集成测试 作为参考实现。有关发布指南,请参阅 贡献沙盒集成

运行测试

如果从模板启动集成,提供了一个包含运行单元和集成测试目标的 Makefile
make test
make integration_test
否则,如果您遵循推荐的目录结构,可以使用以下命令运行测试:
# 运行所有测试
uv run --group test pytest tests/unit_tests/
uv run --group test --group test_integration pytest -n auto tests/integration_tests/

# 对某些单元测试,您可能需要设置某些标志和环境变量:
TIKTOKEN_CACHE_DIR=tiktoken_cache uv run --group test pytest --disable-socket --allow-unix-socket tests/unit_tests/

# 运行特定的测试文件
uv run --group test pytest tests/integration_tests/test_chat_models.py

# 运行文件中的特定测试函数
uv run --group test pytest tests/integration_tests/test_chat_models.py::test_chat_completions

# 运行类内的特定测试函数
uv run --group test pytest tests/integration_tests/test_chat_models.py::TestChatParrotLinkIntegration::test_chat_completions

故障排除

要查看可用的标准测试套件的完整列表,以及了解包含哪些测试和如何解决常见问题,请参阅 标准测试 API 参考