Communitygithub.com

Jamie-BitFlight/bash-testing

Esta habilidad debe usarse cuando el usuario solicite 'probar script bash', 'escribir pruebas shell', 'usar shunit2', 'usar shellspec', 'crear suite de pruebas para bash', o mencione pruebas unitarias, marcos de pruebas, mocking o desarrollo guiado por pruebas para scripts de shell.

¿Qué es bash-testing?

Esta habilidad proporciona un conjunto completo de marcos de pruebas y patrones para scripts de shell, centrándose en shunit2 y shellspec. Es útil para desarrolladores que necesitan escribir pruebas unitarias, pruebas basadas en comportamiento, mocking y pruebas de integración para scripts Bash, mejorando la fiabilidad y facilitando el desarrollo guiado por pruebas (TDD). La habilidad es compatible con cualquier entorno donde se ejecuten scripts Bash (Linux, macOS, WSL) y se integra con herramientas como ShellCheck o linters. Incluye ejemplos de instalación, estructura básica de pruebas, aserciones, mocking, pruebas de salida estándar y error, manejo de fixtures, pruebas de funciones interactivas y ejecución de pruebas. También cubre buenas prácticas como aislamiento de pruebas, limpieza de recursos y pruebas de casos límite. Los usuarios pueden seleccionar entre shunit2 para un estilo xUnit simple y portátil, o shellspec para un enfoque BDD moderno y completo.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Jamie-BitFlight/claude_skills/tree/main/plugins/bash-development/skills/bash-testing

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Pruebas Bash

Marcos de pruebas y patrones para scripts de shell, centrados en shunit2 y shellspec.

Selección de Marco

MarcoFortalezasMejor para
shunit2Estilo xUnit, simple, portátilPruebas unitarias, pruebas de funciones
shellspecEstilo BDD, moderno, extensoEspecificaciones de comportamiento, proyectos completos

shunit2

Instalación

# Descarga directa
curl -L https://github.com/kward/shunit2/raw/master/shunit2 -o shunit2

# O mediante gestor de paquetes
apt install shunit2
brew install shunit2

Estructura Básica de Prueba

#!/usr/bin/env bash

# Incluir el script que se está probando
source ./mi_script.sh

# Las funciones de prueba comienzan con test
test_adicion() {
    resultado=$(sumar 2 3)
    assertEquals "2 + 3 debería ser 5" "5" "$resultado"
}

test_salida_cadena() {
    resultado=$(saludar "Mundo")
    assertEquals "Hola, Mundo" "$resultado"
}

test_creacion_archivo() {
    crear_archivo_temporal
    assertTrue "El archivo temporal debería existir" "[ -f /tmp/archivo_prueba ]"
}

test_codigo_salida() {
    validar_entrada "valido"
    assertEquals "Debería devolver 0 para entrada válida" 0 $?
}

# Configuración y limpieza
oneTimeSetUp() {
    # Ejecutar una vez antes de todas las pruebas
    export DIR_PRUEBA=$(mktemp -d)
}

oneTimeTearDown() {
    # Ejecutar una vez después de todas las pruebas
    rm -rf "$DIR_PRUEBA"
}

setUp() {
    # Ejecutar antes de cada prueba
    cd "$DIR_PRUEBA"
}

