MCP HubMCP Hub
SKILL·17F695

go-test-table-driven

eduardo-sl
Обновлено 27 days ago
5 просмотров
69
9
69
Посмотреть на GitHub
Тестированиеtestingdesigndata

О программе

Этот навык Claude предоставляет экспертные рекомендации по внедрению и рефакторингу табличных тестов в Go. Он охватывает лучшие практики проектирования структур, именования подтестов, продвинутые шаблоны, такие как тестовые матрицы, а также принятие решений о том, когда использовать или избегать данный подход. Используйте его конкретно для написания, рецензирования или очистки табличных тестов, а не для общих стратегий тестирования или других типов тестов.

Быстрая установка

Claude Code

Рекомендуется
Основной
npx skills add eduardo-sl/go-agent-skills -a claude-code
Команда плагинаАльтернативный
/plugin add https://github.com/eduardo-sl/go-agent-skills
Git клонированиеАльтернативный
git clone https://github.com/eduardo-sl/go-agent-skills.git ~/.claude/skills/go-test-table-driven

Скопируйте и вставьте эту команду в Claude Code для установки этого навыка

Документация

Go Table-Driven Tests

Table-driven tests are a powerful Go idiom — when used correctly. Most codebases either underuse them (10 copy-paste tests) or overuse them (complex branching logic in a 200-line struct). This skill covers the sweet spot.

Detailed reference material, loaded on demand:

  • references/patterns.md — full worked examples: canonical tables, wantErr/wantErrIs, parallel tables, map-based tables, error-only tables, struct alignment for readability.
  • references/refactoring.md — recognizing bloated tables and rewriting them as explicit subtests, with before/after examples.

Read a reference file only when the summary below is not enough for the task at hand.

1. When Table-Driven Tests Shine

Use a table only when ALL of these are true:

  • Same function under test across all cases
  • Same assertion pattern — input in, output out, compare
  • Cases differ only in data, not in setup or verification logic
  • 3+ cases — fewer than 3, explicit tests are clearer

Canonical use case: pure functions, parsers, validators, formatters.

func TestParseSize(t *testing.T) {
    tests := []struct {
        name    string
        input   string
        want    int64
        wantErr bool
    }{
        {name: "plain bytes", input: "1024", want: 1024},
        {name: "kilobytes suffix", input: "4KB", want: 4096},
        {name: "empty string", input: "", wantErr: true},
        {name: "negative size", input: "-1", wantErr: true},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := ParseSize(tt.input)
            if tt.wantErr {
                require.Error(t, err)
                return
            }
            require.NoError(t, err)
            assert.Equal(t, tt.want, got)
        })
    }
}

Every case has the same shape, the loop body is a few lines, and adding a case is one struct literal. No branching, no conditionals.

2. When NOT to Use Table-Driven Tests

  • Complex per-case setupsetupMock/setupFunc function fields in the struct mean the table is hiding complexity. Write explicit subtests.
  • Fewer than 3 cases — the struct definition is more code than two plain test functions.
  • Multiple branching pathsif tt.shouldError / if tt.wantRedirect in the loop body means each branch is a different test pretending to share a structure. Split it.

See references/refactoring.md for before/after rewrites of each smell.

3. Struct Design Rules

  1. Every field must vary between at least 2 cases. A field with the same value everywhere is setup — move it outside the table.
  2. Name the name field as a short sentence describing the scenario: "returns error for negative amount", not "case1" or "success".
  3. wantErr bool for "should it error?" — check it first and return early in the loop body.
  4. wantErrIs error with a sentinel when the caller must detect a specific error; assert with require.ErrorIs.
  5. ≤5 fields. More means the scenario is too complex for a table — split into separate test functions.

Full field-pattern examples are in references/patterns.md.

4. The Loop Body Must Be Trivial

The point of a table test is identical execution logic for every case. Keep the loop body under ~10 lines: call, error check, comparison. If it accumulates conditionals or per-case setup, the table has outgrown its usefulness — refactor into explicit subtests.

5. Parallel Table Tests

for _, tt := range tests {
    t.Run(tt.name, func(t *testing.T) {
        t.Parallel()
        got := Transform(tt.input)
        assert.Equal(t, tt.want, got)
    })
}
  • Go 1.22+ scopes the loop variable per iteration — tt := tt capture is unnecessary. For Go <1.22 the capture is still required.
  • Only use t.Parallel() when the function under test has no side effects and no shared mutable state.

