Communitygithub.com

golang-testing

Patrones de testing en Go que incluyen pruebas basadas en tablas, subpruebas, benchmarks, fuzzing y cobertura de código. Sigue la metodología TDD con prácticas idiomáticas de Go. Úsalo al escribir tests en Go: casos basados en tablas, subpruebas, benchmarks, fuzzing o cobertura.

¿Qué es golang-testing?

Este skill proporciona una guía completa sobre patrones de testing en Go, basados en la metodología TDD (Test-Driven Development). Cubre desde el ciclo básico RED-GREEN-REFACTOR hasta técnicas avanzadas como pruebas basadas en tablas, subpruebas paralelas, helpers de test con limpieza automática, archivos golden, mocking con interfaces, benchmarks con diferentes tamaños y asignación de memoria, y fuzzing (Go 1.18+). También incluye pautas sobre cómo medir y excluir la cobertura de código. Es adecuado para cualquier plataforma de agente de IA, como Cursor o Codex, que necesite generar o documentar tests en Go de manera idiomática y confiable. El markdown incluye ejemplos de código completos, comandos de terminal y tablas de referencia, lo que facilita su uso directo por parte de un agente para escribir, refactorizar o analizar pruebas en proyectos Go.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/golang-testing

Preguntar en tu IA favorita

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

Documentación

Patrones de Testing en Go

Patrones completos de testing en Go para escribir pruebas confiables y mantenibles siguiendo la metodología TDD.

Cuándo Activar

  • Al escribir nuevas funciones o métodos en Go
  • Al agregar cobertura de prueba a código existente
  • Al crear benchmarks para código crítico en rendimiento
  • Al implementar pruebas de fuzzing para validación de entrada
  • Al seguir el flujo de trabajo TDD en proyectos Go

Flujo de Trabajo TDD para Go

El Ciclo RED-GREEN-REFACTOR

RED     → Escribe una prueba que falle primero
GREEN   → Escribe el código mínimo para que pase la prueba
REFACTOR → Mejora el código mientras las pruebas sigan pasando
REPEAT  → Continúa con el siguiente requisito

TDD Paso a Paso en Go

// Paso 1: Definir la interfaz/firma
// calculator.go
package calculator

func Add(a, b int) int {
    panic("no implementado") // Placeholder
}

// Paso 2: Escribir prueba fallida (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)
    }
}

// Paso 3: Ejecutar prueba - verificar FALLO
// $ go test
// --- FAIL: TestAdd (0.00s)
// panic: no implementado

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

// Paso 5: Ejecutar prueba - verificar ÉXITO
// $ go test
// PASS

// Paso 6: Refactorizar si es necesario, verificar que las pruebas sigan pasando

Pruebas Basadas en Tablas

El patrón estándar para pruebas en Go. Permite una cobertura completa con 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 cero", 0, 0, 0},
        {"signos mixtos", -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)
            }
        })
    }
}

Pruebas Basadas en Tablas con Casos de Error

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:   `{invalid}`,
            wantErr: true,
        },
        {
            name:    "entrada vacía",
            input:   "",
            wantErr: true,
        },
        {
            name:  "config mínimo",
            input: `{}`,
            want:  &Config{}, // Config con valor cero
        },
    }

    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("se esperaba un error, se obtuvo nil")
                }
                return
            }

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

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

Subpruebas y Sub-benchmarks

Organizando Pruebas Relacionadas

func TestUser(t *testing.T) {
    // Configuración compartida por todas las subpruebas
    db := setupTestDB(t)

    t.Run("Create", func(t *testing.T) {
        user := &User{Name: "Alice"}
        err := db.CreateUser(user)
        if err != nil {
            t.Fatalf("CreateUser falló: %v", err)
        }
        if user.ID == "" {
            t.Error("se esperaba que el ID de usuario estuviera configurado")
        }
    })

    t.Run("Get", func(t *testing.T) {
        user, err := db.GetUser("alice-id")
        if err != nil {
            t.Fatalf("GetUser falló: %v", err)
        }
        if user.Name != "Alice" {
            t.Errorf("got name %q; want %q", user.Name, "Alice")
        }
    })

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

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

Subpruebas Paralelas

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

    for _, tt := range tests {
        tt := tt // Capturar variable de rango
        t.Run(tt.name, func(t *testing.T) {
            t.Parallel() // Ejecutar subpruebas en paralelo
            result := Process(tt.input)
            // aserciones...
            _ = result
        })
    }
}

