# Bats Testing Patterns > Domina Bats (Bash Automated Testing System) para probar exhaustivamente scripts de shell, útil en TDD y pipelines CI/CD. Fuente: https://skillsagentes.com/skills/wshobson/agents/bats-testing-patterns Markdown: https://skillsagentes.com/skills/wshobson/agents/bats-testing-patterns.md Repositorio: https://github.com/wshobson/agents Autor: wshobson Licencia: MIT Actualizado: hace 4 meses Coste de contexto: 50 tok instalada, 1.3k tok al activarse, 3.1k tok con todos los archivos del bundle Bundle: 2 archivos, 12 KB Permisos que pide: ninguno declarado ## Instalación Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina. ```bash # Claude Code npx -y skills add wshobson/agents --skill bats-testing-patterns --agent claude-code # Cursor npx -y skills add wshobson/agents --skill bats-testing-patterns --agent cursor # Codex npx -y skills add wshobson/agents --skill bats-testing-patterns --agent codex # Gemini CLI npx -y skills add wshobson/agents --skill bats-testing-patterns --agent gemini # Windsurf npx -y skills add wshobson/agents --skill bats-testing-patterns --agent windsurf # Cline npx -y skills add wshobson/agents --skill bats-testing-patterns --agent cline ``` ## Qué hace - Enseña patrones para escribir tests unitarios de scripts de shell con Bats - Proporciona ejemplos de tests para condiciones de error, dependencias y compatibilidad entre shells - Incluye patrones de test helpers, fixtures y ejecución paralela - Muestra integración de Bats en pipelines CI/CD (GitHub Actions, Makefile) ## Cuándo usarla - Escribir tests unitarios para scripts de shell - Implementar desarrollo dirigido por tests (TDD) para scripts - Configurar pruebas automatizadas en pipelines CI/CD - Testear casos límite, condiciones de error o compatibilidad entre bash, sh y dash ## Qué la activa - "Escríbeme tests Bats para este script de bash" - "Ayúdame a configurar TDD para mis scripts de shell" - "Necesito tests que verifiquen compatibilidad entre bash, sh y dash" - "Integra Bats en mi pipeline de GitHub Actions" ## Antes de instalar - Requiere tener instalado Bats (Bash Automated Testing System), y opcionalmente jq o dash para ciertos tests. - Necesita en el PATH: npm - Variables de entorno: BATS_TEST_DIRNAME, TEST_DIR - reads environment config ## Archivos - SKILL.md — 5 KB - references/details.md — 7 KB ## SKILL.md Reproducido tal cual desde wshobson/agents bajo MIT. Esta sección es el documento original y está en inglés. # Bats Testing Patterns Comprehensive guidance for writing comprehensive unit tests for shell scripts using Bats (Bash Automated Testing System), including test patterns, fixtures, and best practices for production-grade shell testing. ## When to Use This Skill - Writing unit tests for shell scripts - Implementing test-driven development (TDD) for scripts - Setting up automated testing in CI/CD pipelines - Testing edge cases and error conditions - Validating behavior across different shell environments - Building maintainable test suites for scripts - Creating fixtures for complex test scenarios - Testing multiple shell dialects (bash, sh, dash) ## Detailed patterns and worked examples Detailed pattern documentation lives in `references/details.md`. Read that file when the navigation tier above is insufficient. ## Testing Error Conditions ```bash #!/usr/bin/env bats @test "Function fails with missing file" { run my_function "/nonexistent/file.txt" [ "$status" -ne 0 ] [[ "$output" == *"not found"* ]] } @test "Function fails with invalid input" { run my_function "" [ "$status" -ne 0 ] } @test "Function fails with permission denied" { touch "$TMPDIR/readonly.txt" chmod 000 "$TMPDIR/readonly.txt" run my_function "$TMPDIR/readonly.txt" [ "$status" -ne 0 ] chmod 644 "$TMPDIR/readonly.txt" # Cleanup } @test "Function provides helpful error message" { run my_function --invalid-option [ "$status" -ne 0 ] [[ "$output" == *"Usage:"* ]] } ``` ### Testing with Dependencies ```bash #!/usr/bin/env bats setup() { # Check for required tools if ! command -v jq &>/dev/null; then skip "jq is not installed" fi export SCRIPT="${BATS_TEST_DIRNAME}/../bin/script.sh" } @test "JSON parsing works" { skip_if ! command -v jq &>/dev/null run my_json_parser '{"key": "value"}' [ "$status" -eq 0 ] } ``` ### Testing Shell Compatibility ```bash #!/usr/bin/env bats @test "Script works in bash" { bash "${BATS_TEST_DIRNAME}/../bin/script.sh" arg1 } @test "Script works in sh (POSIX)" { sh "${BATS_TEST_DIRNAME}/../bin/script.sh" arg1 } @test "Script works in dash" { if command -v dash &>/dev/null; then dash "${BATS_TEST_DIRNAME}/../bin/script.sh" arg1 else skip "dash not installed" fi } ``` ### Parallel Execution ```bash #!/usr/bin/env bats @test "Multiple independent operations" { run bash -c 'for i in {1..10}; do my_operation "$i" & done wait' [ "$status" -eq 0 ] } @test "Concurrent file operations" { for i in {1..5}; do my_function "$TMPDIR/file$i" & done wait [ -f "$TMPDIR/file1" ] [ -f "$TMPDIR/file5" ] } ``` ## Test Helper Pattern ### test_helper.sh ```bash #!/usr/bin/env bash # Source script under test export SCRIPT_DIR="${BATS_TEST_DIRNAME%/*}/bin" # Common test utilities assert_file_exists() { if [ ! -f "$1" ]; then echo "Expected file to exist: $1" return 1 fi } assert_file_equals() { local file="$1" local expected="$2" if [ ! -f "$file" ]; then echo "File does not exist: $file" return 1 fi local actual=$(cat "$file") if [ "$actual" != "$expected" ]; then echo "File contents do not match" echo "Expected: $expected" echo "Actual: $actual" return 1 fi } # Create temporary test directory setup_test_dir() { export TEST_DIR=$(mktemp -d) } cleanup_test_dir() { rm -rf "$TEST_DIR" } ``` ## Integration with CI/CD ### GitHub Actions Workflow ```yaml name: Tests on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install Bats run: | npm install --global bats - name: Run Tests run: | bats tests/*.bats - name: Run Tests with Tap Reporter run: | bats tests/*.bats --tap | tee test_output.tap ``` ### Makefile Integration ```makefile .PHONY: test test-verbose test-tap test: bats tests/*.bats test-verbose: bats tests/*.bats --verbose test-tap: bats tests/*.bats --tap test-parallel: bats tests/*.bats --parallel 4 coverage: test # Optional: Generate coverage reports ``` ## Best Practices 1. **Test one thing per test** - Single responsibility principle 2. **Use descriptive test names** - Clearly states what is being tested 3. **Clean up after tests** - Always remove temporary files in teardown 4. **Test both success and failure paths** - Don't just test happy path 5. **Mock external dependencies** - Isolate unit under test 6. **Use fixtures for complex data** - Makes tests more readable 7. **Run tests in CI/CD** - Catch regressions early 8. **Test across shell dialects** - Ensure portability 9. **Keep tests fast** - Run in parallel when possible 10. **Document complex test setup** - Explain unusual patterns ## Dónde encaja - Categoría: [Testing y QA](https://skillsagentes.com/categorias/testing-qa.md) — Flujos de testing unitario, de integración y end-to-end. - Creador: [wshobson](https://skillsagentes.com/creators/wshobson.md) — 183 skills en el directorio - [Todas las skills](https://skillsagentes.com/skills.md) - [Ranking de instalaciones](https://skillsagentes.com/ranking.md) ## Otras skills del mismo repositorio - [Hermes Tweet](https://skillsagentes.com/skills/wshobson/agents/hermes-tweet.md): Instala y opera Hermes Tweet, un plugin de Hermes Agent para investigar X/Twitter, leer timelines, analizar tweets y ejecutar operaciones privadas o de cambio de estado con aprobación previa. - [Grounded Vault](https://skillsagentes.com/skills/wshobson/agents/grounded-vault.md): Úsalo para mantener un almacén Markdown de conocimiento donde cada afirmación compilada se rastrea hasta una fuente inmutable y el drift se detecta con git diff sin gastar tokens. - [Postgresql Table Design](https://skillsagentes.com/skills/wshobson/agents/postgresql-table-design.md): Úsalo al diseñar o revisar un esquema específico de PostgreSQL: buenas prácticas, tipos de datos, indexación, restricciones, patrones de rendimiento y funciones avanzadas. - [Superself](https://skillsagentes.com/skills/wshobson/agents/superself.md): Úsalo cuando un proyecto guarda su estado en Superself: lee `self context` al iniciar sesión, vincula el trabajo a una work unit, reporta con evidencia y registra decisiones confirmadas. - [Prompt Engineering Patterns](https://skillsagentes.com/skills/wshobson/agents/prompt-engineering-patterns.md): Úsalo cuando pidan optimizar un prompt, mejorar su rendimiento, diseñar una plantilla, aplicar chain-of-thought, few-shot prompting o técnicas avanzadas de prompt engineering para producción. ## Skills relacionadas - [Ai Debt Detector](https://skillsagentes.com/skills/wshobson/agents/ai-debt-detector.md): Úsalo tras generar código con IA, aceptar sugerencias o revisar módulos escritos por IA, o cuando el código funcione pero parezca frágil o con deuda oculta. - [Checkpoint Promotion](https://skillsagentes.com/skills/wshobson/agents/checkpoint-promotion.md): Filtra checkpoints fine-tuneados con presupuestos de drift, comparación pareada y chequeos de olvido antes de promoverlos, tras un entrenamiento o al re-gatear un modelo ya promovido. - [Code Review Excellence](https://skillsagentes.com/skills/wshobson/agents/code-review-excellence.md): Domina prácticas efectivas de revisión de código para dar feedback constructivo, detectar bugs a tiempo y fomentar el intercambio de conocimiento sin dañar la moral del equipo. - [Debugging Strategies](https://skillsagentes.com/skills/wshobson/agents/debugging-strategies.md): Domina técnicas sistemáticas de depuración, herramientas de profiling y análisis de causa raíz para localizar bugs en cualquier código o stack tecnológico. - [E2e Testing Patterns](https://skillsagentes.com/skills/wshobson/agents/e2e-testing-patterns.md): Domina el testing end-to-end con Playwright y Cypress para construir suites fiables que detecten bugs y permitan despliegues rápidos. --- Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)