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

如何配置VSCode识别backend子目录下的Python测试文件?

解决VSCode中pytest无法识别backend目录下Python模块的问题

问题背景

项目目录结构如下:

.
├── backend
│   ├── mypackage
│   │   └── main.py
│   ├── tests
│   │   └── test_main.py
│   ├── Dockerfile
│   └── pyproject.toml
├── frontend
│   ├── src
│   │   └── App.js
│   ├── Dockerfile
│   └── package.json
└── README.md

测试文件backend/tests/test_main.py代码:

from mypackage.main import my_function

def test_that_my_function_works():
    my_function()

点击VSCode「测试」标签时触发pytest Discovery Error,错误日志:

ImportError while importing test module '/home/user/myproject/backend/tests/test_main.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
../../../.pyenv/versions/3.12.1/lib/python3.12/importlib/init.py:90: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
backend/tests/test_main.py:1: in
from mypackage.main import my_function
E ModuleNotFoundError: No module named 'mypackage'
=========================== short test summary info ============================
ERROR backend/tests/test_main.py
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
===================== no tests collected, 1 error in 0.17s =====================

问题核心:VSCode默认以仓库根目录作为pytest运行基准目录,导致无法找到backend下的mypackage模块。

解决方法

方法1:修改VSCode的pytest工作目录

  1. 打开VSCode设置(快捷键Ctrl+,或Cmd+,)
  2. 搜索pytest: Working Directory
  3. 在输入框中填写${workspaceFolder}/backend
  4. 保存设置后重新触发测试发现

方法2:通过pyproject.toml配置pytest

在backend/pyproject.toml中添加以下配置,让pytest自动以backend为基准目录:

[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]

方法3:通过VSCode工作区配置文件指定

在项目根目录创建.vscode/settings.json文件,写入以下内容:

{
    "python.testing.pytestArgs": ["backend/tests"],
    "python.testing.pytestEnabled": true,
    "python.testing.cwd": "${workspaceFolder}/backend"
}

方法4:临时添加Python路径(不推荐长期使用)

在测试文件开头加入代码,将backend目录手动加入Python路径:

import sys
from pathlib import Path

sys.path.append(str(Path(__file__).parent.parent))

from mypackage.main import my_function

def test_that_my_function_works():
    my_function()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 20:35:06