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

如何在pytest.ini文件中正确使用GitLab CI/CD变量?

在GitLab CI/CD中让pytest正确读取CI变量的解决方案

为什么直接在pytest.ini里写${CI_COMMIT_REF_SLUG}没用

pytest.ini是静态配置文件,它本身不会自动解析系统环境变量或CI流水线变量,所以你写的变量占位符会原封不动被读取,不会替换成实际值。

可行的解决方案

方案1:在CI流水线中动态生成pytest.ini

先准备一个模板文件(比如命名为pytest.ini.template),内容保留你的变量占位符:

[pytest]
 env =
     branch_name = feature-${CI_COMMIT_REF_SLUG}

然后在.gitlab-ci.yml的测试阶段,用envsubst工具替换模板里的变量,生成实际的pytest.ini后再运行测试:

test:
  stage: test
  script:
    # 替换模板中的CI变量生成pytest.ini
    envsubst < pytest.ini.template > pytest.ini
    # 执行pytest测试
    pytest

注意:大部分Linux镜像默认自带envsubst,如果你的镜像没有,需要先安装gettext包(比如apt-get install gettext或yum install gettext)

方案2:直接在CI流水线中设置环境变量,跳过pytest.ini定义

不需要修改pytest.ini,直接在.gitlab-ci.yml的测试任务里设置环境变量,pytest会自动读取系统环境变量:

test:
  stage: test
  variables:
    branch_name: "feature-${CI_COMMIT_REF_SLUG}"
  script:
    pytest

之后在测试代码里,直接通过os.environ.get("branch_name")获取这个变量值即可。

方案3:用pytest命令行参数传递变量

如果使用pytest-env插件(需要先安装:pip install pytest-env),可以直接在CI脚本中通过命令行传递环境变量,不需要修改pytest.ini:

test:
  stage: test
  script:
    pytest --env "branch_name=feature-${CI_COMMIT_REF_SLUG}"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 01:09:54