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把当前目录(Python目录)加入模块搜索路径,同时指定测试文件所在的[pytest] testpaths = tests pythonpath = .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的默认工作目录限制:
- 打开终端,切换到Python目录:
cd Python - 激活项目的虚拟环境:
- Linux/macOS:
. .venv/bin/activate - Windows:
.venv\Scripts\activate
- Linux/macOS:
- 直接执行
pytest命令,此时工作目录就是Python目录,能正常识别模块。
内容的提问来源于stack exchange,提问作者user2138149
相关产品推荐
相关产品推荐

