Communitygithub.com

padrões-de-teste-em-go

Padrões de teste em Go incluindo testes guiados por tabela, subtestes, benchmarks, fuzzing e cobertura de teste. Segue a metodologia TDD com práticas idiomáticas de Go. Use ao escrever testes Go — casos guiados por tabela, subtestes, benchmarks, fuzzing ou cobertura.

O que é padrões-de-teste-em-go?

Esta skill oferece um guia completo sobre padrões de teste em Go, cobrindo desde os fundamentos do TDD até técnicas avançadas como testes guiados por tabela, subtestes, benchmarks, fuzzing e análise de cobertura. É ideal para desenvolvedores que desejam escrever testes confiáveis e de fácil manutenção seguindo as melhores práticas da linguagem Go. A skill detalha o ciclo TDD (RED-GREEN-REFACTOR) com exemplos práticos de código, mostrando como implementar cada etapa. Inclui padrões para testes com casos de erro, helpers de teste, arquivos golden (para comparação de saída esperada), mocks baseados em interfaces e testes de handlers HTTP. Suporta também testes de desempenho com benchmarks e testes de fuzzing (a partir do Go 1.18), com exemplos de como executá-los via linha de comando. A cobertura de teste é abordada com comandos para geração de perfis e visualização no navegador, além de metas de cobertura sugeridas para diferentes tipos de código. Esta skill é compatível com qualquer ambiente de desenvolvimento Go e agentes de IA que necessitem de diretrizes claras e idiomáticas para implementar testes em projetos Go.

Funciona com~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/golang-testing

Perguntar na sua IA favorita

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

Documentação

Padrões de Teste em Go

Padrões abrangentes de teste em Go para escrever testes confiáveis e de fácil manutenção seguindo a metodologia TDD.

Quando Ativar

  • Escrevendo novas funções ou métodos em Go
  • Adicionando cobertura de teste a código existente
  • Criando benchmarks para código crítico de desempenho
  • Implementando testes de fuzzing para validação de entrada
  • Seguindo o fluxo de trabalho TDD em projetos Go

Fluxo de Trabalho TDD para Go

O Ciclo RED-GREEN-REFACTOR

RED     → Escreva um teste com falha primeiro
GREEN   → Escreva o mínimo de código para passar no teste
REFACTOR → Melhore o código mantendo os testes verdes
REPEAT  → Continue com o próximo requisito

TDD Passo a Passo em Go

// Passo 1: Defina a interface/assinatura
// calculator.go
package calculator

func Add(a, b int) int {
    panic("não implementado") // Placeholder
}

// Passo 2: Escreva o teste com falha (RED)
// calculator_test.go
package calculator

import "testing"

func TestAdd(t *testing.T) {
    got := Add(2, 3)
    want := 5
    if got != want {
        t.Errorf("Add(2, 3) = %d; want %d", got, want)
    }
}

// Passo 3: Execute o teste - verifique FALHA
// $ go test
// --- FAIL: TestAdd (0.00s)
// panic: não implementado

// Passo 4: Implemente o código mínimo (GREEN)
func Add(a, b int) int {
    return a + b
}

// Passo 5: Execute o teste - verifique PASS
// $ go test
// PASS

// Passo 6: Refatore se necessário, verifique se os testes ainda passam

Testes Guiados por Tabela

O padrão padrão para testes em Go. Permite cobertura abrangente com código mínimo.

func TestAdd(t *testing.T) {
    tests := []struct {
        name     string
        a, b     int
        expected int
    }{
        {"números positivos", 2, 3, 5},
        {"números negativos", -1, -2, -3},
        {"valores zero", 0, 0, 0},
        {"sinais mistos", -1, 1, 0},
        {"números grandes", 1000000, 2000000, 3000000},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got := Add(tt.a, tt.b)
            if got != tt.expected {
                t.Errorf("Add(%d, %d) = %d; want %d",
                    tt.a, tt.b, got, tt.expected)
            }
        })
    }
}

Testes Guiados por Tabela com Casos de Erro

