@srobroek/pi-lang-go 0.0.0-stage → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +94 -0
- package/LICENSE +202 -0
- package/README.md +44 -2
- package/package.json +27 -4
- package/skills/lang-go/SKILL.md +21 -0
- package/skills/lang-go-libraries/SKILL.md +75 -0
- package/skills/lang-go-libraries/references/ai.md +29 -0
- package/skills/lang-go-libraries/references/aws.md +76 -0
- package/skills/lang-go-libraries/references/cli.md +29 -0
- package/skills/lang-go-libraries/references/data.md +46 -0
- package/skills/lang-go-libraries/references/messaging.md +35 -0
- package/skills/lang-go-libraries/references/observability.md +40 -0
- package/skills/lang-go-libraries/references/quality.md +66 -0
- package/skills/lang-go-libraries/references/runtime.md +51 -0
- package/skills/lang-go-libraries/references/security.md +40 -0
- package/skills/lang-go-libraries/references/services.md +53 -0
- package/skills/lang-go-libraries/references/testing.md +73 -0
- package/skills/lang-go-packaging/SKILL.md +118 -0
- package/skills/lang-go-profiling/SKILL.md +63 -0
- package/skills/lang-go-quality/SKILL.md +75 -0
- package/skills/lang-go-testing/SKILL.md +140 -0
- package/skills/lang-go-testing/references/practice.md +293 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: lang-go-profiling
|
|
3
|
+
description: Use for Go profiling and benchmarks (go test -bench, pprof CPU/heap/block profiles, go tool trace, benchstat).
|
|
4
|
+
metadata:
|
|
5
|
+
opencode/autoinvoke: false
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# Go
|
|
9
|
+
|
|
10
|
+
Sources: [Go diagnostics](https://go.dev/doc/diagnostics), [`testing`](https://pkg.go.dev/testing), [`net/http/pprof`](https://pkg.go.dev/net/http/pprof), [benchstat](https://pkg.go.dev/golang.org/x/perf/cmd/benchstat). Checked against `go help testflag` on Go 1.27.
|
|
11
|
+
|
|
12
|
+
Tooling only. The method (target, fixed workload, baseline with variance, one change at a time, re-measure, report) is the `quality-profiling` skill; load it first if it is not loaded.
|
|
13
|
+
|
|
14
|
+
## Benchmarks and profiles from tests
|
|
15
|
+
|
|
16
|
+
```go
|
|
17
|
+
func BenchmarkParse(b *testing.B) {
|
|
18
|
+
in := loadFixture() // setup outside the loop is not timed
|
|
19
|
+
b.ReportAllocs()
|
|
20
|
+
for b.Loop() { // Go 1.24+; older code uses for i := 0; i < b.N; i++
|
|
21
|
+
Parse(in)
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
go test -run='^$' -bench=Parse -benchmem -count=10 > old.txt
|
|
28
|
+
# make the change
|
|
29
|
+
go test -run='^$' -bench=Parse -benchmem -count=10 > new.txt
|
|
30
|
+
benchstat old.txt new.txt # go install golang.org/x/perf/cmd/benchstat@latest
|
|
31
|
+
|
|
32
|
+
go test -run='^$' -bench=Parse -cpuprofile cpu.out -memprofile mem.out
|
|
33
|
+
go test -run='^$' -bench=Parse -blockprofile block.out -mutexprofile mutex.out
|
|
34
|
+
go test -run='^$' -bench=Parse -trace trace.out
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
benchstat reports the change with a confidence interval and marks it `~` when not significant; run `-count` of 10 or more.
|
|
38
|
+
|
|
39
|
+
## Live services
|
|
40
|
+
|
|
41
|
+
```go
|
|
42
|
+
import _ "net/http/pprof" // registers /debug/pprof/ on http.DefaultServeMux; serve it on an internal port only
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
go tool pprof -http=:8081 'http://localhost:6060/debug/pprof/profile?seconds=30' # CPU
|
|
47
|
+
go tool pprof -http=:8081 http://localhost:6060/debug/pprof/heap # live heap (-sample_index=alloc_space for allocations)
|
|
48
|
+
go tool pprof http://localhost:6060/debug/pprof/goroutine # stuck or leaked goroutines
|
|
49
|
+
go tool pprof http://localhost:6060/debug/pprof/block # needs runtime.SetBlockProfileRate; mutex needs SetMutexProfileFraction
|
|
50
|
+
curl -o trace.out 'http://localhost:6060/debug/pprof/trace?seconds=5' && go tool trace trace.out
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Reading pprof
|
|
54
|
+
|
|
55
|
+
`top` / `top -cum` rank by self / cumulative time; `list Func` shows per-line cost; `-http` opens graph, flame graph and source views. Compare runs with `go tool pprof -diff_base old.pprof new.pprof`. The CPU profile shows on-CPU time only; latency spent waiting shows in the block, mutex and goroutine profiles and the execution trace (scheduler, GC, syscalls).
|
|
56
|
+
|
|
57
|
+
## Pitfalls
|
|
58
|
+
|
|
59
|
+
- The compiler removes work whose result is unused; assign results to a package-level sink, or rely on `b.Loop()`, which keeps the loop body's calls alive.
|
|
60
|
+
- `-benchmem` allocations per op often matter more than ns/op: each allocation costs GC time later, outside the benchmark.
|
|
61
|
+
- `GOMAXPROCS` defaults to the cgroup CPU limit on Linux since Go 1.25; benchmark with the same limit as production.
|
|
62
|
+
- CPU profiles of a mostly idle server are empty; profile under load, and use the block, mutex and goroutine profiles for latency.
|
|
63
|
+
- The heap profile's default `inuse_space` shows live memory; switch to `alloc_space` or `alloc_objects` to find allocation churn.
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: lang-go-quality
|
|
3
|
+
description: Use to run Go build, format, lint, vet, go mod tidy, govulncheck and go test -race checks with the project toolchain.
|
|
4
|
+
metadata:
|
|
5
|
+
opencode/autoinvoke: false
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# Go Quality
|
|
9
|
+
|
|
10
|
+
Sources: `go help build`, `go help testflag`, `go help mod tidy`, `go help packages` (Go 1.27), [golangci-lint v2](https://golangci-lint.run/docs/), [govulncheck](https://pkg.go.dev/golang.org/x/vuln/cmd/govulncheck), [race detector](https://go.dev/doc/articles/race_detector).
|
|
11
|
+
|
|
12
|
+
Run the checks through the shell tool from the module root (the directory with
|
|
13
|
+
`go.mod`), in this order. Stop at the first failing step, fix it, rerun that step,
|
|
14
|
+
then continue; later steps on code that does not build only add noise.
|
|
15
|
+
|
|
16
|
+
| Step | Command |
|
|
17
|
+
| --- | --- |
|
|
18
|
+
| Build | `go build ./...` |
|
|
19
|
+
| Format check | `golangci-lint fmt --diff` when `.golangci.yml` enables formatters, otherwise `gofmt -l .` (any output is a failure) |
|
|
20
|
+
| Lint | `golangci-lint run` when the project configures it, otherwise `go vet ./...` |
|
|
21
|
+
| Test | `go test -race ./...` |
|
|
22
|
+
| Module tidy | `go mod tidy -diff` (prints the diff and exits non-zero when `go.mod` or `go.sum` is stale) |
|
|
23
|
+
| Vulnerabilities | `go tool govulncheck ./...` (a `tool` directive in `go.mod`) |
|
|
24
|
+
| Format fix | `golangci-lint fmt`, or `gofmt -w .` |
|
|
25
|
+
| API break (libraries) | `go tool go-apidiff <base-ref>` on PRs and at release |
|
|
26
|
+
| Docs | `go doc ./...` renders; lint doc comments through golangci-lint (`revive` `exported`, `godoclint`) |
|
|
27
|
+
| Dead code (executables) | `go tool deadcode -test ./...` |
|
|
28
|
+
|
|
29
|
+
The scaffold's `golangci-lint` v2 config includes `errcheck`, `govet`, `ineffassign`,
|
|
30
|
+
`staticcheck`, `unused` and explicitly enabled `gosec`; `go vet` alone is not that
|
|
31
|
+
gate. Enable `gocognit` at 15 (golangci-lint's own default reports only above 30) and
|
|
32
|
+
`gocyclo` at 10-12, ratcheting reviewed exceptions. For executable
|
|
33
|
+
packages, `go tool deadcode -test ./...` reports whole-program reachability
|
|
34
|
+
from executable/test roots, unlike declaration-level `unused`/`staticcheck` checks.
|
|
35
|
+
Do not treat that report as proof a library's public API is safe to remove.
|
|
36
|
+
|
|
37
|
+
- After an edit that spans files or packages or changes a signature, run
|
|
38
|
+
`go vet ./...` and `go build ./...` once before handing back (or the project's
|
|
39
|
+
own `make`/task target for them when it has one).
|
|
40
|
+
- Respect the project's formatter. When `.golangci.yml` enables `gofumpt`,
|
|
41
|
+
`goimports` or `gci`, a `gofmt`-only check passes code its CI rejects; when it
|
|
42
|
+
uses plain `gofmt`, do not reformat with `gofumpt`.
|
|
43
|
+
- `-race` is the default for tests: it finds data races only on paths the tests
|
|
44
|
+
run, and costs roughly 2-20× time and 5-10× memory. It needs cgo on Linux
|
|
45
|
+
(`CGO_ENABLED=1` and a C compiler); when it cannot run, run `go test ./...` and
|
|
46
|
+
report `-race` as not run.
|
|
47
|
+
- Narrow to the packages the task touched (`go test -race ./internal/billing/...`)
|
|
48
|
+
when the module is slow, and say so in the report.
|
|
49
|
+
- In a `go.work` workspace, `./...` from a root without `go.mod` matches nothing.
|
|
50
|
+
Use the `work` pattern (`go build work`, `go test -race work`, Go 1.25+) or run per
|
|
51
|
+
module with `go -C ./svc test ./...`. `go mod tidy` is per module:
|
|
52
|
+
`go -C ./svc mod tidy -diff`.
|
|
53
|
+
- Never `go install …@latest` a tool inside a check. Use the binary the project
|
|
54
|
+
has: a `tool` directive in `go.mod` (Go 1.24+, detect with `grep -F <module> go.mod`,
|
|
55
|
+
run with `go tool <name>`), or for `golangci-lint` a binary on `PATH`, because its
|
|
56
|
+
docs advise against `go get -tool` and `go install`. When a tool is missing, recommend
|
|
57
|
+
`go get -tool <pkg>@latest` (`golangci-lint`: `brew install golangci-lint`), ask the user
|
|
58
|
+
before running it, and report the step as not run if they decline.
|
|
59
|
+
- Tool choices per concern, with minimum versions, are in `lang-go-libraries`'s
|
|
60
|
+
`references/quality.md` and `references/testing.md`. For `cgo` code, `go test -asan`
|
|
61
|
+
or `-msan` add memory checking beside `-race`.
|
|
62
|
+
|
|
63
|
+
## CI
|
|
64
|
+
|
|
65
|
+
Run the same steps in the same order, one job or step per row so the failure is
|
|
66
|
+
named. Use `actions/setup-go` with `go-version-file: go.mod` (its module cache is on
|
|
67
|
+
by default), and install `golangci-lint` with `golangci/golangci-lint-action`, not
|
|
68
|
+
`go install`. Workflow structure, the required `ci-gate` job and action pinning are
|
|
69
|
+
the `toolchain` plugin's `ci-github-actions` skill.
|
|
70
|
+
|
|
71
|
+
After an edit, run the listed format check for changed files. The host may format files automatically; do not rely on that instead of the project check.
|
|
72
|
+
|
|
73
|
+
A missing `go.mod` or toolchain binary means that step did not run. Report it as
|
|
74
|
+
not run, never as a pass. Read failures as the project's actual toolchain output;
|
|
75
|
+
do not invent extra linters.
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: lang-go-testing
|
|
3
|
+
description: Use to write or fix Go tests (table tests, subtests, -race, golden files, fuzzing, httptest, synctest, testify).
|
|
4
|
+
metadata:
|
|
5
|
+
opencode/autoinvoke: false
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# Go Testing
|
|
9
|
+
|
|
10
|
+
Sources: [`testing`](https://pkg.go.dev/testing), `go help testflag` (Go 1.27), [Go fuzzing](https://go.dev/doc/security/fuzz/), [`testing/synctest`](https://pkg.go.dev/testing/synctest), [go-cmp](https://pkg.go.dev/github.com/google/go-cmp/cmp).
|
|
11
|
+
|
|
12
|
+
Read [practice.md](references/practice.md) for Go idioms and tool choices. Use
|
|
13
|
+
`quality-testing` for what to test, behavior budgets, maintenance and review rules.
|
|
14
|
+
Follow the existing tests' style first: if the package uses `testify`, keep using
|
|
15
|
+
it; do not add it to a package that does not.
|
|
16
|
+
|
|
17
|
+
## Table tests with subtests
|
|
18
|
+
|
|
19
|
+
```go
|
|
20
|
+
func TestParseDuration(t *testing.T) {
|
|
21
|
+
tests := []struct {
|
|
22
|
+
name string
|
|
23
|
+
in string
|
|
24
|
+
want time.Duration
|
|
25
|
+
wantErr bool
|
|
26
|
+
}{
|
|
27
|
+
{name: "minutes", in: "5m", want: 5 * time.Minute},
|
|
28
|
+
{name: "empty", in: "", wantErr: true},
|
|
29
|
+
}
|
|
30
|
+
for _, tt := range tests {
|
|
31
|
+
t.Run(tt.name, func(t *testing.T) {
|
|
32
|
+
t.Parallel()
|
|
33
|
+
got, err := ParseDuration(tt.in)
|
|
34
|
+
if (err != nil) != tt.wantErr {
|
|
35
|
+
t.Fatalf("ParseDuration(%q) error = %v, wantErr %v", tt.in, err, tt.wantErr)
|
|
36
|
+
}
|
|
37
|
+
if got != tt.want {
|
|
38
|
+
t.Errorf("ParseDuration(%q) = %v, want %v", tt.in, got, tt.want)
|
|
39
|
+
}
|
|
40
|
+
})
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
- Under Go `1.22` language semantics, newly declared loop variables have their own
|
|
46
|
+
per-iteration identity; older language versions still need `tt := tt`. Shared
|
|
47
|
+
referenced data and variables reused with `=` are not isolated.
|
|
48
|
+
- Messages read `Func(input) = got, want want`. `t.Fatalf` stops this subtest,
|
|
49
|
+
`t.Errorf` keeps checking.
|
|
50
|
+
- Compare structs and slices with `cmp.Diff(want, got)` from go-cmp
|
|
51
|
+
(`if d := cmp.Diff(want, got); d != "" { t.Errorf("mismatch (-want +got):\n%s", d) }`),
|
|
52
|
+
not `reflect.DeepEqual`, which says only that they differ. Check errors with
|
|
53
|
+
`errors.Is` / `errors.As`, not by string.
|
|
54
|
+
- Helpers call `t.Helper()` first so failures point at the caller. Use `t.TempDir()`,
|
|
55
|
+
`t.Cleanup`, `t.Context()` (Go 1.24+, cancelled before cleanups run) and
|
|
56
|
+
`t.Chdir` (Go 1.24+). `t.Setenv` and `t.Chdir` cannot be combined with `t.Parallel()`.
|
|
57
|
+
- Black-box tests live in `package foo_test` and use only the exported API; keep
|
|
58
|
+
`package foo` tests for internals that cannot be reached otherwise.
|
|
59
|
+
- `func ExampleParse()` with an `// Output:` comment runs as a test and renders as
|
|
60
|
+
documentation.
|
|
61
|
+
|
|
62
|
+
## Running
|
|
63
|
+
|
|
64
|
+
```sh
|
|
65
|
+
go test -race ./... # default; see lang-go-quality
|
|
66
|
+
go test -run 'TestParseDuration/empty$' ./internal/timeparse
|
|
67
|
+
go test -count=1 ./... # bypass the test result cache
|
|
68
|
+
go test -shuffle=on -count=5 ./pkg # flush out order dependence; prints the seed
|
|
69
|
+
gotestsum --junitfile junit.xml -- -race ./... # JUnit for CI; rerun flags only for diagnosis
|
|
70
|
+
go test -failfast ./... # stop after the first failing test
|
|
71
|
+
go test -coverprofile=cover.out ./... && go tool cover -func=cover.out
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Golden files
|
|
75
|
+
|
|
76
|
+
Store stable, reviewable expected outputs under `testdata/` (ignored as a package)
|
|
77
|
+
and regenerate them behind a flag:
|
|
78
|
+
|
|
79
|
+
```go
|
|
80
|
+
var update = flag.Bool("update", false, "rewrite golden files")
|
|
81
|
+
|
|
82
|
+
golden := filepath.Join("testdata", tt.name+".golden")
|
|
83
|
+
if *update {
|
|
84
|
+
if err := os.WriteFile(golden, got, 0o644); err != nil { t.Fatal(err) }
|
|
85
|
+
}
|
|
86
|
+
want, err := os.ReadFile(golden)
|
|
87
|
+
if err != nil { t.Fatal(err) }
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Run `go test ./pkg -update`, then review the golden diff like code before committing.
|
|
91
|
+
This is a custom flag, not a built-in Go flag. Never auto-update in CI.
|
|
92
|
+
|
|
93
|
+
## Fuzzing
|
|
94
|
+
|
|
95
|
+
```go
|
|
96
|
+
func FuzzParse(f *testing.F) {
|
|
97
|
+
f.Add("5m") // seed corpus
|
|
98
|
+
f.Fuzz(func(t *testing.T, in string) {
|
|
99
|
+
d, err := ParseDuration(in)
|
|
100
|
+
if err != nil {
|
|
101
|
+
return // rejecting input is fine; panicking is not
|
|
102
|
+
}
|
|
103
|
+
again, err := ParseDuration(d.String()) // assert an invariant, not an exact value
|
|
104
|
+
if err != nil || again != d {
|
|
105
|
+
t.Errorf("round trip of %q: %v -> %v, %v", in, d, again, err)
|
|
106
|
+
}
|
|
107
|
+
})
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
```sh
|
|
112
|
+
go test -run='^$' -fuzz='^FuzzParse$' -fuzztime=60s ./internal/timeparse # one package at a time; always bound it
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
A failing input is written to `testdata/fuzz/FuzzParse/`; commit it. Plain `go test`
|
|
116
|
+
replays the seeds and that corpus as regular tests, so the bug stays fixed.
|
|
117
|
+
|
|
118
|
+
## Mutation
|
|
119
|
+
|
|
120
|
+
```sh
|
|
121
|
+
go tool gremlins unleash --diff origin/main --output=gremlins.json # changed code only
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
`gremlins` (or avito-tech `go-mutesting` v2 when it cannot parse the code) is not
|
|
125
|
+
installed by default: detect it, recommend `go get -tool github.com/go-gremlins/gremlins/cmd/gremlins@latest`,
|
|
126
|
+
and ask before running it. Scope it to changed or critical packages; never gate on the whole module.
|
|
127
|
+
|
|
128
|
+
## Time, concurrency and I/O
|
|
129
|
+
|
|
130
|
+
- Use `-race`, `synctest` and `go.uber.org/goleak` (`goleak.VerifyNone(t)`) together on
|
|
131
|
+
concurrent code. Go 1.27 adds a `goroutineleak` `runtime/pprof` profile for live processes.
|
|
132
|
+
- Supported in-process timer/concurrency tests can use
|
|
133
|
+
`synctest.Test(t, func(t *testing.T) { /* scenario */ })` (Go `1.25`+). Fake time
|
|
134
|
+
advances when every goroutine in the bubble is durably blocked;
|
|
135
|
+
`synctest.Wait()` waits for quiescence. Network I/O and mutex waits are not
|
|
136
|
+
durably blocking; this does not replace network integration or explore all schedules.
|
|
137
|
+
- HTTP clients: point them at `httptest.NewServer(handler)`; HTTP handlers: call
|
|
138
|
+
them with `httptest.NewRecorder()` and `httptest.NewRequest`.
|
|
139
|
+
- Slow or external integration tests go behind `//go:build integration` (run with
|
|
140
|
+
`go test -tags integration ./...`) or skip under `testing.Short()`.
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
# Go testing practice
|
|
2
|
+
|
|
3
|
+
Checked 2026-11-16.
|
|
4
|
+
|
|
5
|
+
Go idioms and tool choices for small, behavior-focused test suites.
|
|
6
|
+
Use `quality-testing` for what to test, behavior budgets, same-change maintenance,
|
|
7
|
+
double selection and review rules; follow existing package conventions first.
|
|
8
|
+
|
|
9
|
+
## Layout and naming
|
|
10
|
+
|
|
11
|
+
**Do:** Put `*_test.go` beside production code. Prefer `package x_test` for exported
|
|
12
|
+
contracts; use `package x` when an important internal algorithm needs focused tests.
|
|
13
|
+
Name tests for outcomes, such as `TestParseRejectsEmpty`, not just `TestParse`.
|
|
14
|
+
Use `ExampleParse` with an `Output:` comment for a small public usage contract.
|
|
15
|
+
Examples without `Output:` or `Unordered output:` compile but do not execute.
|
|
16
|
+
|
|
17
|
+
**Do not:** Treat access to private helpers as a reason to test each helper. Keep
|
|
18
|
+
fixtures in `testdata/`, not in a second package tree that duplicates the suite.
|
|
19
|
+
|
|
20
|
+
## One behavior per test
|
|
21
|
+
|
|
22
|
+
**Do:** Keep setup, action and the expected outcome visible. Several assertions may
|
|
23
|
+
describe one result. Stop on failed prerequisites with `t.Fatal` or `t.Fatalf`.
|
|
24
|
+
Use `errors.Is`/`errors.As` for error identity unless text is the contract.
|
|
25
|
+
|
|
26
|
+
```go
|
|
27
|
+
got, err := Parse("5m")
|
|
28
|
+
if err != nil {
|
|
29
|
+
t.Fatalf("Parse(%q): %v", "5m", err)
|
|
30
|
+
}
|
|
31
|
+
if got != 5*time.Minute {
|
|
32
|
+
t.Errorf("Parse(%q) = %v, want %v", "5m", got, 5*time.Minute)
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
**Do not:** Copy the implementation into the expected-value calculation. Default
|
|
37
|
+
to standard checks; use `go-cmp` and `cmp.Diff(want, got)` for compound values.
|
|
38
|
+
Handle unexported fields deliberately; broad ignore options can conceal defects.
|
|
39
|
+
Keep existing `testify` or `is` conventions rather than adding a second
|
|
40
|
+
assertion library. Never call fatal assertions, including `require`, in workers.
|
|
41
|
+
|
|
42
|
+
## Parametrize instead of copying
|
|
43
|
+
|
|
44
|
+
**Do:** Use a typed table and named `t.Run` cases when setup and assertion shape match.
|
|
45
|
+
|
|
46
|
+
```go
|
|
47
|
+
for _, tc := range []struct{ name, input string }{
|
|
48
|
+
{"empty", ""}, {"unknown_unit", "5fortnights"},
|
|
49
|
+
} {
|
|
50
|
+
t.Run(tc.name, func(t *testing.T) {
|
|
51
|
+
t.Parallel()
|
|
52
|
+
if _, err := Parse(tc.input); !errors.Is(err, ErrInvalid) {
|
|
53
|
+
t.Fatalf("Parse(%q) error = %v, want ErrInvalid", tc.input, err)
|
|
54
|
+
}
|
|
55
|
+
})
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
**Do not:** Build giant tables with conditional setup/oracles. Separate materially
|
|
60
|
+
different behaviors. Parallelize only isolated cases: `t.Parallel` delays a
|
|
61
|
+
subtest until its parent returns. Go `1.22` language semantics give variables
|
|
62
|
+
declared with `:=` in loops per-iteration identity; older language versions need
|
|
63
|
+
rebinding. Reused `=` variables and shared pointers/maps remain shared.
|
|
64
|
+
|
|
65
|
+
## Fixtures and builders
|
|
66
|
+
|
|
67
|
+
**Do:** Use typed literals or small builders with valid defaults and explicit
|
|
68
|
+
behavior-bearing overrides. Shared helpers live in `*_test.go`, call `t.Helper`,
|
|
69
|
+
and register `t.Cleanup` immediately after acquisition. Use `t.TempDir` for files.
|
|
70
|
+
Cleanup runs in reverse registration order after descendant subtests finish.
|
|
71
|
+
|
|
72
|
+
**Do not:** Hide scenarios in `init` or a global `TestMain` fixture. Allocate mutable
|
|
73
|
+
state per test; avoid suites merely to share it. `t.Setenv` and `t.Chdir` affect
|
|
74
|
+
process state and cannot be used in parallel tests or under parallel ancestors.
|
|
75
|
+
|
|
76
|
+
## Doubles and real boundaries
|
|
77
|
+
|
|
78
|
+
**Do:** Use real deterministic collaborators, then small consumer-owned fakes.
|
|
79
|
+
Check a reusable fake against the real implementation's contract. Use `httptest`
|
|
80
|
+
recorders for handler results and `httptest.NewServer` for client/transport behavior.
|
|
81
|
+
Put `testcontainers-go` database/broker checks in an explicit integration
|
|
82
|
+
lane with pinned images, readiness checks, isolated data and registered cleanup.
|
|
83
|
+
|
|
84
|
+
**Do not:** Invent interfaces solely to mock every collaborator. Choose existing
|
|
85
|
+
`gomock` (`go.uber.org/mock`) or `mockery` only when boundary arguments,
|
|
86
|
+
counts or order are contractual. Do not mix generators or script incidental calls.
|
|
87
|
+
Driver mocks do not establish real SQL, transaction or broker semantics.
|
|
88
|
+
|
|
89
|
+
## Async, time and concurrency
|
|
90
|
+
|
|
91
|
+
**Do:** Await channels/completion signals rather than wall-clock sleeps. On Go
|
|
92
|
+
`1.24`+, pass `t.Context()` to lifetime-bound workers and join them in cleanup;
|
|
93
|
+
the context is canceled before cleanup, but cancellation alone is not termination.
|
|
94
|
+
Send worker errors to the test goroutine for fatal assertions.
|
|
95
|
+
|
|
96
|
+
Use stable `testing/synctest` on Go `1.25`+ for supported in-process timer tests:
|
|
97
|
+
|
|
98
|
+
```go
|
|
99
|
+
synctest.Test(t, func(t *testing.T) {
|
|
100
|
+
ctx, cancel := context.WithTimeout(t.Context(), time.Second)
|
|
101
|
+
defer cancel()
|
|
102
|
+
time.Sleep(time.Second) // Fake time, not a wall-clock synchronization delay.
|
|
103
|
+
synctest.Wait()
|
|
104
|
+
if !errors.Is(ctx.Err(), context.DeadlineExceeded) {
|
|
105
|
+
t.Fatalf("timeout error = %v, want DeadlineExceeded", ctx.Err())
|
|
106
|
+
}
|
|
107
|
+
})
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
**Do not:** Assume fake time models external sockets or every blocking operation.
|
|
111
|
+
Network I/O and mutex waits are not durably blocking; `synctest` is not exhaustive
|
|
112
|
+
schedule exploration. Keep an exercised `-race` lane and add `go.uber.org/goleak` for goroutine leaks.
|
|
113
|
+
Tool versions and install commands live in `lang-go-libraries` `references/testing.md`;
|
|
114
|
+
detect a tool, recommend the install and ask before running it.
|
|
115
|
+
|
|
116
|
+
## Property tests
|
|
117
|
+
|
|
118
|
+
**Do:** Use `rapid` when domain generation and shrinking let one invariant
|
|
119
|
+
replace many examples: conservation, idempotence or ordering. Generate valid domain
|
|
120
|
+
inputs explicitly. Preserve failing seeds and a readable minimized regression case.
|
|
121
|
+
|
|
122
|
+
**Do not:** Generate random values without an independent property, or replace
|
|
123
|
+
named boundary/error examples with an opaque property campaign.
|
|
124
|
+
|
|
125
|
+
## Snapshots and golden files
|
|
126
|
+
|
|
127
|
+
**Do:** Compare small, stable, reviewable outputs; use semantic assertions where
|
|
128
|
+
clearer. Store goldens in `testdata/` and implement an explicit update flag:
|
|
129
|
+
|
|
130
|
+
```go
|
|
131
|
+
var update = flag.Bool("update", false, "rewrite golden files")
|
|
132
|
+
// Inside the test, after producing got and choosing path:
|
|
133
|
+
if *update {
|
|
134
|
+
if err := os.WriteFile(path, got, 0o644); err != nil { t.Fatal(err) }
|
|
135
|
+
}
|
|
136
|
+
want, err := os.ReadFile(path)
|
|
137
|
+
if err != nil { t.Fatal(err) }
|
|
138
|
+
if diff := cmp.Diff(string(want), string(got)); diff != "" {
|
|
139
|
+
t.Errorf("golden mismatch (-want +got):\n%s", diff)
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
**Do not:** Auto-update in CI or accept bulk diffs without review. Go has no built-in
|
|
144
|
+
`-update`; run the project's flag explicitly, for example `go test ./pkg -update`.
|
|
145
|
+
Do not snapshot timestamps, random identifiers or incidental object internals.
|
|
146
|
+
|
|
147
|
+
## Fuzzing, mutation and coverage
|
|
148
|
+
|
|
149
|
+
**Do:** Use native `FuzzXxx` targets for parsers/codecs with seed inputs and meaningful
|
|
150
|
+
no-panic/round-trip invariants. Bound campaigns with `-fuzztime`; ordinary `go test`
|
|
151
|
+
replays seeds and committed failures in `testdata/fuzz/<FuzzName>`.
|
|
152
|
+
Run `gremlins` (`gremlins unleash --diff <ref> --output=<json>`) on important pure-logic
|
|
153
|
+
packages and on changed code in PRs; `go-mutesting` v2 is the fallback. Neither emits
|
|
154
|
+
the Stryker schema; the `quality_test_compare` tool (when available) reads Gremlins JSON.
|
|
155
|
+
Continuous fuzzing uses OSS-Fuzz or ClusterFuzzLite (`compile_native_go_fuzzer`).
|
|
156
|
+
|
|
157
|
+
Read `-coverprofile` and changed-code gaps as prompts for missing behaviors.
|
|
158
|
+
Native Go coverage is statement coverage, not branch coverage. Review branch risks
|
|
159
|
+
explicitly; changed-line reports need separate diff/coverage processing.
|
|
160
|
+
For CLI/integration executions, Go `1.20`+ supports `go build -cover`, `GOCOVERDIR`
|
|
161
|
+
and `go tool covdata` to collect/report/merge instrumented process coverage.
|
|
162
|
+
|
|
163
|
+
**Do not:** Chase a universal percentage or add brittle tests for equivalent mutants.
|
|
164
|
+
A clean `-race` run proves only that executed paths exposed no detected race.
|
|
165
|
+
Benchmark an actual performance question; on Go `1.24`+, prefer `b.Loop()` with
|
|
166
|
+
setup outside the loop. Do not combine it with a `b.N` iteration loop.
|
|
167
|
+
|
|
168
|
+
## Flaky tests
|
|
169
|
+
|
|
170
|
+
**Do:** Diagnose with `go test -shuffle=on -count=20 ./pkg`; record the printed seed
|
|
171
|
+
and replay with `-shuffle=<seed>`. Use `-count=1` to bypass cached results. Inspect
|
|
172
|
+
shared state, resource collisions, goroutine lifetime and races before retrying.
|
|
173
|
+
Quarantine only with an owner, issue, expiry and continued diagnostic execution.
|
|
174
|
+
|
|
175
|
+
**Do not:** Enable retries by default. `gotestsum` reports useful JSON/JUnit
|
|
176
|
+
artifacts, but `--rerun-fails` can turn intermittent defects green. Preserve the
|
|
177
|
+
initial failure and use reruns for diagnosis, not as a passing gate.
|
|
178
|
+
|
|
179
|
+
## Bad tests and fixes
|
|
180
|
+
|
|
181
|
+
See the `quality-testing` skill's `references/bad-tests.md` for language-neutral pairs covering removal checks, copied oracles, call-order mocks, side channels, copies instead of parameters, logic in tests, sleeps, assertion-free tests, eager tests, mystery guests, type re-checks, tampering, and whole-object snapshots.
|
|
182
|
+
|
|
183
|
+
### Sleeping for a goroutine
|
|
184
|
+
|
|
185
|
+
Bad:
|
|
186
|
+
|
|
187
|
+
```go
|
|
188
|
+
func TestRefresh(t *testing.T) {
|
|
189
|
+
go refresh()
|
|
190
|
+
time.Sleep(10 * time.Millisecond)
|
|
191
|
+
if got := cachedValue(); got != "fresh" { t.Fatalf("got %q, want fresh", got) }
|
|
192
|
+
}
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
The delay neither guarantees completion nor synchronizes the worker's writes with the read.
|
|
196
|
+
|
|
197
|
+
Fix:
|
|
198
|
+
|
|
199
|
+
```go
|
|
200
|
+
func TestRefresh(t *testing.T) {
|
|
201
|
+
done := make(chan struct{})
|
|
202
|
+
go func() { refresh(); close(done) }()
|
|
203
|
+
<-done
|
|
204
|
+
if got := cachedValue(); got != "fresh" { t.Fatalf("got %q, want fresh", got) }
|
|
205
|
+
}
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
### Fatal assertions in a worker
|
|
209
|
+
|
|
210
|
+
Bad:
|
|
211
|
+
|
|
212
|
+
```go
|
|
213
|
+
func TestSave(t *testing.T) {
|
|
214
|
+
done := make(chan struct{})
|
|
215
|
+
go func() {
|
|
216
|
+
defer close(done)
|
|
217
|
+
if err := save(); err != nil { t.Fatal(err) }
|
|
218
|
+
}()
|
|
219
|
+
<-done
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
`t.Fatal` calls `FailNow`, which must run in the test goroutine rather than a spawned worker.
|
|
224
|
+
|
|
225
|
+
Fix:
|
|
226
|
+
|
|
227
|
+
```go
|
|
228
|
+
func TestSave(t *testing.T) {
|
|
229
|
+
errs := make(chan error, 1)
|
|
230
|
+
go func() { errs <- save() }()
|
|
231
|
+
if err := <-errs; err != nil { t.Fatalf("save: %v", err) }
|
|
232
|
+
}
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
### Compound comparisons without a useful diff
|
|
236
|
+
|
|
237
|
+
Bad:
|
|
238
|
+
|
|
239
|
+
```go
|
|
240
|
+
func TestReceipt(t *testing.T) {
|
|
241
|
+
got, want := receipt(), Receipt{Total: 25, Currency: "USD"}
|
|
242
|
+
if got != want { t.Error("wrong receipt") }
|
|
243
|
+
}
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
The failure hides which field differs, and `!=` stops compiling if the struct gains a slice or map.
|
|
247
|
+
|
|
248
|
+
Fix:
|
|
249
|
+
|
|
250
|
+
```go
|
|
251
|
+
func TestReceipt(t *testing.T) {
|
|
252
|
+
got, want := receipt(), Receipt{Total: 25, Currency: "USD"}
|
|
253
|
+
if diff := cmp.Diff(want, got); diff != "" {
|
|
254
|
+
t.Errorf("receipt mismatch (-want +got):\n%s", diff)
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
## Do not write
|
|
260
|
+
|
|
261
|
+
- Reflection checks such as `reflect.TypeOf(service).MethodByName("Removed")` to
|
|
262
|
+
prove a deleted method is gone. Package functions cannot be enumerated that way;
|
|
263
|
+
do not replace this with AST/file checks for a removed function either.
|
|
264
|
+
- Runtime interface checks duplicating `var _ Store = (*MemoryStore)(nil)`; the
|
|
265
|
+
compiler already proves implementation. Test the interface's behavior instead.
|
|
266
|
+
- Trivial getter tests, private-helper inventories or expected values computed by
|
|
267
|
+
repeating production logic. Delete obsolete tests/fixtures with removed behavior.
|
|
268
|
+
- A second copy of an already-protected scenario at another level without a distinct
|
|
269
|
+
risk. Genuine API compatibility/security exclusions need contract tests, not
|
|
270
|
+
memorials to removed internals.
|
|
271
|
+
|
|
272
|
+
## Defaults by use case
|
|
273
|
+
|
|
274
|
+
| Use case | Default |
|
|
275
|
+
| --- | --- |
|
|
276
|
+
| Pure logic | `testing`, named cases, `cmp.Diff`; `rapid` for a strong invariant |
|
|
277
|
+
| I/O adapters | Small fake plus real filesystem/service integration checks |
|
|
278
|
+
| HTTP handlers | `httptest.NewRecorder`; server when transport matters |
|
|
279
|
+
| Async/concurrency | Completion signals, cleanup/join, `synctest`, `-race` |
|
|
280
|
+
| CLI | Injected streams/core tests plus a few exit/stdout/stderr subprocess checks |
|
|
281
|
+
| Parsers/codecs | Boundary cases plus native fuzzing and retained corpus |
|
|
282
|
+
| CI | Fast `go test ./...`, exercised `go test -race ./...`; explicit `go test -tags integration ./...` lane, bounded fuzzing, optional targeted mutation |
|
|
283
|
+
|
|
284
|
+
Use `//go:build integration` to select integration files; tags are a project
|
|
285
|
+
convention. `-short` skips nothing unless tests check `testing.Short()` themselves.
|
|
286
|
+
|
|
287
|
+
## Sources
|
|
288
|
+
|
|
289
|
+
- [Testing APIs and examples](https://pkg.go.dev/testing), [Go `1.22` loops](https://go.dev/doc/go1.22), [Go `1.24` lifecycle/benchmarks](https://go.dev/doc/go1.24).
|
|
290
|
+
- [Fake-time testing](https://go.dev/blog/testing-time), [HTTP harness](https://pkg.go.dev/net/http/httptest), [fuzzing](https://go.dev/doc/security/fuzz/).
|
|
291
|
+
- [Integration coverage](https://go.dev/doc/build-cover), [race detector](https://go.dev/doc/articles/race_detector), [go-cmp](https://pkg.go.dev/github.com/google/go-cmp/cmp), [testify](https://pkg.go.dev/github.com/stretchr/testify), [is](https://pkg.go.dev/github.com/matryer/is).
|
|
292
|
+
- [Rapid](https://pkg.go.dev/pgregory.net/rapid), [Uber mocks](https://pkg.go.dev/go.uber.org/mock), [Mockery](https://pkg.go.dev/github.com/vektra/mockery/v3), [Testcontainers](https://pkg.go.dev/github.com/testcontainers/testcontainers-go).
|
|
293
|
+
- [Gremlins](https://pkg.go.dev/github.com/go-gremlins/gremlins), [gotestsum](https://pkg.go.dev/gotest.tools/gotestsum).
|