MCP HubMCP Hub
SKILL·D68062

go-test-quality

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

О программе

Этот навык предоставляет всесторонние рекомендации по шаблонам тестирования 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-quality

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

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

Go Test Quality

Tests are production code. They run in CI on every commit, they document behavior, and they're the first thing you read when a function breaks at 3am. Write them with the same care you'd give to code that handles money.

Detailed reference material, loaded on demand:

  • references/helpers-and-fixtures.md — test helpers, factory functions with options, t.Cleanup, golden files, mock implementations.
  • references/integration-testing.md — httptest recorder and server, testcontainers, build tags, TestMain, fuzz testing.

Read a reference file only when the summary below is not enough.

1. Test Design Philosophy

Test behavior, not implementation

// ✅ Good — tests what the function DOES
func TestTransferFunds_InsufficientBalance(t *testing.T) {
    from := NewAccount("alice", 100)
    to := NewAccount("bob", 0)

    err := TransferFunds(from, to, 150)

    require.ErrorIs(t, err, ErrInsufficientFunds)
    assert.Equal(t, 100, from.Balance(), "sender balance should be unchanged")
    assert.Equal(t, 0, to.Balance(), "receiver balance should be unchanged")
}

// ❌ Bad — tests HOW the function does it
// asserts debit() was called before credit(), rollback() was called,
// internal mutex was locked — breaks on every refactor

One assertion per logical concept

Multiple assert calls are fine when they verify different facets of the SAME behavior (both accounts after a transfer). A test that checks creation AND update AND deletion is three tests pretending to be one.

Name tests like bug reports

When the test fails, the name alone should say what broke:

// ✅ Good — reads like a sentence
func TestOrderService_Cancel_RefundsPartiallyShippedItems(t *testing.T) { ... }
func TestParseConfig_ReturnsErrorOnMissingRequiredField(t *testing.T) { ... }

// ❌ Bad — says nothing useful
func TestCancel(t *testing.T) { ... }
func TestRateLimiter_Success(t *testing.T) { ... }

2. Subtests for Organized Scenarios

Use t.Run to group related scenarios under a parent test. Each subtest gets its own setup, its own failure, and its own name in CI output:

func TestUserService_Create(t *testing.T) {
    svc := setupUserService(t)

    t.Run("succeeds with valid input", func(t *testing.T) {
        user, err := svc.Create(ctx, CreateUserInput{Name: "Alice", Email: "[email protected]"})
        require.NoError(t, err)
        assert.NotEmpty(t, user.ID)
    })

    t.Run("rejects duplicate email", func(t *testing.T) {
        _, _ = svc.Create(ctx, CreateUserInput{Name: "Alice", Email: "[email protected]"})
        _, err := svc.Create(ctx, CreateUserInput{Name: "Bob", Email: "[email protected]"})
        require.ErrorIs(t, err, ErrDuplicateEmail)
    })
}

3. Test Helper Rules

  1. Always call t.Helper() in test utilities so failures point to the caller, not the helper.
  2. Factory functions with functional options for complex test objects — defaults with per-test overrides, never a 15-parameter constructor.
  3. Prefer t.Cleanup over defer — it runs even after t.FailNow() and is scoped to the test, not the function.

Full implementations in references/helpers-and-fixtures.md.

4. Choosing the Test Type

SituationApproachDetails
Pure function, 3+ data casesTable-driven testgo-test-table-driven skill
HTTP handler in isolationhttptest.NewRecorder + mock storereferences/integration-testing.md
Full routing/middleware stackhttptest.NewServerreferences/integration-testing.md
Real database behaviortestcontainers + build tagsreferences/integration-testing.md
Complex output (JSON, HTML, SQL)Golden files in testdata/references/helpers-and-fixtures.md
Parser/validator on untrusted inputFuzz testreferences/integration-testing.md

5. Mocking Rules

  • Interface-based hand-written mocks for small interfaces (≤3 methods): a struct with function fields plus recorded calls.
  • Function injection for simple seams (now func() time.Time).
  • Do NOT mock: value objects, pure functions, the standard library, or your own code in the same package. Test the real thing.
  • If you mock everything, you're testing your mocks, not your code.

6. Parallelism and Coverage

func TestSlugify(t *testing.T) {
    t.Parallel() // safe: pure function, no shared state
    // ...
}

Do NOT use t.Parallel() when tests share mutable state, databases, files, or process-level state (os.Setenv).

go test -race -coverprofile=coverage.out ./...
go tool cover -func=coverage.out

Targets: business logic 80%+, critical paths (auth, payments) 95%+, handlers 70%+. Don't chase 100% on generated code and simple getters.

Anti-Patterns

  • 🔴 Test with no assertions — always passes, proves nothing
  • 🔴 time.Sleep for synchronization — use channels or polling
  • 🔴 Test depends on execution order — each test must stand alone
  • 🔴 Mocking everything — you end up testing your mocks, not your code
  • 🟡 Test names like Test1, TestSuccess — name the scenario
  • 🟡 Reaching into private fields — test through the public API
  • 🟡 No edge cases: empty, nil, zero, max values, unicode
  • 🟡 Giant shared setup — each test should set up only what it needs
  • 🟢 Fuzz anything that takes untrusted input
  • 🟢 Golden files for complex output comparisons

Verification Checklist

  1. Every test has meaningful assertions (no empty test bodies)
  2. Test names describe the scenario, not the method
  3. t.Helper() called in every test utility function
  4. t.Cleanup() used for resource teardown
  5. t.Parallel() used where safe, avoided where not
  6. Integration tests guarded with testing.Short() or build tags
  7. Mocks are minimal — only mock external dependencies
  8. Edge cases covered: empty, nil, zero, boundary values
  9. go test -race ./... passes
  10. Coverage is meaningful, not just high numbers

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

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

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

Что такое Skill go-test-quality?

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

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

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

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

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

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

Да. go-test-quality размещён на 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
Тестирование

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

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