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

VS Code中用pytest时,Python项目移入子目录后测试失败如何修复?

修复VS Code中pytest因工作目录导致的ModuleNotFoundError问题

当VS Code以项目根目录作为工作目录运行pytest时,会找不到Python/下的example_package模块,以下是几种可行的修复方案:

方案1:配置VS Code的测试工作目录

直接让VS Code在Python/目录下运行pytest:

  • 打开VS Code设置(快捷键Ctrl+,),搜索「pytest working directory」
  • 找到「Python > Testing: Cwd」,设置为${workspaceFolder}/Python
  • 或者在「Python > Testing: Pytest Args」中添加--rootdir=Python参数
  • 也可以直接在项目根目录的.vscode/settings.json里写入配置:
    {
        "python.testing.cwd": "${workspaceFolder}/Python",
        "python.testing.pytestArgs": ["--rootdir=Python"]
    }
    

方案2:在Python目录下添加pytest配置文件

让pytest自动识别正确的根目录:

  • 在Python/文件夹下创建pytest.ini文件,写入以下内容:
    [pytest]
    testpaths = tests
    pythonpath = .
    
    这个配置会告诉pytest把当前目录(Python目录)加入模块搜索路径,同时指定测试文件所在的tests目录。

方案3:临时修改测试文件的模块搜索路径

如果只是临时测试,可以在测试文件开头添加代码强制添加路径:

  • 打开tests/test_example_package.py,在最顶部加入:
    import sys
    from pathlib import Path
    
    # 将Python目录添加到模块搜索路径
    sys.path.insert(0, str(Path(__file__).parent.parent))
    
    这种方法适合快速验证,但不推荐长期使用,硬编码路径会降低代码可移植性。

方案4:终端手动运行pytest

绕过VS Code的默认工作目录限制:

  1. 打开终端,切换到Python目录:cd Python
  2. 激活项目的虚拟环境:
    • Linux/macOS:. .venv/bin/activate
    • Windows:.venv\Scripts\activate
  3. 直接执行pytest命令,此时工作目录就是Python目录,能正常识别模块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 03:09:59