← retour aux snippets

bats-core: tester des scripts shell (minimal)

Écrire et exécuter des tests Bats pour scripts shell avec assertions simples.

bash testing #bats#tests#shell

objectif

Valider le comportement d’un script shell via des tests automatisés en TAP.

code minimal

# installer bats-core (exemple Debian/Ubuntu)
sudo apt-get update && sudo apt-get install -y bats

# test fichier: test_hello.bats
cat > test_hello.bats <<'BATS'
#!/usr/bin/env bats

setup() {
  load 'test_helper/bats-support/load'
  load 'test_helper/bats-assert/load' 2>/dev/null || true
}

@test "prints hello" {
  run bash -lc 'echo hello'
  [ "$status" -eq 0 ]
  [ "$output" = "hello" ]
}
BATS
chmod +x test_hello.bats

# exécuter
bats -r .

utilisation

# asserter avec bats-assert si dispo
# (vendori­sez submodules test_helper/)
git submodule add https://github.com/bats-core/bats-support test_helper/bats-support || true
git submodule add https://github.com/bats-core/bats-assert test_helper/bats-assert || true

variante(s) utile(s)

# filtrer par nom de test
bats -r . -f hello

notes

  • structurez vos tests test_*.bats et utilisez run pour capturer output/status.
  • pour l’isolation, créez un TMPDIR par test dans setup().