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

Python+pytest测试遇「no module named common」错误,求解决

pytest导入报错:no module named 'common' 解决方法

问题根源

你的test_my_script.py中使用了from common.util import func1,func2的导入语句,但common是my_module下的子包,并非Python能直接识别的顶级模块,所以pytest无法找到它。另外注意这里存在笔误:你的实际文件是utils.py,导入语句里写的是util,需要同步修正文件名或导入语句。

解决步骤

  • 修正导入路径
    推荐使用基于项目包的绝对导入(更稳定,适配多数运行场景):

    from my_module.common.utils import func1, func2
    

    若想用相对导入,需确保测试文件的层级关系正确(不推荐用于跨目录的测试导入):

    from ..my_module.common.utils import func1, func2
    
  • 以开发模式安装项目包
    利用你已有的setup.py/setup.cfg/pyproject.toml,在项目根目录执行以下命令,将包安装为可编辑模式,让Python能识别my_module作为顶级包:

    pip install -e .
    
  • 确保在正确目录运行pytest
    必须在项目根目录(即包含my_module和test文件夹的目录)执行pytest命令,不要进入test子目录再运行。

  • 适配tox配置(若使用)
    在tox.ini的[testenv]段添加依赖配置,确保tox运行时先安装你的项目包:

    [testenv]
    deps =
        -e .
        pytest
    commands = pytest
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 01:01:21