Communitygithub.com

Jamie-BitFlight/bash-testing

Esta skill deve ser usada quando o usuário pedir para "testar script bash", "escrever testes de shell", "usar shunit2", "usar shellspec", "criar suíte de testes para bash", ou mencionar testes unitários, frameworks de teste, mocking ou desenvolvimento orientado a testes para scripts shell.

O que é bash-testing?

Esta skill fornece um guia abrangente para testes de scripts shell em Bash, com foco em dois frameworks populares: shunit2 e shellspec. O shunit2 é um framework de estilo xUnit, simples e portátil, ideal para testes unitários de funções, enquanto o shellspec oferece uma abordagem BDD mais moderna, adequada para projetos completos. A skill detalha como instalar ambos os frameworks, estruturar testes, usar asserções e matchers, criar mocks de comandos externos e implementar padrões de teste comuns, como validação de códigos de saída, saída padrão (stdout) e erro (stderr), e uso de fixtures. Além disso, inclui boas práticas como isolar testes, limpar recursos e testar casos de borda. O conteúdo é apresentado em markdown com exemplos práticos de código, tornando fácil para desenvolvedores entenderem e aplicarem os conceitos imediatamente em seus projetos, independentemente de estarem usando shunit2 ou shellspec.

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

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Testes Bash

Frameworks e padrões de teste para scripts shell, com foco em shunit2 e shellspec.

Seleção de Framework

FrameworkPontos FortesMelhor Para
shunit2Estilo xUnit, simples, portátilTestes unitários, teste de funções
shellspecEstilo BDD, moderno, extensoEspecificações de comportamento, projetos completos

shunit2

Instalação

# Baixar diretamente
curl -L https://github.com/kward/shunit2/raw/master/shunit2 -o shunit2

# Ou via gerenciador de pacotes
apt install shunit2
brew install shunit2

Estrutura Básica de Teste

#!/usr/bin/env bash

# Incluir o script sendo testado
source ./my_script.sh

# Funções de teste começam com test
test_addition() {
    result=$(add 2 3)
    assertEquals "2 + 3 deve ser igual a 5" "5" "$result"
}

test_string_output() {
    result=$(greet "World")
    assertEquals "Hello, World" "$result"
}

test_file_creation() {
    create_temp_file
    assertTrue "O arquivo temporário deve existir" "[ -f /tmp/testfile ]"
}

test_exit_code() {
    validate_input "valid"
    assertEquals "Deve retornar 0 para entrada válida" 0 $?
}

# Setup e teardown
oneTimeSetUp() {
    # Executado uma vez antes de todos os testes
    export TEST_DIR=$(mktemp -d)
}

oneTimeTearDown() {
    # Executado uma vez após todos os testes
    rm -rf "$TEST_DIR"
}

setUp() {
    # Executado antes de cada teste
    cd "$TEST_DIR"
}

