Skip to main content
ClaudeWave
ES, Spanish
Slash Command2k estrellas del repoactualizado 7mo ago

go-test

The `/go-test` command implements test-driven development for Go projects by guiding developers through a structured TDD workflow. Use this command when writing new Go functions, adding test coverage to existing code, fixing bugs with failing tests first, or building critical business logic that requires comprehensive validation through table-driven tests and minimum 80% code coverage verification.

Instalar en Claude Code
Copiar
mkdir -p ~/.claude/commands && curl -fsSL https://raw.githubusercontent.com/xu-xiang/everything-claude-code-zh/HEAD/commands/go-test.md -o ~/.claude/commands/go-test.md
Después abre una sesión nueva de Claude Code; el slash command carga automáticamente.

go-test.md

# Go TDD 命令

此命令通过惯用的 Go 测试模式为 Go 代码强制执行测试驱动开发(TDD)方法论。

## 此命令的作用

1. **定义类型/接口**:首先搭建函数签名脚手架
2. **编写表格驱动测试**:创建全面的测试用例(红灯 RED)
3. **运行测试**:验证测试因正确的原因而失败
4. **编写代码**:编写最少量的代码以通过测试(绿灯 GREEN)
5. **重构(Refactor)**:在保持测试通过的同时改进代码
6. **检查覆盖率**:确保 80% 以上的覆盖率

## 何时使用

在以下场景使用 `/go-test`:
- 实现新的 Go 函数
- 为现有代码添加测试覆盖率
- 修复 Bug(先编写失败的测试)
- 构建关键业务逻辑
- 学习 Go 中的 TDD 工作流

## TDD 周期

```
RED      → 编写失败的表格驱动测试
GREEN    → 编写最少量的代码以通过测试
REFACTOR → 改进代码,保持测试通过
REPEAT   → 下一个测试用例
```

## 会话示例

````
用户:/go-test 我需要一个验证电子邮件地址的函数

智能体(Agent):
# TDD 会话:电子邮件验证器(Email Validator)

## 第 1 步:定义接口

```go
// validator/email.go
package validator

// ValidateEmail 检查给定的字符串是否为有效的电子邮件地址。
// 如果有效则返回 nil,否则返回描述问题的错误。
func ValidateEmail(email string) error {
    panic("not implemented")
}
```

## 第 2 步:编写表格驱动测试(红灯 RED)

```go
// validator/email_test.go
package validator

import (
    "testing"
)

func TestValidateEmail(t *testing.T) {
    tests := []struct {
        name    string
        email   string
        wantErr bool
    }{
        // 有效的电子邮件
        {"simple email", "user@example.com", false},
        {"with subdomain", "user@mail.example.com", false},
        {"with plus", "user+tag@example.com", false},
        {"with dots", "first.last@example.com", false},

        // 无效的电子邮件
        {"empty string", "", true},
        {"no at sign", "userexample.com", true},
        {"no domain", "user@", true},
        {"no local part", "@example.com", true},
        {"double at", "user@@example.com", true},
        {"spaces", "user @example.com", true},
        {"no tld", "user@example", true},
    }

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

## 第 3 步:运行测试 - 验证失败(FAIL)

```bash
$ go test ./validator/...

--- FAIL: TestValidateEmail (0.00s)
    --- FAIL: TestValidateEmail/simple_email (0.00s)
        panic: not implemented

FAIL
```

✓ 测试按预期失败(panic)。

## 第 4 步:编写最少量代码(绿灯 GREEN)

```go
// validator/email.go
package validator

import (
    "errors"
    "regexp"
)

var emailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)

var (
    ErrEmailEmpty   = errors.New("email cannot be empty")
    ErrEmailInvalid = errors.New("email format is invalid")
)

func ValidateEmail(email string) error {
    if email == "" {
        return ErrEmailEmpty
    }
    if !emailRegex.MatchString(email) {
        return ErrEmailInvalid
    }
    return nil
}
```

## 第 5 步:运行测试 - 验证通过(PASS)

```bash
$ go test ./validator/...

PASS
ok      project/validator    0.003s
```

✓ 所有测试均通过!

## 第 6 步:检查覆盖率

```bash
$ go test -cover ./validator/...

