主题
使用标准测试
标准测试确保你的集成按预期工作。
无论是为自己创建自定义类,还是为发布 LangChain 集成而创建类,都有必要添加测试以确保其按预期工作。LangChain 为每种集成类型提供了一套全面的测试。本指南将向你展示如何为每种集成类型添加 LangChain 的标准测试套件。
设置
首先,安装所需的依赖项:
WARNING
由于新版本 langchain-tests 中新增的测试可能会破坏你的 CI/CD 流水线,我们建议固定到最新版本的 langchain-tests,以避免意外的变更。
bash
pip install -U langchain-core
pip install -U langchain-testsbash
uv add langchain-core
uv add langchain-testslangchain-tests 包中有 2 个命名空间:
这两类测试都实现为基于类的 pytest 测试套件。
实现标准测试
根据你的集成类型,你需要实现单元测试和/或集成测试。
通过继承适用于你的集成类型的标准测试套件,你就能获得该类型的全套标准测试。要使一次测试运行成功,给定测试应仅在被测模型支持其所测能力时才通过。否则,该测试应被跳过。
由于不同的集成提供各自独特的功能集,LangChain 提供的大多数标准测试默认是选择性启用的(opt-in),以防止误报。因此,你需要重写属性来指明你的集成支持哪些功能——参见下面的示例以作说明。
python
# 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)NOTE
你应当将测试组织在相对于包根目录的以下子目录中:
tests/unit_tests用于单元测试tests/integration_tests用于集成测试
要查看可配置能力及其默认值的完整列表,请访问标准测试的 API 参考。
以下是一些来自流行集成的标准测试示例实现:
沙箱集成
Deep Agents 沙箱集成使用来自 langchain_tests.integration_tests 的 SandboxIntegrationTests。 继承它并提供一个 sandbox 夹具(fixture),该夹具产出 SandboxBackendProtocol 实例。 使用 Daytona 集成测试作为参考实现。 发布指南请参阅贡献沙箱集成。
运行测试
如果从模板引导一个集成,会提供一个 Makefile,其中包含用于运行单元测试和集成测试的目标:
bash
make test
make integration_test否则,如果你遵循推荐的目录结构,可以使用以下命令运行测试:
bash
# 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 参考。