tearDown() {
    # Ejecutar después de cada prueba
    rm -f "$DIR_PRUEBA"/*
}

# Cargar shunit2
source shunit2

Aserciones shunit2

# Igualdad
assertEquals [mensaje] esperado actual
assertNotEquals [mensaje] inesperado actual

# Nulo/Vacío
assertNull [mensaje] valor
assertNotNull [mensaje] valor

# Booleano/Estado
assertTrue [mensaje] condición
assertFalse [mensaje] condición

# Misma referencia (comparación de cadenas)
assertSame [mensaje] esperado actual
assertNotSame [mensaje] inesperado actual

# Contiene (en cadena)
assertContains [mensaje] contenedor contenido

# Estado de salida
assertEquals 0 $?

Pruebas de Funciones en Aislamiento

Ejemplos de código

#!/usr/bin/env bash
# pruebas_mis_funciones.sh

source ./mis_funciones.sh

test_calcular_suma_vacio() {
    resultado=$(calcular_suma)
    assertEquals "La suma vacía debería ser 0" "0" "$resultado"
}

test_calcular_suma_unico() {
    resultado=$(calcular_suma 5)
    assertEquals "5" "$resultado"
}

test_calcular_suma_multiple() {
    resultado=$(calcular_suma 1 2 3 4 5)
    assertEquals "15" "$resultado"
}

test_validar_email_valido() {
    validar_email "[email protected]"
    assertTrue "El email válido debería pasar" $?
}

test_validar_email_invalido() {
    validar_email "no-es-un-email"
    assertFalse "El email inválido debería fallar" $?
}

source shunit2

shellspec

Instalación

# Mediante curl
curl -fsSL https://git.io/shellspec | sh

# Mediante Homebrew
brew install shellspec

# Mediante gestores de paquetes
apt install shellspec

Estructura de Directorios

proyecto/
├── lib/
│   └── funciones.sh
├── spec/
│   ├── spec_helper.sh
│   ├── funciones_spec.sh
│   └── support/
│       └── fixtures/
└── .shellspec

Configuración (.shellspec)

--require spec_helper
--format documentation
--color

Estructura Básica de Especificación

Ejemplos de código

Comparadores shellspec

# Comparadores de salida
The output should eq "coincidencia exacta"
The output should include "parcial"
The output should start with "prefijo"
The output should end with "sufijo"
The output should match pattern "*comodín*"
The output should be blank

# Comparadores de estado
The status should be success    # salida 0
The status should be failure    # salida distinta de cero
The status should eq 1          # código específico

# Comparadores de variables
The variable VAR should eq "valor"
The variable VAR should be defined
The variable VAR should be undefined

# Comparadores de archivos
The file "ruta" should be exist
The file "ruta" should be file
The file "ruta" should be directory
The file "ruta" should be readable

# Comparadores de rutas
The path "archivo.txt" should be exist

Mocking en shellspec

Describe 'función de despliegue'
  # Mock de comando externo
  curl() {
    echo "respuesta simulada"
    return 0
  }

  It 'llama al endpoint de la API'
    When call desplegar "servidor"
    The output should include "respuesta simulada"
  End
End

Describe 'operaciones de archivos'
  # Mock con anulación de función
  Mock rm
    echo "rm llamado con: $*"
  End

  It 'intenta eliminar archivo'
    When call limpiar_temporal
    The output should include "rm llamado con"
  End
End

Helper de Especificación

# spec/spec_helper.sh

# Cargar funciones comunes
spec_helper_precheck() {
  minimum_version "0.28.0"
}

spec_helper_loaded() {
  # Configurar entorno de prueba
  export MODO_PRUEBA=true
}

spec_helper_configure() {
  # Importar funciones del proyecto
  import 'lib/funciones.sh'
}

Patrones de Prueba

Pruebas de Códigos de Salida

# shunit2
test_salida_exitosa() {
    ejecutar_comando "entrada_valida"
    assertEquals 0 $?
}

test_salida_error() {
    ejecutar_comando "entrada_invalida"
    assertEquals 1 $?
}

# shellspec
It 'sale con 0 en éxito'
  When call ejecutar_comando "entrada_valida"
  The status should eq 0
End

Pruebas de stdout y stderr

# shunit2
test_stdout() {
    resultado=$(mi_funcion 2>/dev/null)
    assertEquals "salida esperada" "$resultado"
}

test_stderr() {
    error=$(mi_funcion 2>&1 >/dev/null)
    assertContains "$error" "mensaje de error"
}

# shellspec
It 'envía salida a stdout'
  When call mi_funcion
  The stdout should eq "salida esperada"
End

It 'envía error a stderr'
  When call mi_funcion
  The stderr should include "mensaje de error"
End

Pruebas con Fixtures

# Configurar fixtures de prueba
setUp() {
    DIR_PRUEBA=$(mktemp -d)
    cat > "$DIR_PRUEBA/config.json" <<EOF
{
    "clave": "valor"
}
EOF
}

tearDown() {
    rm -rf "$DIR_PRUEBA"
}

test_analisis_config() {
    resultado=$(analizar_config "$DIR_PRUEBA/config.json")
    assertEquals "valor" "$resultado"
}

Pruebas de Funciones Interactivas

# Proporcionar entrada mediante heredoc
test_interactiva() {
    resultado=$(mi_prompt <<EOF
sí
EOF
)
    assertEquals "confirmado" "$resultado"
}

# O usar printf
test_con_entrada() {
    resultado=$(printf 'sí\n' | mi_prompt)
    assertEquals "confirmado" "$resultado"
}

Ejecución de Pruebas

# shunit2
./script_prueba.sh

# shellspec
shellspec                    # Ejecutar todas las especificaciones
shellspec spec/archivo_spec.sh  # Ejecutar especificación específica
shellspec --format tap       # Salida TAP
shellspec --jobs 4           # Ejecución paralela

Buenas Prácticas

  1. Una aserción por prueba cuando sea práctico
  2. Nombres descriptivos de prueba explicando lo que se prueba
  3. Aislar pruebas - sin dependencias entre pruebas
  4. Probar casos límite - entrada vacía, caracteres especiales, datos grandes
  5. Limpiar recursos en tearDown
  6. Mockear comandos externos - no pruebes curl, prueba tu lógica
  7. Probar códigos de salida no solo la salida

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

Jamie-BitFlight/agentskill-kaizen-meta-docs

Agentskill kaizen plugin documentation index. Load when needing to read about cross-platform notes, improvement plans, or DuckDB integration.

Jamie-BitFlight/bash-51-features

Bash 5.1 release features and improvements with practical examples. Use when working with Bash 5.1 features, epoch time variables, redirection enhancements, or when user asks about Bash 5.1 changes, new features, or version-specific capabilities.

Jamie-BitFlight/bash-52-features

Bash 5.2 release features and improvements with practical examples. Use when working with Bash 5.2 features, variable handling enhancements, readline improvements, or when user asks about Bash 5.2 changes, new features, or version-specific capabilities.

Jamie-BitFlight/bash-53-features

Bash 5.3 release features and improvements with practical examples. Use when working with Bash 5.3 features, new command substitution, GLOBSORT, loadable builtins, or when user asks about Bash 5.3 changes, new features, or version-specific capabilities.

Jamie-BitFlight/bash-development

This skill should be used when the user asks to "write a bash script", "create a shell script", "implement bash function", "parse arguments in bash", "handle errors in bash", or mentions bash development, shell scripting, script templates, or modern bash patterns.

Jamie-BitFlight/bash-lint

This skill should be used when the user asks to "lint bash script", "run shellcheck", "format shell script", "use shfmt", "fix shellcheck errors", or mentions shell script linting, formatting, code quality, or pre-commit hooks for bash.

Jamie-BitFlight/bash-logging

This skill should be used when the user asks to "add logging to bash script", "colorize output", "implement log levels", "CI/CD sections", "terminal colors in bash", or mentions logging functions, emoji output, collapsible CI sections, or shlocksmith.

Jamie-BitFlight/bash-portability

This skill should be used when the user asks about "POSIX compatibility", "portable shell scripts", "cross-shell compatibility", "bashisms", "shebang selection", or mentions writing scripts that work on different shells (bash, sh, dash, zsh) or different systems.

Jamie-BitFlight/brainstorming-skill

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or when users request help with ideation, marketing, and strategic planning. Explores user intent, requirements, and design before implementation using research-validated prompt patterns.

Jamie-BitFlight/clang-format

Configure clang-format code formatting. Use when: user mentions clang-format or .clang-format, analyzing code style/patterns, creating/modifying formatting config, troubleshooting formatting, brace styles/indentation/spacing/alignment/pointer alignment, or codifying conventions.

Jamie-BitFlight/commitlint

When setting up commit message validation for a project. When project has commitlint.config.js or .commitlintrc files. When configuring CI/CD to enforce commit format. When extracting commit rules for LLM prompt generation. When debugging commit message rejection errors.

Jamie-BitFlight/conventional-commits

When writing a git commit message. When task completes and changes need committing. When project uses semantic-release, commitizen, git-cliff. When choosing between feat/fix/chore/docs types. When indicating breaking changes. When generating changelogs from commit history.

Jamie-BitFlight/dasel-reference

Use when querying, modifying, or converting JSON, YAML, TOML, XML, CSV, HCL, or INI with dasel v3. Complete reference for selectors, functions, conditionals, variables, spread operator, type casting, and format-specific patterns.

Jamie-BitFlight/data-exploration

Use when exploring unknown structured data files with dasel v3 — discover schema, list keys, find nested values, sample arrays, identify data types across JSON, YAML, TOML, XML, CSV, HCL, INI formats

Jamie-BitFlight/data-transformation

Use when modifying, converting, or transforming structured data with dasel v3 — in-place mutations, format conversion, batch operations, array manipulation, object construction, and merge patterns across JSON, YAML, TOML, XML, CSV, HCL, INI

Jamie-BitFlight/delegate

Decompose substantive work into phases, dispatch each phase to a sub-agent, and adjudicate what comes back. Use whenever a request asks for implementation, investigation, a fix, a review, or any change to files — including small ones — and whenever you are about to read source or run a diagnostic yourself instead of handing it off. Also use when a report from a sub-agent needs judging, when a phase needs re-dispatching, or when a user names one instance of a pattern. Does not apply when your own prompt begins "Your ROLE_TYPE is sub-agent." — then follow references/sub-agent-contract.md instead.

Jamie-BitFlight/enterprise-hibernate-hbm

Dasel v3 query patterns for Hibernate .hbm.xml mapping files — entity-table binding, Java property-to-column extraction, one-to-many set/list/bag relationship tracing, many-to-one foreign key discovery, batch scanning across 60+ HBM files. Use when querying Hibernate ORM class mappings, extracting schema metadata from Java persistence layer, or auditing entity-column relationships in enterprise legacy codebases.

Jamie-BitFlight/enterprise-installanywhere

Dasel v3 query patterns for InstallAnywhere .iap_xml installer definitions — use when querying action sequences, discovering variables, resolving platform conditions, navigating panels, or comparing installer variants. Files are 2.5+ MB, 65,000+ lines — too large for context reads, requires structural dasel queries.

Jamie-BitFlight/enterprise-maven-pom

Dasel v3 selector patterns for Maven POM XML files — use when querying dependency versions, filtering by groupId or scope, extracting module hierarchy from parent POMs, or detecting version conflicts across enterprise multi-module Java projects. Load this skill when working with pom.xml files using dasel.

Jamie-BitFlight/enterprise-spring-xml

Dasel v3 selectors for Spring bean factory XML — use when querying any Spring ApplicationContext XML for bean discovery, dependency wiring, JMS destination mapping, property injection extraction, or cross-bean reference tracing. Load this skill before writing dasel selectors against Spring bean XML files (applicationContext.xml, *_beans.xml, spring-*.xml).

Skills relacionados