Skip to content

notque/vexjoy-agent / skills/programming/programming

programming

Flagged

Language-specific patterns and tooling: Go, Kotlin, PHP, Swift, TypeScript.

FileKindSize
SKILL.mdskill md11.6 KB
references/go/code-review.mdmarkdown12.0 KB
references/go/code-review/common-review-comments.mdmarkdown6.6 KB
references/go/concurrency.mdmarkdown11.5 KB
references/go/concurrency/concurrency-patterns.mdmarkdown5.7 KB
references/go/error-handling.mdmarkdown10.8 KB
references/go/error-handling/patterns.mdmarkdown4.2 KB
references/go/google-style-guide/SHA256SUMSother313 B
references/go/google-style-guide/UPSTREAM_REVISIONother41 B
references/go/google-style-guide/best-practices/part-01.mdmarkdown10.0 KB
references/go/google-style-guide/best-practices/part-02.mdmarkdown15.0 KB
references/go/google-style-guide/best-practices/part-03.mdmarkdown14.1 KB
references/go/google-style-guide/best-practices/part-04.mdmarkdown13.5 KB
references/go/google-style-guide/best-practices/part-05.mdmarkdown10.5 KB
references/go/google-style-guide/best-practices/part-06.mdmarkdown14.4 KB
references/go/google-style-guide/best-practices/part-07.mdmarkdown16.1 KB
references/go/google-style-guide/best-practices/part-08.mdmarkdown11.4 KB
references/go/google-style-guide/best-practices/part-09.mdmarkdown13.7 KB
references/go/google-style-guide/best-practices/part-10.mdmarkdown16.9 KB
references/go/google-style-guide/decisions/part-01.mdmarkdown15.0 KB
references/go/google-style-guide/decisions/part-02.mdmarkdown12.5 KB
references/go/google-style-guide/decisions/part-03.mdmarkdown11.5 KB
references/go/google-style-guide/decisions/part-04.mdmarkdown8.4 KB
references/go/google-style-guide/decisions/part-05.mdmarkdown9.8 KB
references/go/google-style-guide/decisions/part-06.mdmarkdown14.7 KB
references/go/google-style-guide/decisions/part-07.mdmarkdown13.3 KB
references/go/google-style-guide/decisions/part-08.mdmarkdown14.3 KB
references/go/google-style-guide/decisions/part-09.mdmarkdown15.3 KB
references/go/google-style-guide/decisions/part-10.mdmarkdown8.3 KB
references/go/google-style-guide/guide/part-01.mdmarkdown16.3 KB
references/go/google-style-guide/guide/part-02.mdmarkdown3.0 KB
references/go/google-style-guide/index.mdmarkdown8.4 KB
references/go/preferred-patterns.mdmarkdown12.5 KB
references/go/preferred-patterns/code-examples.mdmarkdown11.6 KB
references/go/quality-gate.mdmarkdown7.3 KB
references/go/quality-gate/common-lint-errors.jsonconfig7.6 KB
references/go/quality-gate/examples.mdmarkdown11.0 KB
references/go/quality-gate/makefile-targets.jsonconfig5.1 KB
references/go/sapcc-conventions.mdmarkdown34.6 KB
references/go/sapcc-conventions/api-design-detailed.mdmarkdown22.7 KB
references/go/sapcc-conventions/architecture-patterns.mdmarkdown18.6 KB
references/go/sapcc-conventions/build-ci-detailed.mdmarkdown18.7 KB
references/go/sapcc-conventions/error-handling-detailed.mdmarkdown20.1 KB
references/go/sapcc-conventions/extended-patterns.mdmarkdown7.1 KB
references/go/sapcc-conventions/go-bits-philosophy-detailed.mdmarkdown24.5 KB
references/go/sapcc-conventions/library-reference.mdmarkdown14.0 KB
references/go/sapcc-conventions/pr-mining-insights.mdmarkdown17.5 KB
references/go/sapcc-conventions/review-standards.mdmarkdown10.5 KB
references/go/sapcc-conventions/sapcc-code-patterns.mdmarkdown46.2 KB
references/go/testing.mdmarkdown9.7 KB
references/go/testing/go-benchmark-and-concurrency.mdmarkdown5.6 KB
references/go/testing/go-test-patterns.mdmarkdown9.0 KB
references/kotlin/concurrency-patterns.mdmarkdown5.4 KB
references/kotlin/kotlin-testing.mdmarkdown7.9 KB
references/php/modern-php-features.mdmarkdown4.4 KB
references/php/testing-patterns.mdmarkdown7.5 KB
references/swift/preferred-patterns.mdmarkdown2.4 KB
references/swift/swift-testing.mdmarkdown6.6 KB
references/swift/task-patterns.mdmarkdown3.6 KB
scripts/bench-compare.shscript7.1 KB
scripts/check-errors.shscript7.1 KB
scripts/check-interface-compliance.shscript6.4 KB
scripts/check-sapcc-auth-ordering.shscript5.5 KB
scripts/check-sapcc-httptest.shscript4.4 KB
scripts/check-sapcc-identify-endpoint.shscript5.8 KB
scripts/check-sapcc-json-strict.shscript4.9 KB
scripts/check-sapcc-time-now.shscript4.2 KB
scripts/check-sapcc-todo-format.shscript4.1 KB
scripts/gen-table-test.shscript4.2 KB
scripts/quality_checker.pyscript16.2 KB
scripts/sync-google-style-guide.pyscript2.5 KB
scripts/validate.pyscript6.3 KB

