Python测试导入路径异常:如何让测试正确导入src/resources的foo?
导入错误问题分析与解决方案
项目结构
app/ src resources __init__.py (包含foo方法) tests resources __init__.py sometest.py
问题现象
- 运行
sometest.py时,src/core/some_module.py中使用from resources import foo会触发错误:ImportError: cannot import name 'foo' from 'resources' (app/tests/resources/__init__.py) - 将导入语句改为
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'
问题原因
- 第一个错误原因:Python执行测试时,当前工作目录(
app/tests/)会被优先加入模块搜索路径。此时import resources会先匹配tests/resources目录,而该目录下的__init__.py没有foo方法,因此触发导入错误。 - 第二个错误原因:使用
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 = srcpyproject.toml中添加:[tool.pytest.ini_options] pythonpath = ["src"] - 导入语句保持
from src.resources import foo,pytest和PyCharm都能正常识别。
内容的提问来源于stack exchange,提问作者felisimo
相关产品推荐
相关产品推荐

