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

Azure DevOps Pipeline执行pytest时导入Python测试模块报错

Azure DevOps Pipeline 执行pytest单元测试异常问题

问题现象

在Azure DevOps Pipeline中使用pytest运行Python单元测试时触发报错,报错信息见截图:
pytest运行报错截图

当前Pipeline中除「Run all unit tests」任务外,所有前置任务均执行成功。该报错仅在Azure DevOps Pipeline环境出现,本地环境运行测试无相同问题。

现有Pipeline配置

使用的Pipeline yml配置代码如下:

trigger:
- main
- test-unit-test-devops 

jobs:
  - job: Test
    pool:
      name: OnPrem   # 私有代理池
      demands:
      - Agent.OS -equals Linux

    steps: 
    - task: UsePythonVersion@0
      inputs:
        versionSpec: '3.9.5'
        addToPath: true
        architecture: 'x64'
    
    - task: Bash@3
      inputs:
        targetType: 'inline'
        script: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt
        workingDirectory: '$(Build.SourcesDirectory)'
      displayName: "Installing Dependencies"
        
    - task: Bash@3
      inputs:
        targetType: 'inline'
        script: pytest
        workingDirectory: '$(Build.SourcesDirectory)'
      displayName: "Run all unit tests"

项目目录结构

项目根目录的文件结构如下:

<project_root>/
 | - .venv/
 | - .vscode/
 | - add_pipeline_config/
 | | - __init__.py
 | | - function.json
 | | - example.py
 | - my_second_function/
 | | - __init__.py
 | | - function.json
 | - tests/
 | | - test_add_pipeline_config.py
 | - .funcignore
 | - host.json
 | - local.settings.json
 | - requirements.txt
 | - Dockerfile

已尝试的排查操作

已尝试以下修复方案,均未解决问题:

  • 在tests目录中添加/移除__init__.py文件
  • 更换测试启动命令,分别尝试执行:
    • pytest
    • python -m pytest
    • python -m pytest/pytest
  • 将PYTHONPATH环境变量设置为$(Build.SourcesDirectory)
  • 创建并激活Python虚拟环境后运行测试

已确认的环境信息

  • 已通过打印变量确认$(Build.SourcesDirectory)路径为/azp/_work/1/s,该路径下存在全部项目文件
  • 依赖安装步骤执行正常,requirements.txt中声明的依赖均已完成安装

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 18:27:33