@srobroek/pi-lang-go 0.0.0-stage → 0.9.3

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.
@@ -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).