公司代理环境下VSCode无法检测pytest单元测试求助
- 环境:Windows 10 系统,VSCode 1.69.2,公司代理环境
- 异常表现:
- 测试面板搜索栏重启VSCode后始终显示“d”
- 已确认安装pytest,但VSCode的Python输出面板报错
ImportError: No module named pytest,完整报错内容:
LSP Notebooks experiment is disabled -- not in treatment group
python -c "import sys;print(sys.executable)"
python -c "import sys;print(sys.executable)" Python interpreter path: /usr/local/bin/python
python -c "import sys;print(sys.executable)" Starting Pylance language server.
python ./.vscode-server/extensions/ms-python.python-2022.10.1/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir . -s --cache-clear workflow cwd: .
[ERROR 2022-6-26 13:1:2.338]: Error discovering pytest tests: [n [Error]:
Traceback (most recent call last):
File "/home/cdsw/.vscode-server/extensions/ms-python.python-2022.10.1/pythonFiles/testing_tools/run_adapter.py", line 17, in
from testing_tools.adapter.main import parse_args, main
File "/home/cdsw/.vscode-server/extensions/ms-python.python-2022.10.1/pythonFiles/testing_tools/adapter/main.py", line 9, in
from . import pytest, report
File "/home/cdsw/.vscode-server/extensions/ms-python.python-2022.10.1/pythonFiles/testing_tools/adapter/pytest/init.py", line 7, in
from ._discovery import discover
File "/home/cdsw/.vscode-server/extensions/ms-python.python-2022.10.1/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 8, in
import pytest
ImportError: No module named pytest
1. 对齐VSCode使用的Python解释器与pytest安装环境
从报错可见,VSCode正在调用/usr/local/bin/python,但pytest并未安装在该解释器环境中:
- 点击VSCode左下角的Python解释器选择器,切换到已安装pytest的解释器;
- 如果是远程开发场景,直接在远程环境给目标解释器安装pytest:
/usr/local/bin/python -m pip install pytest
2. 配置VSCode的pytest路径(可选)
若切换解释器后问题仍存在,在.vscode/settings.json中指定pytest的具体路径:
{ "python.testing.pytestPath": "/usr/local/bin/pytest", "python.testing.pytestEnabled": true }
替换/usr/local/bin/pytest为实际的pytest可执行文件路径。
3. 解决代理环境下的依赖安装问题
如果安装pytest时受公司代理限制:
- 临时代理安装:
pip install pytest --proxy=http://你的代理地址:端口
- 永久配置代理:在用户目录创建
pip.conf(Linux)或pip.ini(Windows),添加:
[global] proxy = http://你的代理地址:端口
4. 重置VSCode测试缓存
打开命令面板(Ctrl+Shift+P),执行Python: Clear Test Cache,重启VSCode后重新检测测试。
内容的提问来源于stack exchange,提问作者Winston Fan

