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

Azure DevOps中执行pytest遇ModuleNotFoundError: No module named 'core'

问题原因

本地执行python -m pytest时,你是在项目根目录运行的,此时Python会自动将当前目录加入sys.path,所以能找到core模块。但Azure DevOps的测试步骤设置了workingDirectory: 'tests',在这个目录下执行pytest时,项目根目录不在Python的搜索路径里,导致无法识别core模块。

解决办法

提供三种可行方案,任选其一即可:

方案1:在项目根目录执行pytest

修改流水线的测试步骤,移除workingDirectory: 'tests',并在pytest命令中指定测试目录:

- script: |
    python -m pytest tests/ --junitxml=$(Build.StagingDirectory)/Testoutput.xml
  displayName: 'Test with PyTest'

这样执行时,项目根目录作为当前目录被加入sys.path,core模块就能被正常导入。

方案2:设置PYTHONPATH环境变量

在测试步骤中,将项目根目录($(Build.SourcesDirectory)是Azure DevOps中项目代码的根目录路径)添加到PYTHONPATH:

- script: |
    export PYTHONPATH=$(Build.SourcesDirectory)
    python -m pytest --junitxml=$(Build.StagingDirectory)/Testoutput.xml
  workingDirectory: 'tests'
  displayName: 'Test with PyTest'

PYTHONPATH会告诉Python去哪里查找模块,添加根目录后,即使在tests目录下执行,也能找到core。

方案3:将core安装为可编辑模块

在安装依赖后,添加一步将core所在的项目根目录以可编辑模式安装,这样core会被注册到Python的模块搜索路径中:

- script: |
    python -m pip install --upgrade pip
    pip install -r requirements.txt
    pip install -e .
  displayName: 'Install dependencies and editable core module'

之后执行测试步骤无需修改路径,无论在哪都能导入core模块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:35:21