func TestParseConfig(t *testing.T) {
    tests := []struct {
        name    string
        input   string
        want    *Config
        wantErr bool
    }{
        {
            name:  "config válido",
            input: `{"host": "localhost", "port": 8080}`,
            want:  &Config{Host: "localhost", Port: 8080},
        },
        {
            name:    "JSON inválido",
            input:   `{inválido}`,
            wantErr: true,
        },
        {
            name:    "entrada vazia",
            input:   "",
            wantErr: true,
        },
        {
            name:  "config mínimo",
            input: `{}`,
            want:  &Config{}, // Configuração de valor zero
        },
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := ParseConfig(tt.input)

            if tt.wantErr {
                if err == nil {
                    t.Error("erro esperado, obteve nil")
                }
                return
            }

            if err != nil {
                t.Fatalf("erro inesperado: %v", err)
            }

            if !reflect.DeepEqual(got, tt.want) {
                t.Errorf("got %+v; want %+v", got, tt.want)
            }
        })
    }
}

Subtestes e Sub-benchmarks

Organizando Testes Relacionados

func TestUser(t *testing.T) {
    // Configuração compartilhada por todos os subtestes
    db := setupTestDB(t)

    t.Run("Create", func(t *testing.T) {
        user := &User{Name: "Alice"}
        err := db.CreateUser(user)
        if err != nil {
            t.Fatalf("CreateUser falhou: %v", err)
        }
        if user.ID == "" {
            t.Error("ID do usuário esperado")
        }
    })

    t.Run("Get", func(t *testing.T) {
        user, err := db.GetUser("alice-id")
        if err != nil {
            t.Fatalf("GetUser falhou: %v", err)
        }
        if user.Name != "Alice" {
            t.Errorf("obteve nome %q; esperado %q", user.Name, "Alice")
        }
    })

    t.Run("Update", func(t *testing.T) {
        // ...
    })

    t.Run("Delete", func(t *testing.T) {
        // ...
    })
}

Subtestes Paralelos

func TestParallel(t *testing.T) {
    tests := []struct {
        name  string
        input string
    }{
        {"caso1", "entrada1"},
        {"caso2", "entrada2"},
        {"caso3", "entrada3"},
    }

    for _, tt := range tests {
        tt := tt // Capturar variável de iteração
        t.Run(tt.name, func(t *testing.T) {
            t.Parallel() // Executar subtestes em paralelo
            result := Process(tt.input)
            // asserções...
            _ = result
        })
    }
}

Helpers de Teste

Funções Helper

func setupTestDB(t *testing.T) *sql.DB {
    t.Helper() // Marca esta como uma função helper

    db, err := sql.Open("sqlite3", ":memory:")
    if err != nil {
        t.Fatalf("falha ao abrir banco de dados: %v", err)
    }

    // Limpeza quando o teste terminar
    t.Cleanup(func() {
        db.Close()
    })

    // Executar migrações
    if _, err := db.Exec(schema); err != nil {
        t.Fatalf("falha ao criar esquema: %v", err)
    }

    return db
}

func assertNoError(t *testing.T, err error) {
    t.Helper()
    if err != nil {
        t.Fatalf("erro inesperado: %v", err)
    }
}

func assertEqual[T comparable](t *testing.T, got, want T) {
    t.Helper()
    if got != want {
        t.Errorf("got %v; want %v", got, want)
    }
}

Arquivos e Diretórios Temporários

func TestFileProcessing(t *testing.T) {
    // Criar diretório temporário - limpo automaticamente
    tmpDir := t.TempDir()

    // Criar arquivo de teste
    testFile := filepath.Join(tmpDir, "test.txt")
    err := os.WriteFile(testFile, []byte("conteúdo de teste"), 0644)
    if err != nil {
        t.Fatalf("falha ao criar arquivo de teste: %v", err)
    }

    // Executar teste
    result, err := ProcessFile(testFile)
    if err != nil {
        t.Fatalf("ProcessFile falhou: %v", err)
    }

    // Asserção...
    _ = result
}

Arquivos Golden

Testes contra arquivos de saída esperados armazenados em testdata/.

var update = flag.Bool("update", false, "atualizar arquivos golden")

