标准测试确保你的集成按预期工作。 当你为自己创建自定义类,或要发布 LangChain 集成时,需要添加测试以确保它按预期工作。LangChain 为每种集成类型提供了一套完整的测试。本指南会展示如何为每种集成类型添加 LangChain 标准测试套件。

设置

首先,安装所需依赖:

langchain-core

定义用于导入并定义自定义组件的接口

langchain-tests

提供标准测试和运行它们所需的 pytest plugins
由于新版 langchain-tests 中新增的测试可能破坏你的 CI/CD pipelines,建议固定到 langchain-tests 的最新版本,以避免意外变更。
pip install -U langchain-core
pip install -U langchain-tests
langchain-tests 包中有 2 个 namespace:
位置langchain_tests.unit_tests用于在隔离环境中测试组件,不访问外部服务查看 API reference
位置langchain_tests.integration_tests用于在可以访问外部服务的情况下测试组件,尤其是组件设计要交互的外部服务查看 API reference
这两类测试都实现为基于 pytest class 的测试套件。

实现标准测试

根据集成类型,你需要实现单元测试、集成测试,或两者都实现。 通过继承适用于你的集成类型的标准测试套件,你可以获得该类型的完整标准测试集合。要让测试运行成功,指定测试只有在模型支持被测试能力时才应通过。否则,该测试应被跳过。 由于不同集成提供不同功能集合,LangChain 提供的大多数标准测试默认都是显式启用,以防止误报。因此,你需要覆盖属性来说明你的集成支持哪些功能。下方示例展示了这一点。
tests/integration_tests/test_standard.py
# 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)
你应在包根目录的以下子目录中组织测试:
  • tests/unit_tests 用于单元测试
  • tests/integration_tests 用于集成测试
要查看可配置能力及其默认值的完整列表,请访问标准测试的 API reference 下面是一些热门集成中的标准测试实现示例:

ChatOpenAI

单元测试

ChatAnthropic

单元测试

ChatGenAI

单元测试

Sandbox 集成

Deep Agents sandbox 集成使用 langchain_tests.integration_tests 中的 SandboxIntegrationTests。 继承它,并提供一个 sandbox fixture,yield 一个 SandboxBackendProtocol 实例。 使用 Daytona integration tests 作为参考实现。 发布指南请参阅贡献 sandbox 集成

运行测试

如果从模板引导集成,会提供一个 Makefile,其中包含运行单元测试和集成测试的 targets:
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

故障排除

如需查看可用标准测试套件的完整列表,以及包含哪些测试和如何排查常见问题的信息,请参阅 Standard Tests API Reference