測試
我們所有的套件都有單元測試和整合測試,並且我們偏好單元測試勝於整合測試。
單元測試在每次 pull request 時都會執行,因此它們應該快速且可靠。
整合測試每天執行一次,並且需要更多設定,因此它們應該保留用於確認與外部服務的介面點。
單元測試
單元測試涵蓋不需要調用外部 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 管道中執行測試時,您可能不希望修改現有的 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