go-testing
Go testing practices - unit tests, benchmarks, mocks, coverage
What this skill does
# Go Testing Skill
Comprehensive testing strategies for Go applications.
## Overview
Master Go testing including table-driven tests, benchmarks, mocking, fuzzing, and achieving high code coverage.
## Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| test_type | string | yes | - | Type: "unit", "integration", "benchmark", "fuzz" |
| coverage_min | int | no | 80 | Minimum coverage percentage |
| mock_lib | string | no | "testify" | Mock library: "testify", "gomock" |
## Core Topics
### Table-Driven Tests
```go
func TestParseURL(t *testing.T) {
tests := []struct {
name string
input string
want *URL
wantErr bool
}{
{
name: "valid http",
input: "http://example.com/path",
want: &URL{Scheme: "http", Host: "example.com", Path: "/path"},
},
{
name: "empty string",
input: "",
wantErr: true,
},
{
name: "invalid scheme",
input: "ftp://example.com",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ParseURL(tt.input)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}
}
```
### Mocking
```go
type MockStore struct {
mock.Mock
}
func (m *MockStore) Get(ctx context.Context, key string) (string, error) {
args := m.Called(ctx, key)
return args.String(0), args.Error(1)
}
func TestService_GetValue(t *testing.T) {
store := new(MockStore)
store.On("Get", mock.Anything, "key1").Return("value1", nil)
svc := NewService(store)
val, err := svc.GetValue(context.Background(), "key1")
require.NoError(t, err)
assert.Equal(t, "value1", val)
store.AssertExpectations(t)
}
```
### Benchmarks
```go
func BenchmarkSort(b *testing.B) {
data := generateData(10000)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
sorted := make([]int, len(data))
copy(sorted, data)
Sort(sorted)
}
}
func BenchmarkSort_Parallel(b *testing.B) {
data := generateData(10000)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
sorted := make([]int, len(data))
copy(sorted, data)
Sort(sorted)
}
})
}
```
### Fuzz Testing
```go
func FuzzJSON(f *testing.F) {
f.Add([]byte(`{"name": "test"}`))
f.Add([]byte(`{}`))
f.Add([]byte(`[]`))
f.Fuzz(func(t *testing.T, data []byte) {
var v interface{}
if err := json.Unmarshal(data, &v); err != nil {
return // invalid input, skip
}
// Re-marshal should work
_, err := json.Marshal(v)
if err != nil {
t.Errorf("Marshal failed: %v", err)
}
})
}
```
## Test Commands
```bash
# Run all tests
go test ./...
# Verbose with race detection
go test -v -race ./...
# Coverage
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out -o coverage.html
# Benchmark
go test -bench=. -benchmem ./...
# Fuzz for 30 seconds
go test -fuzz=FuzzJSON -fuzztime=30s ./...
```
## Troubleshooting
### Failure Modes
| Symptom | Cause | Fix |
|---------|-------|-----|
| Flaky test | Race condition | Add `-race` flag |
| Test timeout | Deadlock | Check goroutines |
| Mock not called | Wrong signature | Verify interface |
## Usage
```
Skill("go-testing")
```
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.