references/go/testing/go-test-patterns.md

View on GitHub
# Go Test Patterns Reference

Detailed examples for the go-patterns skill (testing section). See SKILL.md for methodology and workflow.

---

## Table-Driven Test Patterns

### Basic Table-Driven Test

```go
func TestParseTime(t *testing.T) {
    tests := []struct {
        name    string
        input   string
        want    time.Time
        wantErr bool
    }{
        {
            name:  "valid RFC3339",
            input: "2023-01-01T00:00:00Z",
            want:  time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC),
        },
        {
            name:    "invalid format",
            input:   "not a time",
            wantErr: true,
        },
        {
            name:  "valid with timezone",
            input: "2023-01-01T00:00:00+01:00",
            want:  time.Date(2023, 1, 1, 0, 0, 0, 0, time.FixedZone("", 3600)),
        },
    }

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

            if (err != nil) != tt.wantErr {
                t.Errorf("ParseTime() error = %v, wantErr %v", err, tt.wantErr)
                return
            }

            if !tt.wantErr && !got.Equal(tt.want) {
                t.Errorf("ParseTime() = %v, want %v", got, tt.want)
            }
        })
    }
}
```

### Parallel Table-Driven Tests

```go
func TestConcurrentOperations(t *testing.T) {
    tests := []struct {
        name  string
        input string
        want  string
    }{
        {"case1", "input1", "output1"},
        {"case2", "input2", "output2"},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            t.Parallel()
            got := Transform(tt.input)
            if got != tt.want {
                t.Errorf("got %v, want %v", got, tt.want)
            }
        })
    }
}
```

Note: In Go 1.22+, the loop variable capture (`tt := tt`) is no longer needed.

### Named Type vs Anonymous Struct

```go
// PREFER: Anonymous struct for simple tests
tests := []struct {
    name    string
    input   string
    want    int
    wantErr bool
}{ ... }

// USE named type only when:
// 1. Struct is reused across multiple test functions
// 2. Complex setup requires methods on the test case
type parseTestCase struct {
    name    string
    input   string
    setup   func(t *testing.T) *Parser
    verify  func(t *testing.T, result *Result)
}
```

---

## Test Helper Patterns

### Assertion Helpers

```go
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)
    }
}

func assertContains(t *testing.T, haystack, needle string) {
    t.Helper()
    if !strings.Contains(haystack, needle) {
        t.Errorf("expected %q to contain %q", haystack, needle)
    }
}
```

### must.SucceedT Pattern

```go
func SucceedT[T any](t *testing.T, val T, err error) T {
    t.Helper()
    if err != nil {
        t.Fatalf("expected success but got error: %v", err)
    }
    return val
}

// Usage
func TestSomething(t *testing.T) {
    user := must.SucceedT(t, repo.GetUser(ctx, userID))
}
```

### must vs assert: When to Use Which

In Go test code, `must` (fatal) and `assert` (non-fatal) serve different roles:

| Context | Use | Why |
|---------|-----|-----|
| `mustXxx` helper function | `must.SucceedT` / `must.ReturnT` | Fatal — function name says "must" |
| Setup/precondition in test body | `must.SucceedT` / `must.ReturnT` | Fatal — next lines depend on this |
| Checking the tested operation's outcome | `assert.ErrEqual(t, err, nil)` | Non-fatal — reports ALL failures |
| Need return value from fallible call | `must.ReturnT` | Fatal — no assert equivalent |

**Decision tree:**
1. Inside a `mustXxx` helper? → `must.SucceedT` / `must.ReturnT`
2. Next line needs this result? → `must.SucceedT` / `must.ReturnT`
3. Checking the outcome of the tested operation? → `assert.ErrEqual(t, err, nil)`
4. Need a return value? → `must.ReturnT`

```go
// Setup (fatal) — next lines depend on this
must.SucceedT(t, store.UpdateMetrics())
families := must.ReturnT(registry.Gather())(t)

// Assertion (non-fatal) — checking expected outcome
assert.ErrEqual(t, err, nil)
assert.Equal(t, len(families), 3)
```

**The rule: helper = must, assertion = assert.**

Note: For projects using shared test assertion libraries, `must` and `assert` may come from the organization's shared library. The same principle applies to any fatal vs non-fatal test helper pattern.

