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

从Pipenv迁移至uv后,VS Code调试pytest无法激活求助

解决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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 11:27:20