6. Refactoring Bloated Tables

SymptomFix
Struct has 8+ fieldsSplit into multiple test functions by scenario
setupFunc field in structExtract to separate subtests with explicit setup
if tt.shouldX in loop bodyEach branch is a different test — split it
Same 3 fields identical in every caseMove to shared setup outside the table
Adding a case requires understanding all othersTable has grown beyond its useful life

Decision Flowchart

  1. Is the function pure (input → output, no side effects)? Yes → table test is probably ideal. Go to 2. No → consider explicit subtests first.

  2. Do all cases share the exact same assertion pattern? Yes → table test. Go to 3. No → explicit subtests.

  3. Can each case be expressed in ≤5 struct fields? Yes → table test. No → split by scenario into separate test functions.

  4. Is the loop body ≤10 lines? Yes → you're golden. No → the table is hiding complexity. Refactor.

Verification Checklist

  1. Table struct has only fields that vary between cases
  2. Every case has a descriptive name field
  3. Loop body is ≤10 lines with no branching
  4. No setupFunc or mockFunc fields in the struct
  5. wantErr is a simple bool or sentinel, not a string match
  6. Cases cover: happy path, error path, edge cases (empty, nil, zero, max)
  7. t.Run wraps each case for named subtests
  8. t.Parallel() used only when function is side-effect-free

GitHub репозиторий

eduardo-sl/go-agent-skills
Путь: skills/(testing)/go-test-table-driven
0
FAQ

Часто задаваемые вопросы

Что такое Skill go-test-table-driven?

go-test-table-driven — это Claude Skill от eduardo-sl. Skills объединяют инструкции и ресурсы, которые Claude загружает по мере необходимости, чтобы выполнять задачи, связанные с go-test-table-driven, без дополнительных запросов.

Как установить go-test-table-driven?

Используйте команды установки на этой странице: добавьте go-test-table-driven в Claude Code как плагин или клонируйте репозиторий в каталог skills, затем перезапустите Claude, чтобы загрузить Skill.

К какой категории относится go-test-table-driven?

go-test-table-driven относится к категории Тестирование.

Можно ли использовать go-test-table-driven бесплатно?

Да. go-test-table-driven размещён на AIMCP и доступен для бесплатной установки.

Похожие навыки

evaluating-llms-harness
Тестирование

Этот навык Claude запускает lm-evaluation-harness для тестирования LLM на более чем 60 стандартизированных академических задачах, таких как MMLU и GSM8K. Он предназначен для разработчиков, чтобы сравнивать качество моделей, отслеживать прогресс обучения или сообщать академические результаты. Инструмент поддерживает различные бэкенды, включая модели HuggingFace и vLLM.

Просмотреть навык
cloudflare-cron-triggers
Тестирование

Этот навык предоставляет обширные знания по реализации Cloudflare Cron Triggers для планирования запуска Workers с помощью cron-выражений. Он охватывает настройку периодических задач, заданий технического обслуживания и автоматизированных рабочих процессов, а также решение распространенных проблем, таких как неверные cron-выражения и ошибки часовых поясов. Разработчики могут использовать его для настройки планировщиков обработчиков, тестирования cron-триггеров и интеграции с Workflows и Green Compute.

Просмотреть навык
webapp-testing
Тестирование

Этот навык Claude предоставляет инструментарий на базе Playwright для тестирования локальных веб-приложений с помощью Python-скриптов. Он позволяет проводить проверку фронтенда, отладку интерфейса, создание скриншотов и просмотр логов, одновременно управляя жизненным циклом сервера. Используйте его для задач автоматизации браузера, но запускайте скрипты напрямую, вместо чтения их исходного кода, чтобы избежать загрязнения контекста.

Просмотреть навык
finishing-a-development-branch
Тестирование

Этот навык помогает разработчикам завершать готовую работу, проверяя прохождение тестов и предлагая структурированные варианты интеграции. Он направляет рабочий процесс по слиянию, созданию пул-реквестов или очистке веток после завершения реализации. Используйте его, когда ваш код готов и протестирован, чтобы систематически завершать процесс разработки.

Просмотреть навык