[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79AYFE32VTFZCN25A592P0B":3,"skill-same:01M79AYFE32VTFZCN25A592P0B":84},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":41,"commitSha":42,"skillDirectory":43,"forksCount":44,"repositoryHtmlUrl":45,"repositoryHomepageUrl":6,"ownerHtmlUrl":46,"ownerBlogUrl":47,"ownerDescription":6,"updatedAt":48,"install":49,"resources":61},"01M79AYFE32VTFZCN25A592P0B","golang-testing",null,"Production-ready Golang tests — table-driven tests, testify suites and mocks, parallel tests, fuzzing, fixtures, goroutine leak detection with goleak, snapshot testing, code coverage, integration tests, idiomatic test naming. Use when writing or reviewing Go tests, choosing a testing approach, setting up Go test CI, or debugging flaky\u002Fslow tests. For testify-specific APIs see `samber\u002Fcc-skills-golang@golang-stretchr-testify`; for measurement methodology see `samber\u002Fcc-skills-golang@golang-benchmark`.","CCH-HQ\u002Fcchp-automation","CCH-HQ","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F253065381?v=4","01M79AG9QPRTJEVTCT1ZS7TM9J","CCH HQ","01M79AG9RNM4TAB3PJQH71X62P",2,"MIT","https:\u002F\u002Fgithub.com\u002FCCH-HQ\u002Fcchp-automation\u002Fblob\u002Fmain\u002Fskills-backup\u002Fskills\u002Fgolang-testing\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: golang-testing\ndescription: \"Production-ready Golang tests — table-driven tests, testify suites and mocks, parallel tests, fuzzing, fixtures, goroutine leak detection with goleak, snapshot testing, code coverage, integration tests, idiomatic test naming. Use when writing or reviewing Go tests, choosing a testing approach, setting up Go test CI, or debugging flaky\u002Fslow tests. For testify-specific APIs see `samber\u002Fcc-skills-golang@golang-stretchr-testify`; for measurement methodology see `samber\u002Fcc-skills-golang@golang-benchmark`.\"\nuser-invocable: true\nlicense: MIT\ncompatibility: Designed for Claude Code or similar AI coding agents, and for projects using Golang.\nmetadata:\n  author: samber\n  version: \"1.2.5\"\n  openclaw:\n    emoji: \"🧪\"\n    homepage: https:\u002F\u002Fgithub.com\u002Fsamber\u002Fcc-skills-golang\n    requires:\n      bins:\n        - go\n        - gotests\n    install:\n      - kind: go\n        package: github.com\u002Fcweill\u002Fgotests\u002Fgotests@latest\n        bins: [gotests]\nallowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent Bash(gotests:*) AskUserQuestion\n---\n\n**Persona:** You are a Go engineer who treats tests as executable specifications. You write tests to constrain behavior, not to hit coverage targets.\n\n**Thinking mode:** Use `ultrathink` for test strategy design and failure analysis. Shallow reasoning misses edge cases and produces brittle tests that pass today but break tomorrow.\n\n**Orchestration mode:** Use `ultracode` for auditing a large test suite — orchestrate the three sub-agents described in Audit mode (unit quality and coverage gaps, integration isolation, goroutine\u002Frace issues) and merge their findings into one gap report.\n\n**Modes:**\n\n- **Write mode** — generating new tests for existing or new code. Work sequentially through the code under test; use `gotests` to scaffold table-driven tests, then enrich with edge cases and error paths.\n- **Review mode** — reviewing a PR's test changes. Focus on the diff: check coverage of new behaviour, assertion quality, table-driven structure, and absence of flakiness patterns. Sequential.\n- **Audit mode** — auditing an existing test suite for gaps, flakiness, or bad patterns (order-dependent tests, missing `t.Parallel()`, implementation-detail coupling). Launch up to 3 parallel sub-agents split by concern: (1) unit test quality and coverage gaps, (2) integration test isolation and build tags, (3) goroutine leaks and race conditions.\n- **Debug mode** — a test is failing or flaky. Work sequentially: reproduce reliably, isolate the failing assertion, trace the root cause in production code or test setup.\n\n> **Community default.** A company skill that explicitly supersedes `samber\u002Fcc-skills-golang@golang-testing` skill takes precedence.\n\n**Dependencies:**\n\n- gotests: `go install github.com\u002Fcweill\u002Fgotests\u002Fgotests@latest`\n\n# Go Testing Best Practices\n\nThis skill guides the creation of production-ready tests for Go applications. Follow these principles to write maintainable, fast, and reliable tests.\n\n## Best Practices Summary\n\n1. Table-driven tests MUST use named subtests -- every test case needs a `name` field passed to `t.Run`\n2. Integration tests MUST use build tags (`\u002F\u002Fgo:build integration`) to separate from unit tests\n3. Tests MUST NOT depend on execution order -- each test MUST be independently runnable\n4. Independent tests SHOULD use `t.Parallel()` when possible\n5. NEVER test implementation details -- test observable behavior and public API contracts\n6. Packages with goroutines SHOULD use `goleak.VerifyTestMain` in `TestMain` to detect goroutine leaks\n7. Use testify as helpers, not a replacement for standard library\n8. Mock interfaces, not concrete types\n9. Keep unit tests fast (\u003C 1ms), use build tags for integration tests\n10. Run tests with race detection in CI\n11. Include examples as executable documentation\n12. Test files MUST be named after the source file under test, not after the function or method being tested\n13. Test functions SHOULD appear in the same order as the functions\u002Fmethods they test in the source file\n\n## Test Structure and Organization\n\n### File Conventions\n\n```go\n\u002F\u002F package_test.go - tests in same package (white-box, access unexported)\npackage mypackage\n\n\u002F\u002F mypackage_test.go - tests in test package (black-box, public API only)\npackage mypackage_test\n```\n\nName the test file after the source file it tests, not after the function or method under test. Go's convention is one test file per source file (`foo.go` -> `foo_test.go`), because tools (`go test`, coverage reports, IDE \"jump to test\" navigation, `gotests`) and reviewers all resolve tests by source file, not by symbol. A source file usually declares several functions\u002Fmethods; splitting its tests by symbol name scatters them across many files and breaks that file-to-file mapping.\n\n```\n\u002F\u002F ✓ Good — one test file per source file\nhelloworld.go       -> helloworld_test.go   \u002F\u002F contains TestHelloWorld, TestAbcd, TestXyz, ...\n\n\u002F\u002F ✗ Bad — test file named after the function\u002Fmethod instead of the source file\nhelloworld.go       -> abcd_test.go         \u002F\u002F wrong: should be helloworld_test.go\n```\n\nException: very large source files MAY be split into multiple `_test.go` files by concern (e.g. `foo_test.go` + `foo_edgecases_test.go`), but each split file's name MUST still be derived from the source file name, never from an individual function name. Prefer keeping a single `_test.go` file per source file even when it grows large — splitting adds navigation overhead and is rarely worth it; reach for the exception only when a single file becomes genuinely unwieldy to browse or review.\n\nWithin a test file, order test functions to match the order their tested functions\u002Fmethods appear in the source file. A reader (human or agent) scrolling `foo.go` alongside `foo_test.go` can then find the matching test by position instead of searching; drift between the two orderings compounds every time either file grows.\n\n### Naming Conventions\n\n```go\nfunc TestAdd(t *testing.T) { ... }               \u002F\u002F function test\nfunc TestMyStruct_MyMethod(t *testing.T) { ... } \u002F\u002F method test\nfunc BenchmarkAdd(b *testing.B) { ... }          \u002F\u002F benchmark\nfunc ExampleAdd() { ... }                        \u002F\u002F example\nfunc FuzzAdd(f *testing.F) { ... }               \u002F\u002F fuzz test\n```\n\n## Table-Driven Tests\n\nTable-driven tests are the idiomatic Go way to test multiple scenarios. Always name each test case.\n\n```go\nfunc TestCalculatePrice(t *testing.T) {\n    tests := []struct {\n        name     string\n        quantity int\n        unitPrice float64\n        expected  float64\n    }{\n        {\n            name:      \"single item\",\n            quantity:  1,\n            unitPrice: 10.0,\n            expected:  10.0,\n        },\n        {\n            name:      \"bulk discount - 100 items\",\n            quantity:  100,\n            unitPrice: 10.0,\n            expected:  900.0, \u002F\u002F 10% discount\n        },\n        {\n            name:      \"zero quantity\",\n            quantity:  0,\n            unitPrice: 10.0,\n            expected:  0.0,\n        },\n    }\n\n    for _, tt := range tests {\n        t.Run(tt.name, func(t *testing.T) {\n            got := CalculatePrice(tt.quantity, tt.unitPrice)\n            if got != tt.expected {\n                t.Errorf(\"CalculatePrice(%d, %.2f) = %.2f, want %.2f\",\n                    tt.quantity, tt.unitPrice, got, tt.expected)\n            }\n        })\n    }\n}\n```\n\n## Common Pitfall: Assert Scope Leaking into Subtests\n\nNever create a testify `assert`\u002F`require` instance in the parent test function and reuse it inside `t.Run` closures. `assert.New(t)` captures the exact `*testing.T` it was built with, so if that `t` belongs to the parent, every failure raised inside the subtest gets attributed to the *parent* test in `go test` output — the failing subtest itself still reports `--- PASS`, silently hiding which case broke. This happens whether or not the subtest calls `t.Parallel()`.\n\n```go\n\u002F\u002F WRONG -- `is` is bound to the parent's t\nfunc TestCalculatePrice(t *testing.T) {\n    is := assert.New(t)\n    for _, tt := range tests {\n        t.Run(tt.name, func(t *testing.T) {\n            is.Equal(tt.expected, CalculatePrice(tt.quantity, tt.unitPrice)) \u002F\u002F misattributed on failure\n        })\n    }\n}\n\n\u002F\u002F RIGHT -- each subtest builds its own instance from its own t\nfunc TestCalculatePrice(t *testing.T) {\n    for _, tt := range tests {\n        t.Run(tt.name, func(t *testing.T) {\n            is := assert.New(t)\n            is.Equal(tt.expected, CalculatePrice(tt.quantity, tt.unitPrice))\n        })\n    }\n}\n```\n\nVerify with a deliberately-broken case: if `go test -v -run TestName` shows `--- FAIL: TestName` but every `--- PASS: TestName\u002Fsubtest_name` line still says PASS, the assert scope is leaking.\n\n## Unit Tests\n\nUnit tests should be fast (\u003C 1ms), isolated (no external dependencies), and deterministic.\n\n## Testing HTTP Handlers\n\nUse `httptest` for handler tests with table-driven patterns. See [HTTP Testing](.\u002Freferences\u002Fhttp-testing.md) for examples with request\u002Fresponse bodies, query parameters, headers, and status code assertions.\n\n## Goroutine Leak Detection with goleak\n\nUse `go.uber.org\u002Fgoleak` to detect leaking goroutines, especially for concurrent code:\n\n```go\nimport (\n    \"testing\"\n    \"go.uber.org\u002Fgoleak\"\n)\n\nfunc TestMain(m *testing.M) {\n    goleak.VerifyTestMain(m)\n}\n```\n\nTo exclude specific goroutine stacks (for known leaks or library goroutines):\n\n```go\nfunc TestMain(m *testing.M) {\n    goleak.VerifyTestMain(m,\n        goleak.IgnoreCurrent(),\n    )\n}\n```\n\nOr per-test:\n\n```go\nfunc TestWorkerPool(t *testing.T) {\n    defer goleak.VerifyNone(t)\n    \u002F\u002F ... test code ...\n}\n```\n\n## testing\u002Fsynctest for Deterministic Goroutine Testing\n\n`testing\u002Fsynctest` (Go 1.25+) provides deterministic tests for goroutines, timers, deadlines, and context cancellation. Time advances only when all goroutines are blocked, making ordering predictable.\n\nWhen to use `synctest` instead of real time:\n\n- Testing concurrent code with time-based operations (time.Sleep, time.After, time.Ticker)\n- When race conditions need to be reproducible\n- When tests are flaky due to timing issues\n\n```go\nimport (\n    \"context\"\n    \"testing\"\n    \"testing\u002Fsynctest\"\n    \"time\"\n)\n\nfunc TestContextTimeout(t *testing.T) {\n    synctest.Test(t, func(t *testing.T) {\n        const timeout = 5 * time.Second\n\n        ctx, cancel := context.WithTimeout(t.Context(), timeout)\n        defer cancel()\n\n        time.Sleep(timeout - time.Nanosecond)\n        synctest.Wait()\n        if err := ctx.Err(); err != nil {\n            t.Fatalf(\"before timeout: %v\", err)\n        }\n\n        time.Sleep(time.Nanosecond)\n        synctest.Wait()\n        if err := ctx.Err(); err != context.DeadlineExceeded {\n            t.Fatalf(\"after timeout: got %v, want DeadlineExceeded\", err)\n        }\n    })\n}\n```\n\nUse `synctest.Test` in Go 1.25+ and Go 1.26+. Do not use the old Go 1.24 experimental `synctest.Run` API in Go 1.25+ or Go 1.26+ code. If a module explicitly targets Go 1.24 and opts into `GOEXPERIMENT=synctest`, use the old API only as a compatibility fallback.\n\nKey differences in `synctest`:\n\n- `time.Sleep` advances synthetic time instantly when the goroutine blocks\n- `time.After` fires when synthetic time reaches the duration\n- All goroutines run to blocking points before time advances\n- Test execution is deterministic and repeatable\n\n## Test Timeouts\n\nFor tests that may hang, use a timeout helper that panics with caller location. See [Helpers](.\u002Freferences\u002Fhelpers.md).\n\n## Benchmarks\n\n→ See `samber\u002Fcc-skills-golang@golang-benchmark` skill for advanced benchmarking: `b.Loop()` (Go 1.24+), `benchstat`, profiling from benchmarks, and CI regression detection.\n\nWrite benchmarks to measure performance and detect regressions:\n\n```go\nfunc BenchmarkStringConcatenation(b *testing.B) {\n    b.Run(\"plus-operator\", func(b *testing.B) {\n        for b.Loop() {\n            result := \"a\" + \"b\" + \"c\"\n            _ = result\n        }\n    })\n\n    b.Run(\"strings.Builder\", func(b *testing.B) {\n        for b.Loop() {\n            var builder strings.Builder\n            builder.WriteString(\"a\")\n            builder.WriteString(\"b\")\n            builder.WriteString(\"c\")\n            _ = builder.String()\n        }\n    })\n}\n```\n\nBenchmarks with different input sizes:\n\n```go\nfunc BenchmarkFibonacci(b *testing.B) {\n    sizes := []int{10, 20, 30}\n    for _, size := range sizes {\n        b.Run(fmt.Sprintf(\"n=%d\", size), func(b *testing.B) {\n            b.ReportAllocs()\n            for b.Loop() {\n                Fibonacci(size)\n            }\n        })\n    }\n}\n```\n\nFor Go 1.24+, new benchmarks should use `b.Loop()`. Use legacy `b.N` loops only when the module targets Go \u003C1.24 or when preserving old benchmark code intentionally.\n\n### Go 1.26+: test artifacts\n\nWhen a test, benchmark, or fuzz target needs to persist files for inspection, use `ArtifactDir()` instead of ad-hoc paths or repo-local output.\n\n```go\nfunc TestRenderGoldenArtifact(t *testing.T) {\n    dir := t.ArtifactDir()\n\n    out := filepath.Join(dir, \"rendered.json\")\n    if err := os.WriteFile(out, renderedBytes, 0o644); err != nil {\n        t.Fatal(err)\n    }\n\n    t.Logf(\"artifact written: %s\", out)\n}\n```\n\nAvailable on `*testing.T`, `*testing.B`, and `*testing.F` in Go 1.26+.\n\n## Parallel Tests\n\nUse `t.Parallel()` to run tests concurrently:\n\n```go\nfunc TestParallelOperations(t *testing.T) {\n    tests := []struct {\n        name string\n        data []byte\n    }{\n        {\"small data\", make([]byte, 1024)},\n        {\"medium data\", make([]byte, 1024*1024)},\n    }\n\n    for _, tt := range tests {\n        t.Run(tt.name, func(t *testing.T) {\n            t.Parallel()\n            is := assert.New(t)\n\n            result := Process(tt.data)\n            is.NotNil(result)\n        })\n    }\n}\n```\n\n## Fuzzing\n\nUse fuzzing to find edge cases and bugs:\n\n```go\nfunc FuzzReverse(f *testing.F) {\n    f.Add(\"hello\")\n    f.Add(\"\")\n    f.Add(\"a\")\n\n    f.Fuzz(func(t *testing.T, input string) {\n        reversed := Reverse(input)\n        doubleReversed := Reverse(reversed)\n        if input != doubleReversed {\n            t.Errorf(\"Reverse(Reverse(%q)) = %q, want %q\", input, doubleReversed, input)\n        }\n    })\n}\n```\n\n## Examples as Documentation\n\nExamples are executable documentation verified by `go test`:\n\n```go\nfunc ExampleCalculatePrice() {\n    price := CalculatePrice(100, 10.0)\n    fmt.Printf(\"Price: %.2f\\n\", price)\n    \u002F\u002F Output: Price: 900.00\n}\n\nfunc ExampleCalculatePrice_singleItem() {\n    price := CalculatePrice(1, 25.50)\n    fmt.Printf(\"Price: %.2f\\n\", price)\n    \u002F\u002F Output: Price: 25.50\n}\n```\n\n## Code Coverage\n\n```bash\n# Generate coverage file\ngo test -coverprofile=coverage.out .\u002F...\n\n# View coverage in HTML\ngo tool cover -html=coverage.out\n\n# Coverage by function\ngo tool cover -func=coverage.out\n\n# Total coverage percentage\ngo tool cover -func=coverage.out | grep total\n```\n\n## Integration Tests\n\nUse build tags to separate integration tests from unit tests:\n\n```go\n\u002F\u002Fgo:build integration\n\npackage mypackage\n\nfunc TestDatabaseIntegration(t *testing.T) {\n    db, err := sql.Open(\"postgres\", os.Getenv(\"DATABASE_URL\"))\n    if err != nil {\n        t.Fatal(err)\n    }\n    defer db.Close()\n\n    \u002F\u002F Test real database operations\n}\n```\n\nRun integration tests separately:\n\n```bash\ngo test -tags=integration .\u002F...\n```\n\nFor Docker Compose fixtures, SQL schemas, and integration test suites, see [Integration Testing](.\u002Freferences\u002Fintegration-testing.md).\n\n## Mocking\n\nMock interfaces, not concrete types. Define interfaces where consumed, then create mock implementations.\n\nFor mock patterns, test fixtures, and time mocking, see [Mocking](.\u002Freferences\u002Fmocking.md).\n\n## Enforce with Linters\n\nMany test best practices are enforced automatically by linters: `thelper`, `paralleltest`, `testifylint`. See the `samber\u002Fcc-skills-golang@golang-lint` skill for configuration and usage.\n\n## Cross-References\n\n- -> See `samber\u002Fcc-skills-golang@golang-stretchr-testify` skill for detailed testify API (assert, require, mock, suite)\n- -> See `samber\u002Fcc-skills-golang@golang-database` skill (testing.md) for database integration test patterns\n- -> See `samber\u002Fcc-skills-golang@golang-concurrency` skill for goroutine leak detection with goleak\n- -> See `samber\u002Fcc-skills-golang@golang-continuous-integration` skill for CI test configuration and GitHub Actions workflows\n- -> See `samber\u002Fcc-skills-golang@golang-lint` skill for testifylint and paralleltest configuration\n- -> See `samber\u002Fcc-skills-golang@golang-continuous-integration` skill for automated AI-driven code review in CI using these guidelines\n\n## Quick Reference\n\n```bash\ngo test .\u002F...                          # all tests\ngo test -run TestName .\u002F...            # specific test by exact name\ngo test -run TestName\u002Fsubtest .\u002F...    # subtests within a test\ngo test -run 'Test(Add|Sub)' .\u002F...     # multiple tests (regexp OR)\ngo test -run 'Test[A-Z]' .\u002F...         # tests starting with capital letter\ngo test -run 'TestUser.*' .\u002F...        # tests matching prefix\ngo test -run '.*Validation.*' .\u002F...    # tests containing substring\ngo test -run TestName\u002F. .\u002F...          # all subtests of TestName\ngo test -run '\u002F(unit|integration)' .\u002F... # filter by subtest name\ngo test -race .\u002F...                    # race detection\ngo test -cover .\u002F...                   # coverage summary\ngo test -bench=. -benchmem .\u002F...       # benchmarks\ngo test -fuzz=FuzzName .\u002F...           # fuzzing\ngo test -tags=integration .\u002F...        # integration tests\n```\n","**Persona:** You are a Go engineer who treats tests as executable specifications. You write tests to constrain behavior, not to hit coverage targets.\n\n**Thinking mode:** Use `ultrathink` for test strategy design and failure analysis. Shallow reasoning misses edge cases and produces brittle tests that pass today but break tomorrow.\n\n**Orchestration mode:** Use `ultracode` for auditing a large test suite — orchestrate the three sub-agents described in Audit mode (unit quality and coverage gaps, integration isolation, goroutine\u002Frace issues) and merge their findings into one gap report.\n\n**Modes:**\n\n- **Write mode** — generating new tests for existing or new code. Work sequentially through the code under test; use `gotests` to scaffold table-driven tests, then enrich with edge cases and error paths.\n- **Review mode** — reviewing a PR's test changes. Focus on the diff: check coverage of new behaviour, assertion quality, table-driven structure, and absence of flakiness patterns. Sequential.\n- **Audit mode** — auditing an existing test suite for gaps, flakiness, or bad patterns (order-dependent tests, missing `t.Parallel()`, implementation-detail coupling). Launch up to 3 parallel sub-agents split by concern: (1) unit test quality and coverage gaps, (2) integration test isolation and build tags, (3) goroutine leaks and race conditions.\n- **Debug mode** — a test is failing or flaky. Work sequentially: reproduce reliably, isolate the failing assertion, trace the root cause in production code or test setup.\n\n> **Community default.** A company skill that explicitly supersedes `samber\u002Fcc-skills-golang@golang-testing` skill takes precedence.\n\n**Dependencies:**\n\n- gotests: `go install github.com\u002Fcweill\u002Fgotests\u002Fgotests@latest`\n\n# Go Testing Best Practices\n\nThis skill guides the creation of production-ready tests for Go applications. Follow these principles to write maintainable, fast, and reliable tests.\n\n## Best Practices Summary\n\n1. Table-driven tests MUST use named subtests -- every test case needs a `name` field passed to `t.Run`\n2. Integration tests MUST use build tags (`\u002F\u002Fgo:build integration`) to separate from unit tests\n3. Tests MUST NOT depend on execution order -- each test MUST be independently runnable\n4. Independent tests SHOULD use `t.Parallel()` when possible\n5. NEVER test implementation details -- test observable behavior and public API contracts\n6. Packages with goroutines SHOULD use `goleak.VerifyTestMain` in `TestMain` to detect goroutine leaks\n7. Use testify as helpers, not a replacement for standard library\n8. Mock interfaces, not concrete types\n9. Keep unit tests fast (\u003C 1ms), use build tags for integration tests\n10. Run tests with race detection in CI\n11. Include examples as executable documentation\n12. Test files MUST be named after the source file under test, not after the function or method being tested\n13. Test functions SHOULD appear in the same order as the functions\u002Fmethods they test in the source file\n\n## Test Structure and Organization\n\n### File Conventions\n\n```go\n\u002F\u002F package_test.go - tests in same package (white-box, access unexported)\npackage mypackage\n\n\u002F\u002F mypackage_test.go - tests in test package (black-box, public API only)\npackage mypackage_test\n```\n\nName the test file after the source file it tests, not after the function or method under test. Go's convention is one test file per source file (`foo.go` -> `foo_test.go`), because tools (`go test`, coverage reports, IDE \"jump to test\" navigation, `gotests`) and reviewers all resolve tests by source file, not by symbol. A source file usually declares several functions\u002Fmethods; splitting its tests by symbol name scatters them across many files and breaks that file-to-file mapping.\n\n```\n\u002F\u002F ✓ Good — one test file per source file\nhelloworld.go       -> helloworld_test.go   \u002F\u002F contains TestHelloWorld, TestAbcd, TestXyz, ...\n\n\u002F\u002F ✗ Bad — test file named after the function\u002Fmethod instead of the source file\nhelloworld.go       -> abcd_test.go         \u002F\u002F wrong: should be helloworld_test.go\n```\n\nException: very large source files MAY be split into multiple `_test.go` files by concern (e.g. `foo_test.go` + `foo_edgecases_test.go`), but each split file's name MUST still be derived from the source file name, never from an individual function name. Prefer keeping a single `_test.go` file per source file even when it grows large — splitting adds navigation overhead and is rarely worth it; reach for the exception only when a single file becomes genuinely unwieldy to browse or review.\n\nWithin a test file, order test functions to match the order their tested functions\u002Fmethods appear in the source file. A reader (human or agent) scrolling `foo.go` alongside `foo_test.go` can then find the matching test by position instead of searching; drift between the two orderings compounds every time either file grows.\n\n### Naming Conventions\n\n```go\nfunc TestAdd(t *testing.T) { ... }               \u002F\u002F function test\nfunc TestMyStruct_MyMethod(t *testing.T) { ... } \u002F\u002F method test\nfunc BenchmarkAdd(b *testing.B) { ... }          \u002F\u002F benchmark\nfunc ExampleAdd() { ... }                        \u002F\u002F example\nfunc FuzzAdd(f *testing.F) { ... }               \u002F\u002F fuzz test\n```\n\n## Table-Driven Tests\n\nTable-driven tests are the idiomatic Go way to test multiple scenarios. Always name each test case.\n\n```go\nfunc TestCalculatePrice(t *testing.T) {\n    tests := []struct {\n        name     string\n        quantity int\n        unitPrice float64\n        expected  float64\n    }{\n        {\n            name:      \"single item\",\n            quantity:  1,\n            unitPrice: 10.0,\n            expected:  10.0,\n        },\n        {\n            name:      \"bulk discount - 100 items\",\n            quantity:  100,\n            unitPrice: 10.0,\n            expected:  900.0, \u002F\u002F 10% discount\n        },\n        {\n            name:      \"zero quantity\",\n            quantity:  0,\n            unitPrice: 10.0,\n            expected:  0.0,\n        },\n    }\n\n    for _, tt := range tests {\n        t.Run(tt.name, func(t *testing.T) {\n            got := CalculatePrice(tt.quantity, tt.unitPrice)\n            if got != tt.expected {\n                t.Errorf(\"CalculatePrice(%d, %.2f) = %.2f, want %.2f\",\n                    tt.quantity, tt.unitPrice, got, tt.expected)\n            }\n        })\n    }\n}\n```\n\n## Common Pitfall: Assert Scope Leaking into Subtests\n\nNever create a testify `assert`\u002F`require` instance in the parent test function and reuse it inside `t.Run` closures. `assert.New(t)` captures the exact `*testing.T` it was built with, so if that `t` belongs to the parent, every failure raised inside the subtest gets attributed to the *parent* test in `go test` output — the failing subtest itself still reports `--- PASS`, silently hiding which case broke. This happens whether or not the subtest calls `t.Parallel()`.\n\n```go\n\u002F\u002F WRONG -- `is` is bound to the parent's t\nfunc TestCalculatePrice(t *testing.T) {\n    is := assert.New(t)\n    for _, tt := range tests {\n        t.Run(tt.name, func(t *testing.T) {\n            is.Equal(tt.expected, CalculatePrice(tt.quantity, tt.unitPrice)) \u002F\u002F misattributed on failure\n        })\n    }\n}\n\n\u002F\u002F RIGHT -- each subtest builds its own instance from its own t\nfunc TestCalculatePrice(t *testing.T) {\n    for _, tt := range tests {\n        t.Run(tt.name, func(t *testing.T) {\n            is := assert.New(t)\n            is.Equal(tt.expected, CalculatePrice(tt.quantity, tt.unitPrice))\n        })\n    }\n}\n```\n\nVerify with a deliberately-broken case: if `go test -v -run TestName` shows `--- FAIL: TestName` but every `--- PASS: TestName\u002Fsubtest_name` line still says PASS, the assert scope is leaking.\n\n## Unit Tests\n\nUnit tests should be fast (\u003C 1ms), isolated (no external dependencies), and deterministic.\n\n## Testing HTTP Handlers\n\nUse `httptest` for handler tests with table-driven patterns. See [HTTP Testing](.\u002Freferences\u002Fhttp-testing.md) for examples with request\u002Fresponse bodies, query parameters, headers, and status code assertions.\n\n## Goroutine Leak Detection with goleak\n\nUse `go.uber.org\u002Fgoleak` to detect leaking goroutines, especially for concurrent code:\n\n```go\nimport (\n    \"testing\"\n    \"go.uber.org\u002Fgoleak\"\n)\n\nfunc TestMain(m *testing.M) {\n    goleak.VerifyTestMain(m)\n}\n```\n\nTo exclude specific goroutine stacks (for known leaks or library goroutines):\n\n```go\nfunc TestMain(m *testing.M) {\n    goleak.VerifyTestMain(m,\n        goleak.IgnoreCurrent(),\n    )\n}\n```\n\nOr per-test:\n\n```go\nfunc TestWorkerPool(t *testing.T) {\n    defer goleak.VerifyNone(t)\n    \u002F\u002F ... test code ...\n}\n```\n\n## testing\u002Fsynctest for Deterministic Goroutine Testing\n\n`testing\u002Fsynctest` (Go 1.25+) provides deterministic tests for goroutines, timers, deadlines, and context cancellation. Time advances only when all goroutines are blocked, making ordering predictable.\n\nWhen to use `synctest` instead of real time:\n\n- Testing concurrent code with time-based operations (time.Sleep, time.After, time.Ticker)\n- When race conditions need to be reproducible\n- When tests are flaky due to timing issues\n\n```go\nimport (\n    \"context\"\n    \"testing\"\n    \"testing\u002Fsynctest\"\n    \"time\"\n)\n\nfunc TestContextTimeout(t *testing.T) {\n    synctest.Test(t, func(t *testing.T) {\n        const timeout = 5 * time.Second\n\n        ctx, cancel := context.WithTimeout(t.Context(), timeout)\n        defer cancel()\n\n        time.Sleep(timeout - time.Nanosecond)\n        synctest.Wait()\n        if err := ctx.Err(); err != nil {\n            t.Fatalf(\"before timeout: %v\", err)\n        }\n\n        time.Sleep(time.Nanosecond)\n        synctest.Wait()\n        if err := ctx.Err(); err != context.DeadlineExceeded {\n            t.Fatalf(\"after timeout: got %v, want DeadlineExceeded\", err)\n        }\n    })\n}\n```\n\nUse `synctest.Test` in Go 1.25+ and Go 1.26+. Do not use the old Go 1.24 experimental `synctest.Run` API in Go 1.25+ or Go 1.26+ code. If a module explicitly targets Go 1.24 and opts into `GOEXPERIMENT=synctest`, use the old API only as a compatibility fallback.\n\nKey differences in `synctest`:\n\n- `time.Sleep` advances synthetic time instantly when the goroutine blocks\n- `time.After` fires when synthetic time reaches the duration\n- All goroutines run to blocking points before time advances\n- Test execution is deterministic and repeatable\n\n## Test Timeouts\n\nFor tests that may hang, use a timeout helper that panics with caller location. See [Helpers](.\u002Freferences\u002Fhelpers.md).\n\n## Benchmarks\n\n→ See `samber\u002Fcc-skills-golang@golang-benchmark` skill for advanced benchmarking: `b.Loop()` (Go 1.24+), `benchstat`, profiling from benchmarks, and CI regression detection.\n\nWrite benchmarks to measure performance and detect regressions:\n\n```go\nfunc BenchmarkStringConcatenation(b *testing.B) {\n    b.Run(\"plus-operator\", func(b *testing.B) {\n        for b.Loop() {\n            result := \"a\" + \"b\" + \"c\"\n            _ = result\n        }\n    })\n\n    b.Run(\"strings.Builder\", func(b *testing.B) {\n        for b.Loop() {\n            var builder strings.Builder\n            builder.WriteString(\"a\")\n            builder.WriteString(\"b\")\n            builder.WriteString(\"c\")\n            _ = builder.String()\n        }\n    })\n}\n```\n\nBenchmarks with different input sizes:\n\n```go\nfunc BenchmarkFibonacci(b *testing.B) {\n    sizes := []int{10, 20, 30}\n    for _, size := range sizes {\n        b.Run(fmt.Sprintf(\"n=%d\", size), func(b *testing.B) {\n            b.ReportAllocs()\n            for b.Loop() {\n                Fibonacci(size)\n            }\n        })\n    }\n}\n```\n\nFor Go 1.24+, new benchmarks should use `b.Loop()`. Use legacy `b.N` loops only when the module targets Go \u003C1.24 or when preserving old benchmark code intentionally.\n\n### Go 1.26+: test artifacts\n\nWhen a test, benchmark, or fuzz target needs to persist files for inspection, use `ArtifactDir()` instead of ad-hoc paths or repo-local output.\n\n```go\nfunc TestRenderGoldenArtifact(t *testing.T) {\n    dir := t.ArtifactDir()\n\n    out := filepath.Join(dir, \"rendered.json\")\n    if err := os.WriteFile(out, renderedBytes, 0o644); err != nil {\n        t.Fatal(err)\n    }\n\n    t.Logf(\"artifact written: %s\", out)\n}\n```\n\nAvailable on `*testing.T`, `*testing.B`, and `*testing.F` in Go 1.26+.\n\n## Parallel Tests\n\nUse `t.Parallel()` to run tests concurrently:\n\n```go\nfunc TestParallelOperations(t *testing.T) {\n    tests := []struct {\n        name string\n        data []byte\n    }{\n        {\"small data\", make([]byte, 1024)},\n        {\"medium data\", make([]byte, 1024*1024)},\n    }\n\n    for _, tt := range tests {\n        t.Run(tt.name, func(t *testing.T) {\n            t.Parallel()\n            is := assert.New(t)\n\n            result := Process(tt.data)\n            is.NotNil(result)\n        })\n    }\n}\n```\n\n## Fuzzing\n\nUse fuzzing to find edge cases and bugs:\n\n```go\nfunc FuzzReverse(f *testing.F) {\n    f.Add(\"hello\")\n    f.Add(\"\")\n    f.Add(\"a\")\n\n    f.Fuzz(func(t *testing.T, input string) {\n        reversed := Reverse(input)\n        doubleReversed := Reverse(reversed)\n        if input != doubleReversed {\n            t.Errorf(\"Reverse(Reverse(%q)) = %q, want %q\", input, doubleReversed, input)\n        }\n    })\n}\n```\n\n## Examples as Documentation\n\nExamples are executable documentation verified by `go test`:\n\n```go\nfunc ExampleCalculatePrice() {\n    price := CalculatePrice(100, 10.0)\n    fmt.Printf(\"Price: %.2f\\n\", price)\n    \u002F\u002F Output: Price: 900.00\n}\n\nfunc ExampleCalculatePrice_singleItem() {\n    price := CalculatePrice(1, 25.50)\n    fmt.Printf(\"Price: %.2f\\n\", price)\n    \u002F\u002F Output: Price: 25.50\n}\n```\n\n## Code Coverage\n\n```bash\n# Generate coverage file\ngo test -coverprofile=coverage.out .\u002F...\n\n# View coverage in HTML\ngo tool cover -html=coverage.out\n\n# Coverage by function\ngo tool cover -func=coverage.out\n\n# Total coverage percentage\ngo tool cover -func=coverage.out | grep total\n```\n\n## Integration Tests\n\nUse build tags to separate integration tests from unit tests:\n\n```go\n\u002F\u002Fgo:build integration\n\npackage mypackage\n\nfunc TestDatabaseIntegration(t *testing.T) {\n    db, err := sql.Open(\"postgres\", os.Getenv(\"DATABASE_URL\"))\n    if err != nil {\n        t.Fatal(err)\n    }\n    defer db.Close()\n\n    \u002F\u002F Test real database operations\n}\n```\n\nRun integration tests separately:\n\n```bash\ngo test -tags=integration .\u002F...\n```\n\nFor Docker Compose fixtures, SQL schemas, and integration test suites, see [Integration Testing](.\u002Freferences\u002Fintegration-testing.md).\n\n## Mocking\n\nMock interfaces, not concrete types. Define interfaces where consumed, then create mock implementations.\n\nFor mock patterns, test fixtures, and time mocking, see [Mocking](.\u002Freferences\u002Fmocking.md).\n\n## Enforce with Linters\n\nMany test best practices are enforced automatically by linters: `thelper`, `paralleltest`, `testifylint`. See the `samber\u002Fcc-skills-golang@golang-lint` skill for configuration and usage.\n\n## Cross-References\n\n- -> See `samber\u002Fcc-skills-golang@golang-stretchr-testify` skill for detailed testify API (assert, require, mock, suite)\n- -> See `samber\u002Fcc-skills-golang@golang-database` skill (testing.md) for database integration test patterns\n- -> See `samber\u002Fcc-skills-golang@golang-concurrency` skill for goroutine leak detection with goleak\n- -> See `samber\u002Fcc-skills-golang@golang-continuous-integration` skill for CI test configuration and GitHub Actions workflows\n- -> See `samber\u002Fcc-skills-golang@golang-lint` skill for testifylint and paralleltest configuration\n- -> See `samber\u002Fcc-skills-golang@golang-continuous-integration` skill for automated AI-driven code review in CI using these guidelines\n\n## Quick Reference\n\n```bash\ngo test .\u002F...                          # all tests\ngo test -run TestName .\u002F...            # specific test by exact name\ngo test -run TestName\u002Fsubtest .\u002F...    # subtests within a test\ngo test -run 'Test(Add|Sub)' .\u002F...     # multiple tests (regexp OR)\ngo test -run 'Test[A-Z]' .\u002F...         # tests starting with capital letter\ngo test -run 'TestUser.*' .\u002F...        # tests matching prefix\ngo test -run '.*Validation.*' .\u002F...    # tests containing substring\ngo test -run TestName\u002F. .\u002F...          # all subtests of TestName\ngo test -run '\u002F(unit|integration)' .\u002F... # filter by subtest name\ngo test -race .\u002F...                    # race detection\ngo test -cover .\u002F...                   # coverage summary\ngo test -bench=. -benchmem .\u002F...       # benchmarks\ngo test -fuzz=FuzzName .\u002F...           # fuzzing\ngo test -tags=integration .\u002F...        # integration tests\n```\n",{"name":5,"license":15,"metadata":24,"description":7,"allowed-tools":38,"compatibility":39,"user-invocable":40},{"author":25,"version":26,"openclaw":27},"samber","1.2.5",{"emoji":28,"install":29,"homepage":35,"requires":36},"🧪",[30],{"bins":31,"kind":33,"package":34},[32],"gotests","go","github.com\u002Fcweill\u002Fgotests\u002Fgotests@latest","https:\u002F\u002Fgithub.com\u002Fsamber\u002Fcc-skills-golang",{"bins":37},[33,32],"Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent Bash(gotests:*) AskUserQuestion","Designed for Claude Code or similar AI coding agents, and for projects using Golang.",true,"main","a93764baed707eda5a68d91e19e5719368e6335e","skills-backup\u002Fskills\u002Fgolang-testing",0,"https:\u002F\u002Fgithub.com\u002FCCH-HQ\u002Fcchp-automation","https:\u002F\u002Fgithub.com\u002FCCH-HQ","https:\u002F\u002Fclaude-code-hub.app\u002F","2026-11-09 20:50:54",{"source":8,"skillName":5,"commands":50,"prompt":60,"zipAvailable":40},[51,54,57],{"tool":52,"command":53},"npx","npx skills add CCH-HQ\u002Fcchp-automation --skill golang-testing",{"tool":55,"command":56},"bunx","bunx skills add CCH-HQ\u002Fcchp-automation --skill golang-testing",{"tool":58,"command":59},"pnpm","pnpm dlx skills add CCH-HQ\u002Fcchp-automation --skill golang-testing","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FCCH-HQ\u002Fcchp-automation\u002Fblob\u002Fmain\u002Fskills-backup\u002Fskills\u002Fgolang-testing\u002FSKILL.md",[62,68,72,76,80],{"path":63,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":66,"sourceHtmlUrl":67},"evals\u002Fevals.json","REFERENCE","参考文档",21978,"https:\u002F\u002Fgithub.com\u002FCCH-HQ\u002Fcchp-automation\u002Fblob\u002Fmain\u002Fskills-backup\u002Fskills\u002Fgolang-testing\u002Fevals\u002Fevals.json",{"path":69,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":70,"sourceHtmlUrl":71},"references\u002Fhelpers.md",1054,"https:\u002F\u002Fgithub.com\u002FCCH-HQ\u002Fcchp-automation\u002Fblob\u002Fmain\u002Fskills-backup\u002Fskills\u002Fgolang-testing\u002Freferences\u002Fhelpers.md",{"path":73,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":74,"sourceHtmlUrl":75},"references\u002Fhttp-testing.md",2268,"https:\u002F\u002Fgithub.com\u002FCCH-HQ\u002Fcchp-automation\u002Fblob\u002Fmain\u002Fskills-backup\u002Fskills\u002Fgolang-testing\u002Freferences\u002Fhttp-testing.md",{"path":77,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":78,"sourceHtmlUrl":79},"references\u002Fintegration-testing.md",4166,"https:\u002F\u002Fgithub.com\u002FCCH-HQ\u002Fcchp-automation\u002Fblob\u002Fmain\u002Fskills-backup\u002Fskills\u002Fgolang-testing\u002Freferences\u002Fintegration-testing.md",{"path":81,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":82,"sourceHtmlUrl":83},"references\u002Fmocking.md",4573,"https:\u002F\u002Fgithub.com\u002FCCH-HQ\u002Fcchp-automation\u002Fblob\u002Fmain\u002Fskills-backup\u002Fskills\u002Fgolang-testing\u002Freferences\u002Fmocking.md",[85,92,99,106,113,120],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M79B44RKSB6Z0GENGYFCCZYA","writing-skills","Use when creating new skills, editing existing skills, or verifying skills work before deployment","https:\u002F\u002Fgithub.com\u002FCCH-HQ\u002Fcchp-automation\u002Fblob\u002Fmain\u002Fskills-backup\u002Fskills\u002Fwriting-skills\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":19},"01M79B410BHDSNHZ7MKAYXWJHS","writing-plans","Use when you have a spec or requirements for a multi-step task, before touching code","https:\u002F\u002Fgithub.com\u002FCCH-HQ\u002Fcchp-automation\u002Fblob\u002Fmain\u002Fskills-backup\u002Fskills\u002Fwriting-plans\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":19},"01M79B3XK29MCD5HGD50YGYXQZ","wizard","Generate an interactive bash wizard that walks a human through steps only they can perform. Use when provisioning infrastructure, setting up credentials or CI secrets, walking an unfamiliar third-party dashboard, or running a one-off migration or cutover. Don't invoke this for steps the agent can perform itself.","https:\u002F\u002Fgithub.com\u002FCCH-HQ\u002Fcchp-automation\u002Fblob\u002Fmain\u002Fskills-backup\u002Fskills\u002Fwizard\u002FSKILL.md",[],[],{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":19},"01M79B3TFQEXXM2KK5V44H64DV","wayfinder","Plan a huge chunk of work — more than one agent session can hold — as a shared map of decision tickets on your issue tracker, and resolve them one at a time until the way to the destination is clear.","https:\u002F\u002Fgithub.com\u002FCCH-HQ\u002Fcchp-automation\u002Fblob\u002Fmain\u002Fskills-backup\u002Fskills\u002Fwayfinder\u002FSKILL.md",[],[],{"skillNo":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":119,"publishedAt":19},"01M79B3Q3WTMJDM6NNGG1X4NYK","verification-before-completion","Use 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 always","https:\u002F\u002Fgithub.com\u002FCCH-HQ\u002Fcchp-automation\u002Fblob\u002Fmain\u002Fskills-backup\u002Fskills\u002Fverification-before-completion\u002FSKILL.md",[],[],{"skillNo":121,"name":122,"nameZh":6,"description":123,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":124,"categories":125,"keywords":126,"publishedAt":19},"01M79B3GW8YCKT7W489HKWFMNC","vercel-react-best-practices","React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React\u002FNext.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.","https:\u002F\u002Fgithub.com\u002FCCH-HQ\u002Fcchp-automation\u002Fblob\u002Fmain\u002Fskills-backup\u002Fskills\u002Fvercel-react-best-practices\u002FSKILL.md",[],[]]