测试
我们所有的软件包都有单元测试和集成测试,并且我们更倾向于单元测试而不是集成测试。
单元测试在每次拉取请求时运行,因此它们应该快速且可靠。
集成测试每天运行一次,并且需要更多设置,因此应保留用于确认与外部服务的接口点。
单元测试
单元测试涵盖不需要调用外部 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 来使用小型 fixture 模拟请求。
安装集成测试的依赖项
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 管道中运行测试时,您可能不希望修改现有的 cassettes。您可以使用 --vcr-record=none 命令行选项来禁用记录新的 cassettes。这是一个例子
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