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

Azure DevOps Pipeline中pytest无法获取环境变量的问题排查

解决Azure DevOps Windows代理下pytest无法读取环境变量的问题

问题场景:在Azure DevOps构建流水线的Windows代理上运行pytest单元测试时,脚本中通过echo %AUTOMATION_ENV%能正常打印环境变量,但pytest测试用例无法读取该变量导致测试失败;而在GitHub Actions的Ubuntu代理上用类似逻辑可正常运行。

可能的原因及解决方案

1. 确认Python读取环境变量的代码正确性

确保测试用例中使用Python标准库的os.environ读取变量,示例代码如下:

import os

def test_check_env_var():
    automation_env = os.environ.get("AUTOMATION_ENV")
    assert automation_env == "unittest"

避免使用依赖shell特定逻辑的非标准方式读取环境变量。

2. 调整Windows脚本的环境变量传递方式

Windows的cmd shell中,需确保环境变量能传递给pytest子进程,可尝试以下两种方式:

方式一:在脚本内显式绑定环境变量与pytest执行命令

修改YAML的script块,将环境变量设置与pytest执行用&&连接,确保变量在同一shell会话中生效:

- script: |
    pip install pytest pytest-cov
    set AUTOMATION_ENV=unittest && echo %AUTOMATION_ENV%
    set AUTOMATION_ENV=unittest && python -m pytest -v ./test/general/test_identity.py
    set AUTOMATION_ENV=unittest && python -m pytest -v ./test/general/test_initialization.py
  displayName: 'Unit test'
  enabled: true

方式二:改用PowerShell执行脚本

Azure DevOps的pwsh任务(PowerShell Core)对环境变量传递更可靠,修改YAML配置为:

- pwsh: |
    pip install pytest pytest-cov
    Write-Host $env:AUTOMATION_ENV
    python -m pytest -v ./test/general/test_identity.py
    python -m pytest -v ./test/general/test_initialization.py
  displayName: 'Unit test'
  enabled: true
  env:
    AUTOMATION_ENV: unittest

PowerShell中通过$env:VAR_NAME访问环境变量,子进程会自动继承当前会话的环境变量。

3. 排查环境变量是否传入pytest进程

可在测试用例中临时打印所有环境变量,验证目标变量是否存在:

import os

def test_debug_envs():
    print("当前所有环境变量:")
    for key, value in os.environ.items():
        print(f"{key}={value}")

运行测试后查看构建日志,确认AUTOMATION_ENV是否出现在输出中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:23:25