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_testsSandboxIntegrationTests。 继承它并提供一个 sandbox fixture,该 fixture 生成一个 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 参考