可能的解决方法之一是使用相同版本的 pytest、httpx 和 Python 在本地环境和 GitHub Actions 中运行测试。此外,在 GitHub Actions 中,还需要设置正确的环境变量和依赖项,以确保测试能够正确运行。
如果仍然存在问题,可以利用 pytest 的 CLI 标志来分析问题,例如运行 pytest -v
或 pytest -x
来查看测试失败的详细信息。如果是由于依赖关系问题导致的测试失败,可以尝试安装依赖关系并重新运行测试。
以下是使用 HTTPX 进行测试的示例代码:
import httpx
async def test_get():
async with httpx.AsyncClient(app=app, base_url="http://localhost") as client:
response = await client.get("/get")
assert response.status_code == 200
assert response.json() == {"message": "Hello World"}
在 GitHub Actions 中,可以使用以下 YAML 文件来设置环境变量和依赖项:
name: CI
on: [push]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.7, 3.8, 3.9]
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
pytest
env:
ENVIRONMENT: test
BASE_URL: "http://localhost"
请注意,此 YAML 文件设置了 Python 版本、安装依赖项(从 requirements.txt 文件),并运行 pytest,同时设置了 ENVIRONMENT 和 BASE_URL 环境变量。以便在测试期间使用。