从Pipenv迁移至uv后,VS Code调试pytest无法激活求助
将Django项目从Pipenv迁移到uv后,在VS Code Dev Container中调试pytest单元测试时出现异常:测试能正常运行,但断点始终无法触发,调试器未激活。已确认Python解释器指向uv虚拟环境,且安装了debugpy,手动尝试debugpy监听也未成功,怀疑问题与pytest.ini中的配置相关。
解决方案
排查
--import-mode=importlib配置
pytest.ini中的--import-mode=importlib会改变模块导入机制,可能干扰debugpy的进程注入逻辑。先临时注释该选项,重新尝试调试:[pytest] # Test coverage options addopts = --cov=. --cov-branch --cov-fail-under=75 --cov-report=html --cov-report=term-missing # --import-mode=importlib # 临时注释修正VS Code调试配置(launch.json)
确保调试配置正确关联uv虚拟环境,且参数未覆盖debugpy的注入逻辑。示例配置:{ "version": "0.2.0", "configurations": [ { "name": "Python: pytest 调试", "type": "python", "request": "launch", "module": "pytest", "args": ["src/nexxus/tests/test_views.py::TestLegacyClientView::test_legacy_client_view_returns_active_servers"], "justMyCode": false, "python": "${command:python.interpreterPath}" } ] }使用debugpy正确启动pytest
手动调试时,需让pytest进程启动时直接绑定debugpy,而非先开监听再跑测试。执行以下命令:uv run python -m debugpy --listen 127.0.0.1:5678 --wait-for-client -m pytest src/nexxus/tests/test_views.py::TestLegacyClientView::test_legacy_client_view_returns_active_servers然后在VS Code中添加Attach类型的调试配置:
{ "name": "Python: Attach to debugpy", "type": "python", "request": "attach", "connect": { "host": "127.0.0.1", "port": 5678 }, "justMyCode": false }启动Attach配置后,测试会等待调试连接,断点即可触发。
验证uv虚拟环境路径
在Dev Container中,通过Ctrl+Shift+P打开"Python: Select Interpreter",确认选中的路径为uv创建的虚拟环境(通常为/workspace/.venv/bin/python)。排查coverage插件冲突
临时注释pytest.ini中所有--cov开头的选项,测试调试是否正常。若恢复正常,说明coverage的hook与debugpy存在冲突,可尝试更新coverage版本(uv add coverage --dev)或调整coverage配置。
内容的提问来源于stack exchange,提问作者Bob Tanner

