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 pruebas en Go: casos basados en tablas, subpruebas, benchmarks, fuzzing o cobertura.

¿Qué es golang-testing?

Este skill proporciona una guía completa sobre los patrones de testing en Go, diseñada para seguir la metodología TDD (Desarrollo Guiado por Pruebas) con prácticas idiomáticas del lenguaje. Incluye plantillas y ejemplos detallados para pruebas basadas en tablas (table-driven tests), subpruebas, helpers de prueba, archivos golden, mocking con interfaces, benchmarks, fuzzing y pruebas de handlers HTTP. Es útil para desarrolladores que trabajan con Go y desean escribir pruebas confiables, mantenibles y eficientes. El skill se activa al escribir nuevas funciones, agregar cobertura, crear benchmarks o implementar fuzzing. Utiliza el ciclo RED-GREEN-REFACTOR y proporciona ejemplos de código listos para usar, incluyendo cobertura con perfiles, exclusión de código generado y ejecución paralela de pruebas. Está pensado para entornos de desarrollo donde se usa Go standard tooling, como `go test`, `-bench`, `-fuzz`, y herramientas de cobertura.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/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 Activarlo

  • Escribir nuevas funciones o métodos en Go
  • Agregar cobertura de pruebas a código existente
  • Crear benchmarks para código crítico en rendimiento
  • Implementar pruebas de fuzzing para validación de entrada
  • Seguir el flujo de trabajo TDD en proyectos Go

Flujo de Trabajo TDD para Go

El Ciclo RED-GREEN-REFACTOR

RED     → Escribir una prueba que falle primero
GREEN   → Escribir el código mínimo para pasar la prueba
REFACTOR → Mejorar el código mientras las pruebas sigan pasando
REPEAT  → Continuar 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("not implemented") // Marcador de posición
}

// 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: not implemented

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

