PyCharm运行pytest配置问题求助:卡顿及ModuleNotFoundError
解决PyCharm中pytest配置问题
问题概述
- Windows 11下曾遇pytest卡顿,已通过管理员身份运行一次解决,但当前点击PyCharm测试函数旁的绿色运行图标,测试卡在收集阶段:
============================= test session starts =============================
collecting ... - 终端执行
python -m pytest ./tests时,出现错误:ModuleNotFoundError: No module named 'myproject' - 项目文件夹结构:
myproject/ docs/ examples/ src/ myproject/ functionsA.py functionsB.py tests/ test_functionsA.py
解决步骤
1. 修复ModuleNotFoundError问题
你的项目采用标准src布局,需将src目录加入Python路径,可任选一种方法:
方法一:添加pytest.ini配置文件
在项目根目录(myproject/)创建pytest.ini文件,内容如下:
[pytest] pythonpath = src
配置完成后,终端执行python -m pytest ./tests即可正常找到myproject模块。
方法二:安装项目为可编辑模式
在项目根目录执行以下命令,将项目安装到Python环境中(可编辑模式,修改代码无需重新安装):
pip install -e .
方法三:在测试文件中临时添加路径(临时方案)
在test_functionsA.py开头添加代码,手动将src目录加入路径:
import sys from pathlib import Path sys.path.append(str(Path(__file__).parent.parent / "src"))
2. 解决PyCharm绿色图标运行测试卡顿问题
步骤1:配置PyCharm测试环境
- 打开
File > Settings > Project: myproject > Python Interpreter,确认选中的解释器已安装pytest。 - 进入
File > Settings > Tools > Python Integrated Tools,将默认测试框架设置为pytest。
步骤2:修正测试运行的工作目录
- 点击运行按钮旁的配置下拉菜单,选择
Edit Configurations... - 在打开的窗口中找到对应pytest配置,将
Working directory设置为项目根目录(myproject/)。
步骤3:清理PyCharm缓存
执行File > Invalidate Caches...,选择Invalidate and Restart,重启后再尝试运行测试。
3. 验证
- 终端执行
python -m pytest ./tests,确认测试正常运行。 - 点击PyCharm测试函数旁的绿色图标,确认测试能正常收集并执行。
内容的提问来源于stack exchange,提问作者Delosari
相关产品推荐
相关产品推荐