Helpers de Prueba

Funciones Helper

func setupTestDB(t *testing.T) *sql.DB {
    t.Helper() // Marca esto como función helper

    db, err := sql.Open("sqlite3", ":memory:")
    if err != nil {
        t.Fatalf("falló al abrir la base de datos: %v", err)
    }

    // Limpieza cuando la prueba termine
    t.Cleanup(func() {
        db.Close()
    })

    // Ejecutar migraciones
    if _, err := db.Exec(schema); err != nil {
        t.Fatalf("falló al crear el esquema: %v", err)
    }

    return db
}

func assertNoError(t *testing.T, err error) {
    t.Helper()
    if err != nil {
        t.Fatalf("error 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)
    }
}

Archivos y Directorios Temporales

func TestFileProcessing(t *testing.T) {
    // Crear directorio temporal - se limpia automáticamente
    tmpDir := t.TempDir()

    // Crear archivo de prueba
    testFile := filepath.Join(tmpDir, "test.txt")
    err := os.WriteFile(testFile, []byte("contenido de prueba"), 0644)
    if err != nil {
        t.Fatalf("falló al crear archivo de prueba: %v", err)
    }

    // Ejecutar prueba
    result, err := ProcessFile(testFile)
    if err != nil {
        t.Fatalf("ProcessFile falló: %v", err)
    }

    // Afirmar...
    _ = result
}

Archivos Golden

Pruebas contra archivos de salida esperados almacenados en testdata/.

var update = flag.Bool("update", false, "actualizar archivos golden")

func TestRender(t *testing.T) {
    tests := []struct {
        name  string
        input Template
    }{
        {"simple", Template{Name: "prueba"}},
        {"complejo", Template{Name: "prueba", 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 {
                // Actualizar archivo golden: go test -update
                err := os.WriteFile(golden, got, 0644)
                if err != nil {
                    t.Fatalf("falló al actualizar archivo golden: %v", err)
                }
            }

            want, err := os.ReadFile(golden)
            if err != nil {
                t.Fatalf("falló al leer archivo golden: %v", err)
            }

            if !bytes.Equal(got, want) {
                t.Errorf("discrepancia en salida:\ngot:\n%s\nwant:\n%s", got, want)
            }
        })
    }
}

Mocking con Interfaces

Mocking Basado en Interfaces

// Definir interfaz para dependencias
type UserRepository interface {
    GetUser(id string) (*User, error)
    SaveUser(user *User) error
}

// Implementación en producción
type PostgresUserRepository struct {
    db *sql.DB
}

func (r *PostgresUserRepository) GetUser(id string) (*User, error) {
    // Consulta real a la base de datos
}

// Implementación Mock para pruebas
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)
}

// Prueba 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("error inesperado: %v", err)
    }
    if user.Name != "Alice" {
        t.Errorf("got name %q; want %q", user.Name, "Alice")
    }
}

Benchmarks

Benchmarks Básicos

func BenchmarkProcess(b *testing.B) {
    data := generateTestData(1000)
    b.ResetTimer() // No contar el tiempo de configuración

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

// Ejecutar: go test -bench=BenchmarkProcess -benchmem
// Salida: BenchmarkProcess-8   10000   105234 ns/op   4096 B/op   10 allocs/op

Benchmark con Diferentes Tamaños

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

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

            for i := 0; i < b.N; i++ {
                // Hacer una copia para no ordenar datos ya ordenados
                tmp := make([]int, len(data))
                copy(tmp, data)
                sort.Ints(tmp)
            }
        })
    }
}

