跳至主要内容

测试

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

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

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

单元测试

单元测试涵盖不需要调用外部 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 上.