func TestRender(t *testing.T) {
    tests := []struct {
        name  string
        input Template
    }{
        {"simples", Template{Name: "teste"}},
        {"complexo", Template{Name: "teste", Items: []string{"a", "b"}}},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got := Render(tt.input)

            golden := filepath.Join("testdata", tt.name+".golden")

            if *update {
                // Atualizar arquivo golden: go test -update
                err := os.WriteFile(golden, got, 0644)
                if err != nil {
                    t.Fatalf("falha ao atualizar arquivo golden: %v", err)
                }
            }

            want, err := os.ReadFile(golden)
            if err != nil {
                t.Fatalf("falha ao ler arquivo golden: %v", err)
            }

            if !bytes.Equal(got, want) {
                t.Errorf("incompatibilidade de saída:\ngot:\n%s\nwant:\n%s", got, want)
            }
        })
    }
}

Mocking com Interfaces

Mocking Baseado em Interface

// Definir interface para dependências
type UserRepository interface {
    GetUser(id string) (*User, error)
    SaveUser(user *User) error
}

// Implementação de produção
type PostgresUserRepository struct {
    db *sql.DB
}

func (r *PostgresUserRepository) GetUser(id string) (*User, error) {
    // Consulta real ao banco de dados
}

// Implementação Mock para testes
type MockUserRepository struct {
    GetUserFunc  func(id string) (*User, error)
    SaveUserFunc func(user *User) error
}

func (m *MockUserRepository) GetUser(id string) (*User, error) {
    return m.GetUserFunc(id)
}

func (m *MockUserRepository) SaveUser(user *User) error {
    return m.SaveUserFunc(user)
}

// Teste usando mock
func TestUserService(t *testing.T) {
    mock := &MockUserRepository{
        GetUserFunc: func(id string) (*User, error) {
            if id == "123" {
                return &User{ID: "123", Name: "Alice"}, nil
            }
            return nil, ErrNotFound
        },
    }

    service := NewUserService(mock)

    user, err := service.GetUserProfile("123")
    if err != nil {
        t.Fatalf("erro inesperado: %v", err)
    }
    if user.Name != "Alice" {
        t.Errorf("obteve nome %q; esperado %q", user.Name, "Alice")
    }
}

Benchmarks

Benchmarks Básicos

func BenchmarkProcess(b *testing.B) {
    data := generateTestData(1000)
    b.ResetTimer() // Não conta o tempo de configuração

    for i := 0; i < b.N; i++ {
        Process(data)
    }
}

// Execute: go test -bench=BenchmarkProcess -benchmem
// Saída: BenchmarkProcess-8   10000   105234 ns/op   4096 B/op   10 allocs/op

Benchmark com Diferentes Tamanhos

func BenchmarkSort(b *testing.B) {
    sizes := []int{100, 1000, 10000, 100000}

    for _, size := range sizes {
        b.Run(fmt.Sprintf("tamanho=%d", size), func(b *testing.B) {
            data := generateRandomSlice(size)
            b.ResetTimer()

            for i := 0; i < b.N; i++ {
                // Fazer uma cópia para evitar ordenar dados já ordenados
                tmp := make([]int, len(data))
                copy(tmp, data)
                sort.Ints(tmp)
            }
        })
    }
}

Benchmarks de Alocação de Memória

func BenchmarkStringConcat(b *testing.B) {
    parts := []string{"hello", "world", "foo", "bar", "baz"}

    b.Run("mais", func(b *testing.B) {
        for i := 0; i < b.N; i++ {
            var s string
            for _, p := range parts {
                s += p
            }
            _ = s
        }
    })

    b.Run("builder", func(b *testing.B) {
        for i := 0; i < b.N; i++ {
            var sb strings.Builder
            for _, p := range parts {
                sb.WriteString(p)
            }
            _ = sb.String()
        }
    })

    b.Run("join", func(b *testing.B) {
        for i := 0; i < b.N; i++ {
            _ = strings.Join(parts, "")
        }
    })
}

Fuzzing (Go 1.18+)

Teste de Fuzzing Básico

func FuzzParseJSON(f *testing.F) {
    // Adicionar corpus de sementes
    f.Add(`{"name": "teste"}`)
    f.Add(`{"count": 123}`)
    f.Add(`[]`)
    f.Add(`""`)

    f.Fuzz(func(t *testing.T, input string) {
        var result map[string]interface{}
        err := json.Unmarshal([]byte(input), &result)

        if err != nil {
            // JSON inválido é esperado para entrada aleatória
            return
        }

        // Se o parsing foi bem-sucedido, a re-codificação deve funcionar
        _, err = json.Marshal(result)
        if err != nil {
            t.Errorf("Marshal falhou após Unmarshal bem-sucedido: %v", err)
        }
    })
}

