agentleFS
peopleforresterpeopleforrester/claude-dotfiles/skills/development/golang-testing/SKILL.md

golang-testing

Skill3 starsChanged 8 months agoMITView on GitHub

Comprehensive Go testing patterns. Covers table-driven tests, httptest, testcontainers, benchmarks, fuzzing, and race detection.

30 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use golang-concurrency, golang-error-handling and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • guynhsichngeodiecSkill

    golang-concurrency

    Golang concurrency patterns. Use when writing or reviewing concurrent Go code involving goroutines, channels, select, locks, sync primitives, errgroup, singleflight, worker pools, or fan-out/fan-in pipelines. Also triggers when you detect goroutine leaks, race conditions, channel ownership issues, or need to choose between channels and mutexes.

    Also in 7 projects that use this

  • guynhsichngeodiecSkill

    golang-error-handling

    Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code.

    Also in 6 projects that use this

  • +10 more from guynhsichngeodiec

The file

Files
SKILL.md

Go Testing Patterns

Table-Driven Tests

The standard Go testing pattern:

func TestParseAmount(t *testing.T) {
    tests := []struct {
        name    string
        input   string
        want    float64
        wantErr bool
    }{
        {"valid integer", "100", 100.0, false},
        {"valid decimal", "99.99", 99.99, false},
        {"with currency", "$50.00", 50.0, false},
        {"negative", "-10", -10.0, false},
        {"empty string", "", 0, true},
        {"not a number", "abc", 0, true},
        {"overflow", "9999999999999999999", 0, true},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := ParseAmount(tt.input)
            if (err != nil) != tt.wantErr {
                t.Fatalf("ParseAmount(%q) error = %v, wantErr %v",
                    tt.input, err, tt.wantErr)
            }
            if !tt.wantErr && got != tt.want {
                t.Errorf("ParseAmount(%q) = %v, want %v",
                    tt.input, got, tt.want)
            }
        })
    }
}

HTTP Handler Testing

func TestGetUserHandler(t *testing.T) {
    repo := &mockUserRepo{
        users: map[string]*User{
            "1": {ID: "1", Name: "Alice"},
        },
    }
    handler := NewUserHandler(repo)

    req := httptest.NewRequest("GET", "/users/1", nil)
    rec := httptest.NewRecorder()

    handler.ServeHTTP(rec, req)

    require.Equal(t, http.StatusOK, rec.Code)

    var user User
    err := json.NewDecoder(rec.Body).Decode(&user)
    require.NoError(t, err)
    assert.Equal(t, "Alice", user.Name)
}

Subtests for Setup/Teardown

func TestUserService(t *testing.T) {
    db := setupTestDB(t)
    svc := NewUserService(db)

    t.Run("Create", func(t *testing.T) {
        user, err := svc.Create(context.Background(), "Alice", "alice@example.com")
        require.NoError(t, err)
        assert.Equal(t, "Alice", user.Name)
    })

    t.Run("FindByEmail", func(t *testing.T) {
        user, err := svc.FindByEmail(context.Background(), "alice@example.com")
        require.NoError(t, err)
        assert.Equal(t, "Alice", user.Name)
    })

    t.Run("NotFound", func(t *testing.T) {
        _, err := svc.FindByEmail(context.Background(), "missing@example.com")
        assert.ErrorIs(t, err, ErrNotFound)
    })
}

Benchmarks

func BenchmarkParseAmount(b *testing.B) {
    inputs := []string{"100", "99.99", "$50.00", "-10.5"}

    for _, input := range inputs {
        b.Run(input, func(b *testing.B) {
            for i := 0; i < b.N; i++ {
                ParseAmount(input)
            }
        })
    }
}

// Run: go test -bench=. -benchmem ./...

Fuzzing (Go 1.18+)

func FuzzParseAmount(f *testing.F) {
    // Seed corpus
    f.Add("100")
    f.Add("99.99")
    f.Add("$50.00")
    f.Add("")

    f.Fuzz(func(t *testing.T, input string) {
        result, err := ParseAmount(input)
        if err == nil && result < 0 {
            // Verify invariants on successful parse
            t.Errorf("ParseAmount(%q) = %v, expected non-negative", input, result)
        }
    })
}

// Run: go test -fuzz=FuzzParseAmount ./...

Race Detection

# Always run with -race in CI
go test -race -count=1 ./...

Test Helpers

// testutil/helpers.go
func RequireEqualJSON(t *testing.T, expected, actual string) {
    t.Helper()
    var e, a interface{}
    require.NoError(t, json.Unmarshal([]byte(expected), &e))
    require.NoError(t, json.Unmarshal([]byte(actual), &a))
    assert.Equal(t, e, a)
}

Commands

go test ./...                    # Run all tests
go test -v ./...                 # Verbose output
go test -race ./...              # Race detection
go test -cover ./...             # Coverage summary
go test -coverprofile=c.out ./... # Coverage profile
go tool cover -html=c.out       # Visual coverage report
go test -bench=. -benchmem ./... # Benchmarks
go test -fuzz=FuzzName ./pkg     # Fuzzing
go test -count=1 ./...           # Disable test caching

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.