使用VS Code的任务(Tasks)来运行测试脚本

在 VS Code 中配置 tasks.json 可一键运行测试脚本,核心是设置 label、type、command、args、group、presentation 和 problemMatcher;支持多环境适配、动态文件执行及与调试联动。

使用vs code的任务(tasks)来运行测试脚本

在 VS Code 中用 Tasks 运行测试脚本,核心是配置 tasks.json,让编辑器能一键触发命令(比如 pytestpython -m unittest 或自定义脚本),无需切到终端手动敲。

创建或编辑 tasks.json

打开命令面板(Ctrl+Shift+P / Cmd+Shift+P),输入并选择 Tasks: Configure Task → 选 Create tasks.json file from template → 选 Others。VS Code 会在 .vscode/tasks.json 中生成基础模板。

  • 确保 version"2.0.0"(新版格式)
  • label 设为易识别的名字,如 "Run tests with pytest"
  • type 设为 "shell"(推荐)或 "process",便于执行带管道、重定向的命令

写一个可运行的测试任务

以 Python 项目常用 pytest 为例,假设测试文件在 tests/ 目录下:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Run pytest",
      "type": "shell",
      "command": "pytest",
      "args": ["tests/", "-v", "--tb=short"],
      "group": "test",
      "presentation": {
        "echo": true,
        "reveal": "always",
        "focus": false,
        "panel": "new",
        "showReuseMessage": true,
        "clear": true
      },
      "problemMatcher": ["$pytest"]
    }
  ]
}
  • args 支持传参,比如加 --cov=src 跑覆盖率
  • group: "test" 让它归类到「测试」组,方便用 Ctrl+Shift+P → Tasks: Run Test Task 快速调用
  • problemMatcher: ["$pytest"] 可解析错误输出,点击问题直接跳转到失败行(需安装 Python 扩展)

支持多环境或条件运行

如果项目有多个测试套(单元/集成/E2E),可配多个 task 并用 dependsOn 或变量区分:

AutoIt3 中文帮助文档打包 AutoIt3 中文帮助文档打包

AutoIt v3 版本, 这是一个使用类似 BASIC 脚本语言的免费软件, 它设计用于 Windows GUI(图形用户界面)中进行自动化操作. 利用模拟键盘按键, 鼠标移动和窗口/控件的组合来实现自动化任务. 而这是其它语言不可能做到或无可靠方法实现的(比如VBScript和SendKeys). AutoIt 非常小巧, 完全运行在所有windows操作系统上.(thesnow注:现在已经不再支持win 9x,微软连XP都能放弃, 何况一个win 9x支持), 并且不需要任何运行库. AutoIt

AutoIt3 中文帮助文档打包 57 查看详情 AutoIt3 中文帮助文档打包
  • ${fileBasenameNoExtension} 动态运行当前测试文件:"command": "pytest", "args": ["${file}"]
  • windows/linux/osx 字段做平台适配,比如 Windows 下用 py -m pytest 避免命令找不到
  • 配合 isBackground: trueproblemMatcher 实现持续监听(适合 watch 模式)

快捷运行与调试联动

配好后,几种常用方式:

  • Ctrl+Shift+P → Tasks: Run Task → 选 "Run pytest"
  • 右键测试文件 → Run Task(需在文件内右键)
  • 绑定快捷键:在 keybindings.json 加一条:{"key": "ctrl+t", "command": "workbench.action.terminal.runActiveFile", "args": {"task": "Run pytest"}}
  • 和调试结合:在 launch.jsonpreLaunchTask 指定该 task,确保每次调试前先跑测试

基本上就这些。不复杂但容易忽略的是 problemMatcherpresentation.clear——加上它们,体验会明显更顺。

以上就是使用VS Code的任务(Tasks)来运行测试脚本的详细内容,更多请关注php中文网其它相关文章!

本文转自网络,如有侵权请联系客服删除。