使用pytest运行测试文件失败,提示ModuleNotFoundError: No module named 'src'
问题:终端执行pytest报ModuleNotFoundError,PyCharm内运行正常
项目结构
myapplication |-> src |->my_app |->utils |-> Utils.py |-> config |-> data |-> tests |-> test_my_app |-> test_utils |->test_Utils.py
测试文件代码(test_Utils.py)
import pytest from datetime import datetime from src.my_app.utils.Utils import Utils # Define test cases def test_roundOff(): assert Utils.roundOff(12.345) == 12.35 assert Utils.roundOff(10.0) == 10.0 assert Utils.roundOff(9.999) == 10.0 def test_getMarketStartTime(): now = datetime(2023, 10, 11, 9, 0, 0) market_start = Utils.getMarketStartTime(now) assert market_start == datetime(2023, 10, 11, 9, 15, 0) def test_getMarketEndTime(): now = datetime(2023, 10, 11, 16, 0, 0) market_end = Utils.getMarketEndTime(now) assert market_end == datetime(2023, 10, 11, 15, 30, 0) # You can add more test functions for other methods in the Utils class # Run the tests with pytest if __name__ == "__main__": pytest.main()
终端执行pytest的错误信息
(venv) PS C:\Users\mylaptop\PycharmProjects\myapplication> pytest ================================================================================= test session starts ================================================================================= platform win32 -- Python 3.10.9, pytest-7.4.2, pluggy-1.3.0 rootdir: C:\Users\mylaptop\PycharmProjects\myapplication collected 0 items / 1 error ======================================================================================= ERRORS ======================================================================================== ___________________________________________________________ ERROR collecting tests/test_my_app/test_utils/test_Utils.py ___________________________________________________________ ImportError while importing test module 'C:\Users\mylaptop\PycharmProjects\myapplication\tests\test_my_app\test_utils\test_Utils.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: C:\Python310\lib\importlib\__init__.py:126: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests\test_my_app\test_utils\test_Utils.py:3: in <module> from src.my_app.utils.Utils import Utils E ModuleNotFoundError: No module named 'src' =============================================================================== short test summary info =============================================================================== ERROR tests/test_my_app/test_utils/test_Utils.py !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ================================================================================== 1 error in 0.60s ===================================================================================
已尝试但无效的方法
- 删除pytest_cache文件夹后重试
- PyCharm内运行测试正常,但终端执行报错
- PyCharm设置中已将默认测试框架选为pytest
- 尝试多种pytest命令:
pytest、pytest -v tests/test_my_app/test_utils/test_Utils.py等 - 在src、my_app、utils目录下添加空的
__init__.py文件 - 将src目录路径添加到系统环境变量并重启机器
- 在PyCharm中将src标记为源文件夹并移除导入语句中的
src.前缀
环境:Python 3.10、pytest,PyCharm IDE
解决方案
方法1:临时将项目根目录加入Python路径(终端执行)
在终端运行pytest前,先执行以下命令(Windows PowerShell):
$env:PYTHONPATH = "$(Get-Location);$env:PYTHONPATH"
再执行pytest即可。
方法2:使用pytest的--import-mode=append参数
直接执行命令:
pytest --import-mode=append
该参数会将测试文件所在目录的父目录加入Python路径,让解释器识别src模块。
方法3:在测试文件中手动添加路径
在test_Utils.py的开头添加以下代码:
import sys from pathlib import Path # 获取项目根目录路径 project_root = Path(__file__).parent.parent.parent.parent sys.path.append(str(project_root))
无论从哪个路径执行测试,都能确保项目根目录被加入Python路径。
方法4:安装项目为可编辑模式(推荐)
在项目根目录(myapplication文件夹下)执行:
pip install -e .
将项目以可编辑模式安装到虚拟环境后,Python可直接识别src.my_app的包结构,无需手动设置路径。
内容的提问来源于stack exchange,提问作者Simbu
相关产品推荐
相关产品推荐

