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

Python测试导入路径异常:如何让测试正确导入src/resources的foo?

导入错误问题分析与解决方案

项目结构

app/
  src
    resources
      __init__.py (包含foo方法)
  tests
    resources
      __init__.py
    sometest.py

问题现象

  1. 运行sometest.py时,src/core/some_module.py中使用from resources import foo会触发错误:
    ImportError: cannot import name 'foo' from 'resources' (app/tests/resources/__init__.py)
    
  2. 将导入语句改为from src.resources import foo后,PyCharm UI中运行正常,但执行poetry run pytest -ra --cov=src --cov-fail-under=80 --cov-config=.coveragerc时报错:
    ModuleNotFoundError: No module named 'src'
    

问题原因

  1. 第一个错误原因:Python执行测试时,当前工作目录(app/tests/)会被优先加入模块搜索路径。此时import resources会先匹配tests/resources目录,而该目录下的__init__.py没有foo方法,因此触发导入错误。
  2. 第二个错误原因:使用poetry run pytest时,工作目录为app/,但src目录未被添加到Python的模块搜索路径(sys.path)中,导致Python无法识别src作为模块。PyCharm能正常运行是因为它自动将项目相关目录加入了搜索路径。

解决方案

方案一:采用可安装包结构(推荐长期使用)

这是Python项目的标准结构,能彻底解决导入问题:

  • 调整项目结构,在src下创建与项目同名的包,将resources、core等子目录移入其中:
    app/
      src
        your_project
          resources
            __init__.py (包含foo方法)
          core
            some_module.py
      tests
        sometest.py
    
  • 在pyproject.toml中配置包路径(Poetry项目已有的话只需修改对应部分):
    [tool.poetry]
    name = "your_project"
    packages = [{ include = "your_project", from = "src" }]
    
  • 修改导入语句为from your_project.resources import foo
  • 执行poetry install将包以可编辑模式安装,此后无论PyCharm还是pytest都能正确识别模块。

方案二:临时添加搜索路径(快速临时解决)

在测试文件sometest.py的最顶部添加代码,手动将src目录加入搜索路径:

import sys
from pathlib import Path
# 将app/src目录加入sys.path
sys.path.append(str(Path(__file__).parent.parent / "src"))

此时导入语句使用from src.resources import foo即可正常运行测试。

方案三:配置pytest自动添加搜索路径

通过pytest配置文件让pytest自动将src加入搜索路径:

  • 在app目录下创建pytest.ini文件,添加内容:
    [pytest]
    pythonpath = src
    
    或者在已有的pyproject.toml中添加:
    [tool.pytest.ini_options]
    pythonpath = ["src"]
    
  • 导入语句保持from src.resources import foo,pytest和PyCharm都能正常识别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 23:45:02