Bats shell testing

From findscripter/everything-skills · View interactive version

Bats shell testing is an AI agent skill from the GitHub repository findscripter/everything-skills. 当为 Bash/POSIX shell 脚本、CLI 工具或 CI 流程写单元测试、做 TDD 时使用;做 Bats(Bash Automated Testing System)测试编写——断言退出码/输出/文件副作用、setup/teardown 夹具、命令打桩(stub)、CI 接入,产出 .bats 测试套件与 TAP 报告;不适用于非 shell 项目、跨服务集成测试、仅做 lint/格式化或纯 shellcheck 静态检查;触发词:bats、shell 脚本测试、@test、TAP、脚本 TDD

How to use this skill

Skill file

何时使用

步骤

  1. 装 Bats 并确认目标 shell:brew install bats-core / npm i -g bats / 源码 ./install.sh /usr/local;bats --version 验证。先确认要支持的 shell 方言与环境。
  2. 搭测试结构:脚本放 bin/,测试放 tests/*.bats,夹具放 tests/fixtures/,共享工具放 tests/test_helper.sh(用 load test_helper 引入)。
  3. 写测试三类断言:退出码($status)、输出($output / ${lines[N]})、副作用(文件是否生成/内容/权限)。每个测试只验一件事,命名清楚说明意图。
  4. 加 setup/teardown:setup 建临时目录与夹具,teardown 清理;昂贵的一次性准备用 setup_file/teardown_file。
  5. 隔离外部依赖:mock 函数或在 PATH 前置 stub 目录拦截 curl/jq 等命令;缺依赖用 skip。
  6. 跑测试并接 CI:本地 bats tests/*.bats(--tap 出 TAP、--parallel N 并行),在 GitHub Actions / Makefile 中固化。

指令

核心 API(背下来)

断言惯用法

夹具与隔离

示例

最小测试文件(夹具 + 三类断言):

#!/usr/bin/env bats
load test_helper

setup()    { TMPDIR=$(mktemp -d); export TMPDIR; }
teardown() { rm -rf "$TMPDIR"; }

@test "成功时返回 0" {
    run my_function "input"
    [ "$status" -eq 0 ]
}

@test "缺参时报错并提示 Usage" {
    run my_function
    [ "$status" -ne 0 ]
    [[ "$output" == *"Usage:"* ]]
}

@test "生成输出文件且内容正确" {
    my_function > "$TMPDIR/out.txt"
    [ -f "$TMPDIR/out.txt" ]
    [ "$(cat "$TMPDIR/out.txt")" = "expected content" ]
}

命令打桩(拦截外部 curl):

create_stub() {            # 在 $STUBS_DIR 生成假命令
    cat > "$STUBS_DIR/$1" <<EOF
#!/bin/bash
echo "$2"
exit ${3:-0}
EOF
    chmod +x "$STUBS_DIR/$1"
}

@test "API 调用走桩" {
    create_stub curl '{ "status": "ok" }' 0
    run my_api_function
    [ "$status" -eq 0 ]
}

依赖缺失时跳过 + 多 shell 兼容:

@test "JSON 解析" {
    command -v jq >/dev/null || skip "jq 未安装"
    run my_json_parser '{"key":"value"}'
    [ "$status" -eq 0 ]
}

@test "脚本在 POSIX sh 下可运行" {
    sh "${BATS_TEST_DIRNAME}/../bin/script.sh" arg1
}

CI 接入(GitHub Actions 片段):

- name: Install Bats
  run: npm install --global bats
- name: Run Tests
  run: bats tests/*.bats --tap | tee test_output.tap

注意事项

互见


采编自 sickn33/antigravity-awesome-skills(MIT 许可)。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.