You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GitLab作业执行poetry install后无法找到pytest等Python包

排查GitLab CI中Poetry安装后pytest找不到的问题

以下是针对你遇到的pytest: command not found错误的关键排查点:

1. 用poetry run调用pytest

Poetry会将依赖安装在独立虚拟环境中,直接执行pytest无法识别环境内的可执行文件。修改.gitlab-ci.yml的测试脚本,用poetry run包裹命令:

test:
  script:
    - poetry install
    - poetry run pytest  # 替换直接的pytest命令

CI的非交互式环境下,避免使用poetry shell,该命令无法正常工作。

2. 检查pyproject.toml的依赖声明

确认pytest已被正确添加到依赖中:

  • 若使用Poetry 1.2+的分组依赖,需放在dev分组下:
    [tool.poetry.group.dev.dependencies]
    pytest = "^7.0.0"
    
  • 老版本Poetry则放在dev-dependencies下:
    [tool.poetry.dev-dependencies]
    pytest = "^7.0.0"
    

同时确保poetry install未添加--without dev参数(否则开发依赖不会安装);若用分组依赖,需执行poetry install --with dev。

3. 配置Poetry在CI环境的虚拟环境行为

CI中Poetry默认将虚拟环境创建在系统目录,可能导致环境识别异常。在poetry install前添加配置,让虚拟环境生成在项目目录内:

test:
  script:
    - poetry config virtualenvs.in-project true
    - poetry install
    - poetry run pytest

另外要确认CI runner的Python版本与pyproject.toml中python约束一致,比如:

[tool.poetry.dependencies]
python = "^3.10"

需确保CI使用的Python版本符合该约束。

4. 清理CI缓存

若GitLab CI配置了缓存,旧的虚拟环境缓存可能导致依赖未正确更新:

  • 可在GitLab项目的CI/CD设置中手动清空缓存
  • 或在脚本中添加缓存清理命令:
    test:
      script:
        - poetry cache clear --all pypi -n
        - poetry install
        - poetry run pytest
    

5. 验证测试文件结构(后续补充排查)

如果解决命令问题后仍有测试执行异常,需确保测试文件符合pytest默认规则:

  • 测试文件命名为test_*.py或*_test.py
  • 测试函数/类以test_开头
  • 若测试文件在自定义目录,需在pyproject.toml中配置pytest路径:
    [tool.pytest.ini_options]
    testpaths = ["tests"]
    

内容的提问来源于stack exchange,提问作者KarimovAnton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 17:14:57