为何GitHub Actions未执行tests文件夹中全部测试脚本?
问题:pytest结合GitHub Actions仅执行tests文件夹中第一个测试脚本
我使用pytest配合GitHub Actions,在推送至main分支前运行单元测试,但pytest仅执行tests文件夹中的第一个脚本,该文件夹下共有三个测试脚本。
项目文件夹结构
guerrilla_forecast/ ├─utils/ │ ├─__init__.py │ ├─datapull.py │ ├─google_bucket.py │ ├─monthly_data_aggregation.py │ ├─one_month_promotions.txt │ ├─.ipynb_checkpoints/ │ │ ├─monthly_data_aggregation-checkpoint.py │ │ ├─one_month_promotions-checkpoint.txt │ │ ├─google_bucket-checkpoint.py │ │ ├─datapull-checkpoint.py │ │ ├─key1-checkpoint.json │ │ └─prophet_daily-checkpoint.py │ └─prophet_daily.py ├─requirements.txt ├─.github/ │ └─workflows/ │ ├─overview.md │ └─python-app.yml ├─tests/ │ ├─forecast_test.py │ ├─__init__.py │ ├─daily_data_test.py │ ├─monthly_aggregation_test.py │ ├─.ipynb_checkpoints/ │ │ ├─daily_data_test-checkpoint.py │ │ ├─forecast_test-checkpoint.py │ │ ├─monthly_aggregation_test-checkpoint.py │ │ └─__init__-checkpoint.py │ └─.pytest_cache/ │ ├─v/ │ │ └─cache/ │ │ ├─stepwise │ │ ├─lastfailed │ │ └─nodeids │ ├─README.md │ ├─CACHEDIR.TAG │ └─.gitignore ├─README.md ├─ssh.txt ├─pic_files/ │ └─seg.png ├─Dockerfile └─.ipynb_checkpoints/ ├─ssh-checkpoint.txt ├─requirements-checkpoint.txt ├─README-checkpoint.md └─Untitled-checkpoint.ipynb
GitHub Actions工作流文件
name: Python application on: push: branches: [ "main" ] pull_request: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Python 3.10 uses: actions/setup-python@v3 with: python-version: "3.10" - name: Install dependencies run: | python -m pip install --upgrade pip pip install flake8 pytest if [ -f requirements.txt ]; then pip install -r requirements.txt; fi - name: Lint with flake8 run: | # stop the build if there are Python syntax errors or undefined names flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics - name: Test with pytest run: | pytest
解决方案
- 明确指定测试目录运行:修改GitHub Actions中pytest的执行命令,明确指向tests目录并开启详细输出,方便排查问题:
pytest tests/ -v - 检查测试函数命名:确保所有测试脚本内的测试函数都以
test_开头(比如def test_xxx()),这是pytest默认的测试发现规则,不符合命名规范的函数不会被执行。 - 排除干扰目录:在项目根目录创建
pytest.ini配置文件,添加规则忽略.ipynb_checkpoints目录,避免检查点文件干扰测试发现:[pytest] addopts = --ignore=tests/.ipynb_checkpoints/ - 排查致命错误:在本地执行
pytest tests/ -v,查看是否第一个测试脚本抛出了导致进程终止的未捕获异常,这类错误会直接终止pytest运行,导致后续脚本无法执行。
内容的提问来源于stack exchange,提问作者Jordan Howell
相关产品推荐
相关产品推荐

