跳到主要内容
标准测试可确保您的集成按预期工作。 当您为自己创建自定义类或在 LangChain 集成中发布时,有必要添加测试以确保其按预期工作。LangChain 为您提供了针对每种集成类型的全面测试集。本指南将向您展示如何将 LangChain 的标准测试套件添加到每种集成类型中。

设置

首先,安装所需的依赖项
由于 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
# 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 参考 以下是一些流行集成中标准测试的示例实现:

运行测试

如果从模板引导集成,则提供了包含用于运行单元测试和集成测试的目标的 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 参考
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.