Benchmarks de Asignación de Memoria

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

    b.Run("plus", 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+)

Prueba de Fuzzing Básica

func FuzzParseJSON(f *testing.F) {
    // Agregar semillas al corpus
    f.Add(`{"name": "test"}`)
    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 {
            // Se espera JSON inválido para entrada aleatoria
            return
        }

        // Si el análisis tuvo éxito, la re-codificación debería funcionar
        _, err = json.Marshal(result)
        if err != nil {
            t.Errorf("Marshal falló después de Unmarshal exitoso: %v", err)
        }
    })
}

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

Prueba de Fuzzing con Múltiples 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)

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

        // Propiedad: Compare(a, b) y Compare(b, a) deben tener signos opuestos
        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 Prueba

Ejecutar Cobertura

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

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

# Ver cobertura en el navegador
go tool cover -html=coverage.out

# Ver cobertura por función
go tool cover -func=coverage.out

# Cobertura con detección de carrera
go test -race -coverprofile=coverage.out ./...

Objetivos de Cobertura

Tipo de CódigoObjetivo
Lógica de negocio crítica100%
APIs públicas90%+
Código general80%+
Código generadoExcluir

Excluir Código Generado de la Cobertura

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

// En el perfil de cobertura, excluir con etiquetas de compilación:
// go test -cover -tags=!generate ./...

Pruebas de Manejadores HTTP

func TestHealthHandler(t *testing.T) {
    // Crear solicitud
    req := httptest.NewRequest(http.MethodGet, "/health", nil)
    w := httptest.NewRecorder()

    // Llamar al manejador
    HealthHandler(w, req)

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

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

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

func TestAPIHandler(t *testing.T) {
    tests := []struct {
        name       string
        method     string
        path       string
        body       string
        wantStatus int
        wantBody   string
    }{
        {
            name:       "obtener usuario",
            method:     http.MethodGet,
            path:       "/users/123",
            wantStatus: http.StatusOK,
            wantBody:   `{"id":"123","name":"Alice"}`,
        },
        {
            name:       "no encontrado",
            method:     http.MethodGet,
            path:       "/users/999",
            wantStatus: http.StatusNotFound,
        },
        {
            name:       "crear usuario",
            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) {
            var bodyReader io.Reader
            if tt.body != "" {
                bodyReader = strings.NewReader(tt.body)
            }

            req := httptest.NewRequest(tt.method, tt.path, bodyReader)
            w := httptest.NewRecorder()
            handler.ServeHTTP(w, req)

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

            if resp.StatusCode != tt.wantStatus {
                t.Errorf("got status %d; want %d", resp.StatusCode, tt.wantStatus)
            }

            if tt.wantBody != "" {
                body, _ := io.ReadAll(resp.Body)
                if string(body) != tt.wantBody {
                    t.Errorf("got body %q; want %q", body, tt.wantBody)
                }
            }
        })
    }
}

Mejores Prácticas

  1. Usa t.Helper() en funciones auxiliares de prueba para que los informes de errores muestren la línea de llamada correcta.
  2. Usa t.Cleanup() para liberar recursos, en lugar de diferir en el ámbito de la función de prueba.
  3. Nombra subtests de forma descriptiva para obtener resultados de prueba claros.
  4. Usa t.TempDir() para archivos temporales; Go los limpia automáticamente.
  5. Evita comparaciones frágiles entre cadenas; usa reflect.DeepEqual para estructuras o tipos de datos complejos.
  6. No uses t.Error y t.Fatal indistintamente: t.Error marca la prueba como fallida pero continúa, t.Fatal la detiene.
  7. Mantén las pruebas independientes: no compartas estado mutable entre pruebas a menos que esté claramente documentado.
  8. Usa la función t.Run para agrupar subpruebas; permite una ejecución selectiva y una salida más limpia.
  9. Captura variables de rango en pruebas paralelas para evitar errores de referencia.
  10. Usa archivos golden cuando la salida esperada sea extensa o compleja.

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/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

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.

Skills relacionados