// Execute: go test -fuzz=FuzzParseJSON -fuzztime=30s

Teste de Fuzzing com Múltiplas Entradas

func FuzzCompare(f *testing.F) {
    f.Add("hello", "world")
    f.Add("", "")
    f.Add("abc", "abc")

    f.Fuzz(func(t *testing.T, a, b string) {
        result := Compare(a, b)

        // Propriedade: Compare(a, a) deve sempre ser igual a 0
        if a == b && result != 0 {
            t.Errorf("Compare(%q, %q) = %d; want 0", a, b, result)
        }

        // Propriedade: Compare(a, b) e Compare(b, a) devem ter sinais opostos
        reverse := Compare(b, a)
        if (result > 0 && reverse >= 0) || (result < 0 && reverse <= 0) {
            if result != 0 || reverse != 0 {
                t.Errorf("Compare(%q, %q) = %d, Compare(%q, %q) = %d; inconsistente",
                    a, b, result, b, a, reverse)
            }
        }
    })
}

Cobertura de Teste

Executando Cobertura

# Cobertura básica
go test -cover ./...

# Gerar perfil de cobertura
go test -coverprofile=coverage.out ./...

# Visualizar cobertura no navegador
go tool cover -html=coverage.out

# Visualizar cobertura por função
go tool cover -func=coverage.out

# Cobertura com detecção de condição de corrida
go test -race -coverprofile=coverage.out ./...

Metas de Cobertura

Tipo de CódigoMeta
Lógica de negócios crítica100%
APIs públicas90%+
Código geral80%+
Código geradoExcluir

Excluindo Código Gerado da Cobertura

//go:generate mockgen -source=interface.go -destination=mock_interface.go

// No perfil de cobertura, exclua com tags de compilação:
// go test -cover -tags=!generate ./...

Teste de Handler HTTP

func TestHealthHandler(t *testing.T) {
    // Criar requisição
    req := httptest.NewRequest(http.MethodGet, "/health", nil)
    w := httptest.NewRecorder()

    // Chamar handler
    HealthHandler(w, req)

    // Verificar resposta
    resp := w.Result()
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        t.Errorf("obteve status %d; esperado %d", resp.StatusCode, http.StatusOK)
    }

    body, _ := io.ReadAll(resp.Body)
    if string(body) != "OK" {
        t.Errorf("obteve corpo %q; esperado %q", body, "OK")
    }
}

func TestAPIHandler(t *testing.T) {
    tests := []struct {
        name       string
        method     string
        path       string
        body       string
        wantStatus int
        wantBody   string
    }{
        {
            name:       "obter usuário",
            method:     http.MethodGet,
            path:       "/users/123",
            wantStatus: http.StatusOK,
            wantBody:   `{"id":"123","name":"Alice"}`,
        },
        {
            name:       "não encontrado",
            method:     http.MethodGet,
            path:       "/users/999",
            wantStatus: http.StatusNotFound,
        },
        {
            name:       "criar usuário",
            method:     http.MethodPost,
            path:       "/users",
            body:       `{"name":"Bob"}`,
            wantStatus: http.StatusCreated,
        },
    }

    handler := NewAPIHandler()

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            // Construir requisição
            var req *http.Request
            if tt.body != "" {
                req = httptest.NewRequest(tt.method, tt.path, strings.NewReader(tt.body))
                req.Header.Set("Content-Type", "application/json")
            } else {
                req = httptest.NewRequest(tt.method, tt.path, nil)
            }

            w := httptest.NewRecorder()
            handler.ServeHTTP(w, req)

            resp := w.Result()
            defer resp.Body.Close()

            // Verificar status code
            if resp.StatusCode != tt.wantStatus {
                t.Errorf("obteve status %d; esperado %d", resp.StatusCode, tt.wantStatus)
            }

            // Verificar corpo se esperado
            if tt.wantBody != "" {
                body, _ := io.ReadAll(resp.Body)
                if string(body) != tt.wantBody {
                    t.Errorf("obteve corpo %q; esperado %q", body, tt.wantBody)
                }
            }
        })
    }
}

Individual skills in this repo

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

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

Habilidades Relacionadas