VS Code运行 pytest_hello_world.py 在 VS Code 中运行 pytest_hello_world.py 更便捷,支持图形化操作、断点调试和结果可视化,步骤如下(含环境配置、运行方式、调试技巧):
首先确保安装 Python 相关插件(核心支持 pytest 运行):
Ctrl+Shift+X / Cmd+Shift+X)。假设已编写 pytest_hello_world.py(参考上一轮的测试代码),且 VS Code 已打开该文件所在的「工作区」(重要!需将文件所在文件夹添加到 VS Code 工作区,否则可能识别不到用例)。
VS Code 内置终端,无需切换窗口,直接执行命令:
Ctrl+`` / Cmd+``)。venvScriptsactivate(Windows)或 source venv/bin/activate(Mac/Linux))。pip install pytest。# 方式 1:运行整个文件
pytest pytest_hello_world.py -v
# 方式 2:运行文件中的单个用例
pytest pytest_hello_world.py::test_hello_world -v
Python 插件内置 pytest 集成,无需手动输命令,点击即可运行:
pytest_hello_world.py 文件。test_ 开头的函数(如 test_hello_world)上方会出现「运行测试」/「调试测试」的按钮(小三角/小虫子图标),点击即可直接运行该用例。Ctrl+Shift+T / Cmd+Shift+T),再点击顶部「配置测试」。test_*.py)。test_hello_world、test_addition)。若安装了 Pytest Explorer 插件,操作更直观:
当测试用例失败时,可通过调试模式逐步排查:
assert result == "helloworld" 行设置断点)。F5)、「单步跳过」(F10)、「单步进入」(F11)、「退出调试」(Shift+F5)。test_ 开头,用例以 test_ 开头)。pytest --version 验证,若提示「pytest 不是内部或外部命令」,则重新安装 pip install pytest)。Pytest Explorer →「扩展设置」),确认「Pytest: Python Path」已选择正确的 Python 环境。VS Code 中运行 pytest_hello_world.py 的核心是「环境正确 + 用例识别」:
按以上步骤操作,即可在 VS Code 中快速运行和调试 pytest 测试用例。
审核编辑 黄宇
全部0条评论
快来发表一下你的评论吧 !