go-testing-mistakes
Guides the agent to avoid common Go testing mistakes when writing or reviewing test code. Covers test categorization (build tags, env vars, short mode), race detection, test execution modes (parallel, shuffle), table-driven tests, avoiding sleeps in tests, handling the time API deterministically, using httptest/iotest utility packages, writing accurate benchmarks, and leveraging Go testing features (coverage, external test packages, utility functions, setup/teardown). Use when writing, reviewing, or refactoring Go tests, benchmarks, or test helpers, or when setting up CI test pipelines for Go projects.
v0lka · 已有静态检查记录
安装与使用
运行命令前先阅读来源与依赖说明。复制命令不会自动安装或执行。
npx skills add v0lka/skills --skill go-testing-mistakes技能说明
name: go-testing-mistakes description: > Guides the agent to avoid common Go testing mistakes when writing or reviewing test code. Covers test categorization (build tags, env vars, short mode), race detection, test execution modes (parallel, shuffle), table-driven tests, avoiding sleeps in tests, handling the time API deterministically, using httptest/iotest utility packages, writing accurate benchmarks, and leveraging Go testing features (coverage, external test packages, utility functions, setup/teardown). Use when writing, reviewing, or refactoring Go tests, benchmarks, or test helpers, or when setting up CI test pipelines for Go projects.
Go Testing Mistakes
Rules and patterns for robust, accurate Go testing based on common mistakes #82-#90.
1. Categorize Tests (#82)
Rule: Always categorize tests so unit, integration, and long-running tests can be run independently. Use one or more of these three mechanisms.
Build tags (file-level)
Use //go:build tags to separate integration tests from unit tests.
// File: db_test.go
//go:build integration
package db
func TestInsert(t *testing.T) {
// ...
}
go test ./...runs only files without build tags.go test --tags=integration ./...includes files taggedintegration.- To run only integration tests, add
//go:build !integrationto unit test files.
Environment variables (test-level)
Prefer this when you want skipped tests to appear explicitly in output.
func TestInsert(t *testing.T) {
if os.Getenv("INTEGRATION") != "true" {
t.Skip("skipping integration test")
}
// ...
}
Short mode (speed-based)
Use testing.Short() to skip long-running tests during fast feedback loops.
func TestLongRunning(t *testing.T) {
if testing.Short() {
t.Skip("skipping long-running test")
}
// ...
}
Run with go test -short ./....
Combine approaches: Use build tags or env vars for test kind (unit vs integration) and short mode for test speed.
2. Enable the -race Flag (#83)
Rule: Always run go test -race ./... in local development and CI. The race detector finds real data races at runtime with zero false positives.
Overhead: Memory 5-10x, execution 2-20x. Do not enable in production binaries (canary releases excepted).
Key points:
- The race detector can produce false negatives. Loop concurrent test logic to increase detection probability:
func TestDataRace(t *testing.T) {
for i := 0; i < 100; i++ {
// concurrent logic under test
}
}
- To exclude a file from race detection, use
//go:build !race.
3. Use Test Execution Modes (#84)
Parallel execution
Mark independent tests with t.Parallel() to speed up long-running test suites.
func TestA(t *testing.T) {
t.Parallel()
// ...
}
- Sequential tests run first; parallel tests are paused then resumed together.
- Default max parallel =
GOMAXPROCS. Override withgo test -parallel 16 ./....
Shuffle mode
Use -shuffle=on to detect hidden inter-test dependencies.
go test -shuffle=on -v ./...
- Reproduce a specific order with the seed:
go test -shuffle=1636399552801504000 -v ./... - The seed is printed in verbose output.
4. Use Table-Driven Tests (#85)
Rule: When multiple tests share the same structure (call, compare, report), use table-driven tests with subtests.
func TestRemoveNewLineSuffix(t *testing.T) {
tests := map[string]struct {
input string
expected string
}{
"empty": {input: "", expected: ""},
"ending with \\r\\n": {input: "a\r\n", expected: "a"},
"ending with \\n": {input: "a\n", expected: "a"},
"ending with multiple": {input: "a\n\n\n", expected: "a"},
"no newline": {input: "a", expected: "a"},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
got := removeNewLineSuffixes(tt.input)
if got != tt.expected {
t.Errorf("got: %s, expected: %s", got, tt.expected)
}
})
}
}
Parallel subtests: When combining table-driven tests with t.Parallel(), shadow the loop variable to avoid closure capture bugs:
for name, tt := range tests {
tt := tt // shadow to capture current value
t.Run(name, func(t *testing.T) {
t.Parallel()
// use tt safely
})
}
Note: Go 1.22+ fixes the loop variable capture issue, but shadowing remains safe for backward compatibility.
5. Never Sleep in Unit Tests (#86)
Rule: Never use time.Sleep as a synchronization mechanism in tests. It causes flakiness.
Option A: Retry with polling (acceptable)
func assertEventually(t *testing.T, assertion func() bool, maxRetries int, waitTime time.Duration) {
t.Helper()
for i := 0; i < maxRetries; i++ {
if assertion() {
return
}
time.Sleep(waitTime)
}
t.Fatal("assertion never became true")
}
Use short intervals with many retries instead of a single long sleep. Libraries like testify provide Eventually.
Option B: Channel synchronization (preferred)
type publisherMock struct {
ch chan []Foo
}
func (p *publisherMock) Publish(got []Foo) {
p.ch <- got
}
func TestGetBestFoo(t *testing.T) {
mock := publisherMock{ch: make(chan []Foo)}
defer close(mock.ch)
h := Handler{publisher: &mock, n: 2}
foo := h.getBestFoo(42)
// check foo ...
select {
case published := <-mock.ch:
if len(published) != 2 {
t.Fatalf("expected 2, got %d", len(published))
}
case <-time.After(time.Second):
t.Fatal("timed out waiting for publish")
}
}
Prefer synchronization over retries. If synchronization is impossible, reconsider the design.