Skills Plugins MCP Prompt Model 博客 我的中心
開発 #writing #testing

golang-testing

Go testing best practices including table-driven tests, test helpers, benchmarking, race detection, coverage analysis, and integration testing patterns. Use when writing or improving Go tests.

DeepseekModel キュレーション済みスキル 品質 優秀 · 90 v1.0.0

取得

https://deepseekmodel.com/api/download.php?id=affaan-m-ecc-kiro-skills-golang-testing-skill-md&format=skill
ダウンロード .skill 標準形式。system_prompt と model_config を収録し、任意の Agent で利用可能
.skill ファイルの system_prompt フィールドの実際の内容。
name golang-testing description Go testing best practices including table-driven tests, test helpers, benchmarking, race detection, coverage analysis, and integration testing patterns. Use when writing or improving Go tests. metadata {"origin":"ECC","globs":["**/*.go","**/go.mod","**/go.sum"]} Go Testing This skill provides comprehensive Go testing patterns extending common testing principles with Go-specific idioms. Testing Framework Use the standard go test with table-driven tests as the primary pattern. Table-Driven Tests The idiomatic Go testing pattern: func TestValidateEmail (t *testing.T) { tests := [] struct { name string email string wantErr bool }{ { name: "valid email" , email: "user@example.com" , wantErr: false , }, { name: "missing @" , email: "userexample.com" , wantErr: true , }, { name: "empty string" , email: "" , wantErr: true , }, } for _, tt := range tests { t.Run(tt.name, func (t *testing.T) { err := ValidateEmail(tt.email) if (err != nil ) != tt.wantErr { t.Errorf( "ValidateEmail(%q) error = %v, wantErr %v" , tt.email, err, tt.wantErr) } }) } } Benefits: Easy to add new test cases Clear test case documentation Parallel test execution with t.Parallel() Isolated subtests with t.Run() Test Helpers Use t.Helper() to mark helper functions: func assertNoError (t *testing.T, err error ) { t.Helper() if err != nil { t.Fatalf( "unexpected error: %v" , err) } } func assertEqual (t *testing.T, got, want interface {}) { t.Helper() if !reflect.DeepEqual(got, want) { t.Errorf( "got %v, want %v" , got, want) } } Benefits: Correct line numbers in test failures Reusable test utilities Cleaner test code Test Fixtures Use t.Cleanup() for resource cleanup: func testDB (t *testing.T) *sql.DB { t.Helper() db, err := sql.Open( "sqlite3" , ":memory:" ) if err != nil { t.Fatalf( "failed to open test db: %v" , err) } // Cleanup runs after test completes t.Cleanup( func () { if err := db.Close(); err != nil { t.Errorf( "failed to close db: %v" , err) } }) return db } func TestUserRepository (t *testing.T) { db := testDB(t) repo := NewUserRepository(db) // ... test logic } Race Detection Always run tests with the -race flag to detect data races: go test -race ./... In CI/CD: - name: Test with race detector run: go test -race -timeout 5m ./... Why: Detects concurrent access bugs Prevents production race conditions Minimal performance overhead in tests Coverage Analysis Basic Coverage go test -cover ./... Detailed Coverage Report go test -coverprofile=coverage.out ./... go tool cover -html=coverage.out Coverage Thresholds # Fail if coverage below 80% go test -cover ./... | grep -E 'coverage: [0-7][0-9]\.[0-9]%' && exit 1 Benchmarking func BenchmarkValidateEmail (b *testing.B) { email := "user@example.com" b.ResetTimer() for i := 0 ; i < b.N; i++ { ValidateEmail(email) } } Run benchmarks: go test -bench=. -benchmem Compare benchmarks: go test -bench=. -benchmem > old.txt # make changes go test -bench=. -benchmem > new.txt benchstat old.txt new.txt Mocking Interface-Based Mocking type UserRepository interface { GetUser(id string ) (*User, error ) } type mockUserRepository struct { users map [ string ]*User err error } func (m *mockUserRepository) GetUser(id string ) (*User, error ) { if m.err != nil { return nil , m.err } return m.users[id], nil } func TestUserService (t *testing.T) { mock := &mockUserRepository{ users: map [ string ]*User{ "1" : {ID: "1" , Name: "Alice" }, }, } service := NewUserService(mock) // ... test logic } Integration Tests Build Tags //go:build integration // +build integration package user_test func TestUserRepository_Integration (t *testing.T) { // ... integration test } Run integration tests: go test -tags=integration ./... Test Containers func TestWithPostgres (t *testing.T) { if testing.Short() { t.Skip( "skipping integration test" ) } // Setup test container ctx := context.Background() container, err := testcontainers.GenericContainer(ctx, ...) assertNoError(t, err) t.Cleanup( func () { container.Terminate(ctx) }) // ... test logic } Test Organization File Structure package/ ├── user.go ├── user_test.go # Unit tests ├── user_integration_test.go # Integration tests └── testdata/ # Test fixtures └── users.json Package Naming // Black-box testing (external perspective) package user_test // White-box testing (internal access) package user Common Patterns Testing HTTP Handlers func TestUserHandler (t *testing.T) { req := httptest.NewRequest( "GET" , "/users/1" , nil ) rec := httptest.NewRecorder() handler := NewUserHandler(mockRepo) handler.ServeHTTP(rec, req) assertEqual(t, rec.Code, http.StatusOK) } Testing with Context func TestWithTimeout (t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 100 *time.Millisecond) defer cancel() err := SlowOperation(ctx) if !errors.Is(err, context.DeadlineExceeded) { t.Errorf( "expected timeout error, got %v" , err) } } Best Practices Use t.Parallel() for independent tests Use testing.Short() to skip slow tests Use t.TempDir() for temporary directories Use t.Setenv() for environment variables Avoid init() in test files Keep tests focused - one behavior per test Use meaningful test names - describe what's being tested When to Use This Skill Writing new Go tests Improving test coverage Setting up test infrastructure Debugging flaky tests Optimizing test performance Implementing integration tests
このスキルを起動するキーワード。クリックでコピーできます。

このスキルにはトリガーワードがありません。

ダウンロードした .skill に含まれるフィールド。
フィールド 説明
formatフォーマット識別子(skill/v1)
skill_idスキル固有 ID
nameスキル名
versionバージョン
description説明
categoryカテゴリ(配列)
trigger_wordsトリガーワード
tagsタグ
sourceソース
source_urlソース URL(本ページ)
exported_atエクスポート日時(ダウンロード毎)
system_promptシステムプロンプト本文
model_configモデル設定:provider / model / temperature / max_tokens / top_p
examplesサンプル
install_guide各プラットフォームの導入説明(Coze / Dify / Claude / カスタム)
同じスキルを各プラットフォーム形式で出力できます。
.skill 標準形式。system_prompt と model_config を収録し、任意の Agent で利用可能 ダウンロード
.skillpro 拡張形式。scripts / tools / dependencies / hooks を含む ダウンロード
.json 純粋な JSON 出力。system_prompt とモデル設定のみ ダウンロード
Coze frontmatter 付き Markdown。Coze へのインポート用 ダウンロード
Dify Dify DSL。アプリ作成後にそのままインポート ダウンロード

每日精选 Skill 推荐,免费送到你邮箱

输入邮箱,每天接收一个精选 AI Agent 技能推荐。完全免费,持续更新。

提交后我们会发送一封确认邮件,点击邮件里的链接才会开始收信。

完全免费,取消任意时间。我们不会发送垃圾邮件。