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 参考