PASS
coverage: 100.0% of statements
ok      project/validator    0.003s
```

✓ 覆盖率:100%

## TDD 完成!
````

## 测试模式

### 表格驱动测试(Table-Driven Tests)
```go
tests := []struct {
    name     string
    input    InputType
    want     OutputType
    wantErr  bool
}{
    {"case 1", input1, want1, false},
    {"case 2", input2, want2, true},
}

for _, tt := range tests {
    t.Run(tt.name, func(t *testing.T) {
        got, err := Function(tt.input)
        // 断言(assertions)
    })
}
```

### 并行测试(Parallel Tests)
```go
for _, tt := range tests {
    tt := tt // 变量捕获(Capture)
    t.Run(tt.name, func(t *testing.T) {
        t.Parallel()
        // 测试主体
    })
}
```

### 测试助手(Test Helpers)
```go
func setupTestDB(t *testing.T) *sql.DB {
    t.Helper()
    db := createDB()
    t.Cleanup(func() { db.Close() })
    return db
}
```

## 覆盖率命令

```bash
# 基础覆盖率
go test -cover ./...

# 覆盖率配置文件
go test -coverprofile=coverage.out ./...

# 在浏览器中查看
go tool cover -html=coverage.out

# 按函数查看覆盖率
go tool cover -func=coverage.out

# 启用竞态检测
go test -race -cover ./...
```

## 覆盖率目标

| 代码类型 | 目标 |
|-----------|--------|
| 关键业务逻辑 | 100% |
| 公共 API | 90%+ |
| 通用代码 | 80%+ |
| 生成的代码 | 排除 |

## TDD 最佳实践

**应该(DO):**
- 在任何实现之前,先编写测试
- 每次更改后运行测试
- 使用表格驱动测试以获得全面的覆盖率
- 测试行为,而非实现细节
- 包含边缘情况(空值、nil、最大值)

**不该(DON'T):**
- 在测试之前编写实现
- 跳过红灯(RED)阶段
- 直接测试私有函数
- 在测试中使用 `time.Sleep`
- 忽视不稳定的测试(Flaky tests)

## 相关命令

- `/go-build` - 修复构建错误
- `/go-review` - 实现后评审代码
- `/verify` - 运行完整的验证循环

## 相关

- 技能(Skill):`skills/golang-testing/`
- 技能(Skill):`skills/tdd-workflow/`
api-designSkill

生产级 API 的 REST API 设计模式,包括资源命名、状态码、分页、过滤、错误响应、版本控制和速率限制。

architectSubagent

用于系统设计、可扩展性及技术决策的软件架构专家。在规划新功能、重构大型系统或做出架构决策时请主动(PROACTIVELY)使用。

article-writingSkill

编写文章、指南、博客、教程、时事通讯(Newsletter)等长内容,支持从示例或品牌指南中提取独特的语感语调。适用于需要撰写超过一个段落的精炼文本,尤其是对语气一致性、结构和可信度有较高要求时。

backend-patternsSkill

后端架构模式、API 设计、数据库优化以及 Node.js、Express 和 Next.js API 路由的服务端最佳实践。

build-error-resolverSubagent

构建与 TypeScript 错误修复专家。当构建失败或出现类型错误时,请主动(PROACTIVELY)使用。仅修复构建/类型错误,保持最小差异(diff),不进行架构性修改。重点是快速使构建通过(get the build green)。

chief-of-staffSubagent

个人通讯幕僚 (Chief of Staff),负责分拣电子邮件、Slack、LINE 和 Messenger。将消息分类为 4 个级别 (skip/info_only/meeting_info/action_required),生成草稿回复,并通过钩子 (Hooks) 强制执行发送后的后续跟进。适用于管理多渠道通讯工作流。

clawSlash Command

启动 NanoClaw 智能体 (Agent) REPL — 一个由 claude CLI 驱动的持久化、会话感知 (session-aware) 的 AI 助手。

clickhouse-ioSkill

ClickHouse 数据库模式、查询优化、分析以及高性能分析工作负载的数据工程最佳实践。