Skip to main content

测试

我们所有的包都有单元测试和集成测试,我们更倾向于单元测试而不是集成测试。

单元测试在每个拉取请求时运行,因此它们应该快速且可靠。

集成测试每天运行一次,并且需要更多的设置,因此它们应保留用于确认与外部服务的接口点。

单元测试

单元测试涵盖不需要调用外部 API 的模块化逻辑。 如果您添加了新逻辑,请添加单元测试。

要安装单元测试的依赖项:

poetry install --with test

要运行单元测试:

make test

要在 Docker 中运行单元测试:

make docker_tests

要运行特定测试:

TEST_FILE=tests/unit_tests/test_imports.py make test

集成测试

集成测试涵盖需要调用外部 API 的逻辑(通常是与其他服务的集成)。如果您添加了对新的外部 API 的支持,请添加一个新的集成测试。

警告:几乎没有测试应该是集成测试。

需要进行网络连接的测试使其他开发人员测试代码变得困难。

相反,建议依赖 responses 库和/或 mock.patch 使用小的固定数据来模拟请求。

要安装集成测试的依赖项:

poetry install --with test,test_integration

要运行集成测试:

make integration_tests

准备

集成测试使用多个搜索引擎和数据库。这些测试旨在验证引擎和数据库是否按照其规范和要求正确运行。

要运行某些集成测试,例如位于 tests/integration_tests/vectorstores/ 的测试,您需要安装以下软件:

  • Docker
  • Python 3.8.1 或更高版本

任何新的依赖项应通过运行以下命令添加:

# add package and install it after adding:
poetry add tiktoken@latest --group "test_integration" && poetry install --with test_integration

在运行任何测试之前,您应启动一个特定的 Docker 容器,该容器已安装所有必要的依赖项。例如,我们使用 elasticsearch.yml 容器来运行 test_elasticsearch.py

cd tests/integration_tests/vectorstores/docker-compose
docker-compose -f elasticsearch.yml up

对于需要更复杂准备的环境,请查找 *.sh。例如,opensearch.sh 构建所需的 Docker 镜像,然后启动 opensearch。

为本地测试准备环境变量:

  • tests/integration_tests/.env.example 复制到 tests/integration_tests/.env
  • tests/integration_tests/.env 文件中设置变量,例如 OPENAI_API_KEY

此外,重要的是要注意某些集成测试可能需要设置特定的环境变量,例如 OPENAI_API_KEY。在运行测试之前,请确保设置所有必需的环境变量,以确保它们正确运行。

使用pytest-vcr录制HTTP交互

本仓库中的一些集成测试涉及向外部服务发出HTTP请求。为了防止每次运行测试时都发出这些请求,我们使用pytest-vcr来录制和重放HTTP交互。

在CI/CD管道中运行测试时,您可能不想修改现有的录音带。您可以使用--vcr-record=none命令行选项来禁用录制新录音带。以下是一个示例:

pytest --log-cli-level=10 tests/integration_tests/vectorstores/test_pinecone.py --vcr-record=none
pytest tests/integration_tests/vectorstores/test_elasticsearch.py --vcr-record=none

运行一些覆盖率测试:

pytest tests/integration_tests/vectorstores/test_elasticsearch.py --cov=langchain --cov-report=html
start "" htmlcov/index.html || open htmlcov/index.html

覆盖率

代码覆盖率(即被单元测试覆盖的代码量)有助于识别代码中可能更脆弱或更强健的区域。

覆盖率需要集成测试的依赖项:

poetry install --with test_integration

要获取当前覆盖率报告,请运行以下命令:

make coverage

此页面是否有帮助?


您还可以留下详细的反馈 在 GitHub 上