tearDown() {
    # Executado após cada teste
    rm -f "$TEST_DIR"/*
}

# Carregar shunit2
source shunit2

Asserções do shunit2

# Igualdade
assertEquals [mensagem] esperado atual
assertNotEquals [mensagem] inesperado atual

# Nulo/Vazio
assertNull [mensagem] valor
assertNotNull [mensagem] valor

# Booleano/Status
assertTrue [mensagem] condição
assertFalse [mensagem] condição

# Mesma referência (comparação de strings)
assertSame [mensagem] esperado atual
assertNotSame [mensagem] inesperado atual

# Contém (em string)
assertContains [mensagem] contêiner conteúdo

# Status de saída
assertEquals 0 $?

Testando Funções Isoladamente

Exemplos de código

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

source ./my_functions.sh

test_calculate_sum_empty() {
    result=$(calculate_sum)
    assertEquals "Soma vazia deve ser 0" "0" "$result"
}

test_calculate_sum_single() {
    result=$(calculate_sum 5)
    assertEquals "5" "$result"
}

test_calculate_sum_multiple() {
    result=$(calculate_sum 1 2 3 4 5)
    assertEquals "15" "$result"
}

test_validate_email_valid() {
    validate_email "[email protected]"
    assertTrue "Email válido deve passar" $?
}

test_validate_email_invalid() {
    validate_email "not-an-email"
    assertFalse "Email inválido deve falhar" $?
}

source shunit2

shellspec

Instalação

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

# Via Homebrew
brew install shellspec

# Via gerenciadores de pacotes
apt install shellspec

Estrutura de Diretórios

project/
├── lib/
│   └── functions.sh
├── spec/
│   ├── spec_helper.sh
│   ├── functions_spec.sh
│   └── support/
│       └── fixtures/
└── .shellspec

Configuração (.shellspec)

--require spec_helper
--format documentation
--color

Estrutura Básica de Especificação

Exemplos de código

Matchers do shellspec

# Matchers de saída
The output deve eq "correspondência exata"
The output deve include "parcial"
The output deve start with "prefixo"
The output deve end with "sufixo"
The output deve match pattern "*glob*"
The output deve be blank

# Matchers de status
The status deve be success    # saída 0
The status deve be failure    # saída não zero
The status deve eq 1          # código específico

# Matchers de variável
The variable VAR deve eq "valor"
The variable VAR deve be defined
The variable VAR deve be undefined

# Matchers de arquivo
The file "caminho" deve be exist
The file "caminho" deve be file
The file "caminho" deve be directory
The file "caminho" deve be readable

# Matchers de caminho
The path "arquivo.txt" deve be exist

Mocking no shellspec

Describe 'função de deploy'
  # Mock de comando externo
  curl() {
    echo "resposta mockada"
    return 0
  }

  It 'chama a API endpoint'
    When call deploy "servidor"
    The output deve include "resposta mockada"
  End
End

Describe 'operações de arquivo'
  # Mock com sobrescrita de função
  Mock rm
    echo "rm chamado com: $*"
  End

  It 'tenta remover o arquivo'
    When call cleanup_temp
    The output deve include "rm chamado com"
  End
End

Spec Helper

# spec/spec_helper.sh

# Carregar funções comuns
spec_helper_precheck() {
  minimum_version "0.28.0"
}

spec_helper_loaded() {
  # Configurar ambiente de teste
  export TEST_MODE=true
}

spec_helper_configure() {
  # Importar funções do projeto
  import 'lib/functions.sh'
}

Padrões de Teste

Testando Códigos de Saída

# shunit2
test_success_exit() {
    run_command "entrada_válida"
    assertEquals 0 $?
}

test_error_exit() {
    run_command "entrada_inválida"
    assertEquals 1 $?
}

# shellspec
It 'sai com 0 em caso de sucesso'
  When call run_command "entrada_válida"
  The status deve eq 0
End

Testando stdout e stderr

# shunit2
test_stdout() {
    result=$(my_function 2>/dev/null)
    assertEquals "saída esperada" "$result"
}

test_stderr() {
    error=$(my_function 2>&1 >/dev/null)
    assertContains "$error" "mensagem de erro"
}

# shellspec
It 'saída para stdout'
  When call my_function
  The stdout deve eq "saída esperada"
End

It 'saída de erro para stderr'
  When call my_function
  The stderr deve include "mensagem de erro"
End

Testando com Fixtures

# Configurar fixtures de teste
setUp() {
    TEST_DIR=$(mktemp -d)
    cat > "$TEST_DIR/config.json" <<EOF
{
    "key": "value"
}
EOF
}

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

test_config_parsing() {
    result=$(parse_config "$TEST_DIR/config.json")
    assertEquals "value" "$result"
}

Testando Funções Interativas

# Fornecer entrada via heredoc
test_interactive() {
    result=$(my_prompt <<EOF
sim
EOF
)
    assertEquals "confirmado" "$result"
}

# Ou usar printf
test_with_input() {
    result=$(printf 'sim\n' | my_prompt)
    assertEquals "confirmado" "$result"
}

Executando Testes

# shunit2
./test_script.sh

# shellspec
shellspec                    # Executar todas as especificações
shellspec spec/file_spec.sh  # Executar especificação específica
shellspec --format tap       # Saída TAP
shellspec --jobs 4           # Execução paralela

Melhores Práticas

  1. Uma asserção por teste quando prático
  2. Nomes de teste descritivos explicando o que é testado
  3. Isolar testes - sem dependências entre testes
  4. Testar casos de borda - entrada vazia, caracteres especiais, dados grandes
  5. Limpar recursos no tearDown
  6. Mockar comandos externos - não teste curl, teste sua lógica
  7. Testar códigos de saída não apenas a saída

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

Habilidades Relacionadas