**Equal vs DeepEqual:**
- `Equal(t, actual, expected)` — for comparable types (int, string, bool), uses `==`
- `DeepEqual(t, "label", actual, expected)` — for slices/maps/structs, uses `reflect.DeepEqual`
- If type supports `==` → `Equal`. If not → `DeepEqual`. Reviewers flag `DeepEqual` used on comparable types.

### Setup/Teardown with t.Cleanup

```go
func setupTestDB(t *testing.T) *sql.DB {
    t.Helper()

    db, err := sql.Open("sqlite3", ":memory:")
    assertNoError(t, err)

    err = runMigrations(db)
    assertNoError(t, err)

    t.Cleanup(func() {
        db.Close()
    })

    return db
}

// Usage - no defer needed
func TestUserRepository(t *testing.T) {
    db := setupTestDB(t)
    repo := NewUserRepository(db)
    // test repo methods
}
```

---

## Mocking Patterns

### Manual Mock with Function Fields and Call Tracking

```go
type EmailSender interface {
    SendEmail(ctx context.Context, to, subject, body string) error
}

type MockEmailSender struct {
    SendEmailFunc func(ctx context.Context, to, subject, body string) error
    calls         []EmailCall
    mu            sync.Mutex
}

type EmailCall struct {
    To      string
    Subject string
    Body    string
}

func (m *MockEmailSender) SendEmail(ctx context.Context, to, subject, body string) error {
    m.mu.Lock()
    m.calls = append(m.calls, EmailCall{To: to, Subject: subject, Body: body})
    m.mu.Unlock()

    if m.SendEmailFunc != nil {
        return m.SendEmailFunc(ctx, to, subject, body)
    }
    return nil
}

func (m *MockEmailSender) GetCalls() []EmailCall {
    m.mu.Lock()
    defer m.mu.Unlock()
    return append([]EmailCall{}, m.calls...)
}

// Usage
func TestNotificationService(t *testing.T) {
    mockSender := &MockEmailSender{
        SendEmailFunc: func(ctx context.Context, to, subject, body string) error {
            if to == "invalid@example.com" {
                return errors.New("invalid email")
            }
            return nil
        },
    }

    service := NewNotificationService(mockSender)
    err := service.NotifyUser(t.Context(), "user@example.com", "Test")
    assertNoError(t, err)

    calls := mockSender.GetCalls()
    if len(calls) != 1 {
        t.Fatalf("expected 1 call, got %d", len(calls))
    }
    assertEqual(t, calls[0].To, "user@example.com")
}
```

### Mock with Expectation Assertions

```go
type MockStorage struct {
    events   []Event
    getCalls []EventFilter
}

func (m *MockStorage) StoreEvent(e Event) error {
    m.events = append(m.events, e)
    return nil
}

func (m *MockStorage) ExpectEvents(t *testing.T, expected ...Event) {
    t.Helper()
    if !reflect.DeepEqual(m.events, expected) {
        t.Errorf("events mismatch:\ngot:  %+v\nwant: %+v", m.events, expected)
    }
}
```

---

## Interface Test Deduplication

When testing multiple implementations of the same interface:

```go
type BackingStore interface {
    Get(key string) ([]byte, error)
    Set(key string, value []byte) error
}

// Shared test logic for any implementation
func testBackingStoreOperations(t *testing.T, store BackingStore) {
    t.Helper()

    err := store.Set("key1", []byte("value1"))
    assertNoError(t, err)

    val, err := store.Get("key1")
    assertNoError(t, err)
    assertEqual(t, string(val), "value1")
}

// Run against all implementations
func testWithEachBackingStore(t *testing.T, action func(*testing.T, BackingStore)) {
    t.Run("with file store", func(t *testing.T) {
        action(t, newTestFileBackingStore(t))
    })
    t.Run("with memory store", func(t *testing.T) {
        action(t, newTestMemoryBackingStore(t))
    })
}

// Usage
func TestBackingStore(t *testing.T) {
    testWithEachBackingStore(t, testBackingStoreOperations)
}
```

---

## Context in Tests

```go
// Go 1.24+: Use t.Context() for automatic cancellation when test ends
func TestWithContext(t *testing.T) {
    ctx := t.Context()
    result, err := longRunningOperation(ctx)
    assertNoError(t, err)
}

// Pre-1.24: Manual context with timeout
func TestEventProcessing(t *testing.T) {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    result, err := processEvent(ctx, testEvent)
    assertNoError(t, err)
    assertEqual(t, result.Status, "processed")
}
```

---

## Coverage Guidelines

1. **Critical paths**: >80% coverage required
2. **Error paths**: Must be tested, not just happy paths
3. **Edge cases**: Empty inputs, nil values, boundary values
4. **Do not chase 100%**: Simple getters and generated code rarely need tests
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 321kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 321kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 321kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 321kUpdated Claude CodeCodexVerifiedInstall