// Paso 5: Ejecutar prueba - verificar PASO
// $ 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
    }{
        {"positive numbers", 2, 3, 5},
        {"negative numbers", -1, -2, -3},
        {"zero values", 0, 0, 0},
        {"mixed signs", -1, 1, 0},
        {"large numbers", 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:  "valid config",
            input: `{"host": "localhost", "port": 8080}`,
            want:  &Config{Host: "localhost", Port: 8080},
        },
        {
            name:    "invalid JSON",
            input:   `{invalid}`,
            wantErr: true,
        },
        {
            name:    "empty input",
            input:   "",
            wantErr: true,
        },
        {
            name:  "minimal config",
            input: `{}`,
            want:  &Config{}, // Configuración 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("expected error, got nil")
                }
                return
            }

            if err != nil {
                t.Fatalf("unexpected error: %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 failed: %v", err)
        }
        if user.ID == "" {
            t.Error("expected user ID to be set")
        }
    })

    t.Run("Get", func(t *testing.T) {
        user, err := db.GetUser("alice-id")
        if err != nil {
            t.Fatalf("GetUser failed: %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 en Paralelo

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

    for _, tt := range tests {
        tt := tt // Capturar la variable de rango
        t.Run(tt.name, func(t *testing.T) {
            t.Parallel() // Ejecutar subpruebas en paralelo
            result := Process(tt.input)
            // afirmaciones...
            _ = 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("failed to open database: %v", err)
    }

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

    // Ejecutar migraciones
    if _, err := db.Exec(schema); err != nil {
        t.Fatalf("failed to create schema: %v", err)
    }

    return db
}

func assertNoError(t *testing.T, err error) {
    t.Helper()
    if err != nil {
        t.Fatalf("unexpected error: %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("test content"), 0644)
    if err != nil {
        t.Fatalf("failed to create test file: %v", err)
    }

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

    // Afirmar...
    _ = result
}

Archivos Golden

Pruebas contra archivos de salida esperados almacenados en testdata/.

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

func TestRender(t *testing.T) {
    tests := []struct {
        name  string
        input Template
    }{
        {"simple", Template{Name: "test"}},
        {"complex", Template{Name: "test", 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("failed to update golden file: %v", err)
                }
            }

            want, err := os.ReadFile(golden)
            if err != nil {
                t.Fatalf("failed to read golden file: %v", err)
            }

            if !bytes.Equal(got, want) {
                t.Errorf("output mismatch:\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("unexpected error: %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 evitar 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 {
            // JSON inválido es esperado para entrada aleatoria
            return
        }

        // Si el análisis tuvo éxito, la recodificación debería funcionar
        _, err = json.Marshal(result)
        if err != nil {
            t.Errorf("Marshal failed after successful Unmarshal: %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 debería ser 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; inconsistent",
                    a, b, result, b, a, reverse)
            }
        }
    })
}

Cobertura de Pruebas

Ejecutando 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 condiciones 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:       "get user",
            method:     http.MethodGet,
            path:       "/users/123",
            wantStatus: http.StatusOK,
            wantBody:   `{"id":"123","name":"Alice"}`,
        },
        {
            name:       "not found",
            method:     http.MethodGet,
            path:       "/users/999",
            wantStatus: http.StatusNotFound,
        },
        {
            name:       "create user",
            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) {
            // Crear solicitud con cuerpo
            var bodyReader io.Reader
            if tt.body != "" {
                bodyReader = strings.NewReader(tt.body)
            }
            req := httptest.NewRequest(tt.method, tt.path, bodyReader)
            w := httptest.NewRecorder()

            // Llamar al manejador
            handler.ServeHTTP(w, req)

            // Verificar código de estado
            resp := w.Result()
            defer resp.Body.Close()

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

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

Integración Continua

Configuración de GitHub Actions

name: Test
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version: '1.22'
      - name: Run tests
        run: go test -v -race -coverprofile=coverage.out ./...
      - name: Upload coverage
        uses: actions/upload-artifact@v4
        with:
          name: coverage
          path: coverage.out

Script de Control de Cobertura

#!/bin/bash
# scripts/check-coverage.sh

go test -coverprofile=coverage.out ./...

# Extraer cobertura total
coverage=$(go tool cover -func=coverage.out | grep total | awk '{print $3}' | sed 's/%//')

if (( $(echo "$coverage < 80" | bc -l) )); then
    echo "Cobertura de prueba $coverage% por debajo del umbral del 80%"
    exit 1
fi

echo "Cobertura de prueba: $coverage%"

Go-Privacy: Asegurando Pruebas Aisladas

Estado Compartido y Datos de Prueba

func TestUserService(t *testing.T) {
    // Configuración local aislada - sin estado global
    repo := NewInMemoryRepository()
    svc := NewUserService(repo)

    // Estado compartido dentro del ámbito de la prueba
    t.Run("Create", func(t *testing.T) {
        svc.CreateUser("[email protected]")
    })

    t.Run("Get", func(t *testing.T) {
        // Este test ve los efectos del test "Create"
        user, _ := svc.GetUser("[email protected]")
        if user == nil {
            t.Fatal("Se esperaba que el usuario creado esté disponible")
        }
    })

    t.Run("Cleanup", func(t *testing.T) {
        // Los tests pueden limpiar después de sí mismos
        svc.DeleteUser("[email protected]")
    })
}

Estado Paralelo Aislado

func TestParallelIsolation(t *testing.T) {
    // Cada subprueba obtiene su propio estado limpio
    tests := []struct {
        name  string
        input string
    }{
        {"Alice", "[email protected]"},
        {"Bob", "[email protected]"},
        {"Charlie", "[email protected]"},
    }

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

            // Cada goroutine obtiene su propia instancia del servicio
            repo := NewInMemoryRepository()
            svc := NewUserService(repo)

            // Usar nombres únicos para evitar colisiones
            username := fmt.Sprintf("%s_%d", tt.input, time.Now().UnixNano())

            err := svc.CreateUser(username)
            if err != nil {
                t.Errorf("Error creando usuario: %v", err)
            }
        })
    }
}

Conclusión

Sigue estos patrones para escribir pruebas Go confiables, mantenibles y eficientes que se integren bien con el ecosistema Go. La combinación de pruebas basadas en tablas, ayudantes, archivos golden, mocking, benchmarks, fuzzing y cobertura te brinda un conjunto de herramientas completo para garantizar la calidad del código.

Recursos Adicionales

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.

Skills relacionados