ASD

Bats Testing Patterns

Domina Bats (Bash Automated Testing System) para probar exhaustivamente scripts de shell, útil en TDD y pipelines CI/CD.

Estrellas
38.8k

en todo el repo

Actividad
47

0–100, la ruta de este skill

Actualizado
hace 2 meses

último commit aquí

Commits
1

últimos 90 días

Contexto
1.3k tok

50 tok en reposo

Paquete
2 archivos

12 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add wshobson/agents --skill bats-testing-patterns --agent claude-code

Se instala solo en este repositorio.

Este skill reads environment config.

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)

Úsalo cuando

  • 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

No lo uses cuando

    Qué lo activa

    Di cualquiera de estas frases y el agente debería cargar este skill.

    • 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

    SKILL.md

    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

    #!/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

    #!/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

    #!/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

    #!/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

    #!/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

    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

    .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

    Reproducido de wshobson/agents bajo licencia MIT. Leer esta página en markdown.

    Archivos

    2 archivos en el paquete. Solo se lee SKILL.md al activarse — las referencias se cargan si el skill decide que las necesita.

    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_DIRNAMETEST_DIR

    Detalles

    Creador
    wshobson
    Categoría
    Testing y QA
    Licencia
    MIT
    Recursos incluidos
    referencias
    Repositorio
    wshobson/agents
    Código fuente
    Ver SKILL.md

    Etiquetas

    Más de wshobson/agents

    Este repo incluye 180 skills. Si instalas uno, normalmente ya tienes los demás.

    Úsalo al seleccionar y colocar iconos, imágenes, SVGs, diagramas o infografías de apoyo aprobados en un PPTX editable.

    Costo de contexto al activarse
    344 tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 26 días
    documentos

    Ú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.

    Costo de contexto al activarse
    1.3k tok
    Tamaño del paquete
    10 archivos
    Última actualización
    el mes pasado
    herramientas desarrollo

    Úsalo al redactar o reparar una especificación JSON con coordenadas explícitas para un PPTX editable.

    Costo de contexto al activarse
    489 tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 26 días
    documentos

    Úsalo para validar o reparar un PPTX editable en cuanto a geometría, accesibilidad, editabilidad nativa, linaje de fuente e integridad del paquete OOXML.

    Costo de contexto al activarse
    409 tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 26 días
    documentos

    Úsalo para analizar un PPTX de referencia en modo solo lectura: estructura, tema, tipografía, ritmo de layout, diagnósticos, catálogos de plantillas derivados o inspección segura del paquete OOXML.

    Costo de contexto al activarse
    689 tok
    Tamaño del paquete
    8 archivos
    Última actualización
    hace 26 días
    documentos

    Úsalo al preparar la narrativa, las fuentes y el contexto de diseño para un nuevo deck PPTX editable.

    Costo de contexto al activarse
    415 tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 26 días
    documentos

    Skills relacionados

    Testea contratos inteligentes de forma exhaustiva con Hardhat y Foundry: tests unitarios, de integración y forking de mainnet.

    Costo de contexto al activarse
    2k tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 2 meses
    testing qa

    Realiza auditorías de accesibilidad WCAG 2.2 con pruebas automatizadas, verificación manual y guía de remediación. Útil para auditar sitios, corregir violaciones y aplicar patrones de diseño accesible.

    Costo de contexto al activarse
    628 tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 2 meses
    testing qa

    Prueba workflows de Temporal con pytest, time-skipping y estrategias de mocking: testing unitario, de integración, de replay y configuración de desarrollo local.

    Costo de contexto al activarse
    1.2k tok
    Tamaño del paquete
    5 archivos
    Última actualización
    hace 3 meses
    testing qa