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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 04:32:36