Testing
Go testing is a small package with exact rules about order, failure and time. Here are the rules, recorded from real runs, and the tests a strong build has.
- 1Register shared resources with t.Cleanup, not defer. A defer runs before parallel subtests resume.
- 2Test the handler through a table, and keep every store behind one contract test.
- 3A fake hides what the real database does. Run the same contract on real Postgres.
- 4Time, races and odd input need their own tools: synctest, -race and fuzzing. Assertions alone do not find them.
package trap
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestAPI(t *testing.T) {
h := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})
srv := httptest.NewServer(h)
defer srv.Close()1
for _, name := range []string{"a", "b"} {
t.Run(name, func(t *testing.T) {
t.Parallel()2
resp, err := http.Get(srv.URL + "/" + name)3
if err != nil {
t.Fatal("request failed")
}
resp.Body.Close()
})
}
}- 1Runs when TestAPI returns. The subtests have paused and have not sent a request yet.
- 2Pauses this subtest. It resumes after the parent function has returned.
- 3The server has closed, so every request fails.
| line | exit | status |
|---|---|---|
| defer srv.Close() | 1 | Both subtests fail |
| t.Cleanup(srv.Close) | 0 | Both pass |
case_test.go:19: request failed
case_test.go:19: request failed
--- FAIL: TestAPI
--- FAIL: TestAPI/a
--- FAIL: TestAPI/b
FAIL- t.Cleanup waits for every subtest, parallel or not. A defer waits for the function only.
- The failure names the request, not the defer, so the cause is hard to see.
Parallel subtests resume after the parent returns, so I put the server in t.Cleanup and not in a defer.
package lifecycle
import (
"fmt"
"testing"
)
func TestLife(t *testing.T) {
ctx := t.Context()
t.Cleanup(func() { fmt.Println("parent cleanup, ctx:", ctx.Err()) })
defer fmt.Println("parent defer")2
fmt.Println("parent body")
t.Run("serial", func(t *testing.T) {
fmt.Println("serial runs at once")
})
t.Run("parallel", func(t *testing.T) {
sub := t.Context()
t.Cleanup(func() { fmt.Println("parallel cleanup, ctx:", sub.Err()) })
t.Parallel()1
fmt.Println("parallel resumes, ctx:", sub.Err())
})
fmt.Println("parent body ends, ctx:", ctx.Err())
}- 1The subtest pauses here, and t.Run returns to the parent.
- 2Runs before the parallel subtest resumes.
parent bodyThe test function starts. Its context is live.
The order is: body, serial subtests, defers, parallel subtests, then context cancel and cleanups.
| rule | why | status |
|---|---|---|
| One table, one loop, one t.Run per case | Each case has a name, runs alone with -run, and fails alone. | Approved |
| Call t.Helper first in a helper | The failure points at the test line, not the helper. | Approved |
| Use t.Cleanup for resources that subtests share | It waits for parallel subtests. See panel A. | Approved |
| Use t.Context for work the test starts | It ends before cleanups, so a cleanup can wait for the work to stop. | Approved |
| Use a real Postgres for store tests | A fake has different rules. See panel O. | Approved |
| Use -race in CI on every package | It finds races that no assertion sees. See panel Q. | Approved |
| Use t.Parallel on pure table cases | It shortens the run and exposes shared state. | Not with Setenv or Chdir |
| Assert on errors with errors.Is | The text of a wrapped error can change. | Approved |
| Keep a mock for a third party you cannot run | A mock tests your guess at its behaviour. | Only at a process boundary |
| Use time.Sleep to wait for a goroutine | It is slow when it passes and flaky under load. Use synctest. | Not approved |
| Call t.Fatal from another goroutine | It stops that goroutine only. See the drill. | Not approved |
| Depend on the order of tests or map iteration | -shuffle and the runtime change the order on purpose. | Not approved |
| Test private details with no behaviour to show | A refactor then breaks tests with no bug present. | Not approved |
I run go test -race -shuffle=on in CI. The rest is habit: subtests, helpers, real dependencies.
func TestSplit(t *testing.T) {
tests := []struct {
name string
line string
want []string
err error1
}{
{name: "plain", line: "a,b", want: []string{"a", "b"}},
{name: "empty line", line: "", want: []string{""}},
{name: "empty fields", line: ",", want: []string{"", ""}},
{name: "escaped comma", line: `a\,b,c`, want: []string{"a,b", "c"}},
{name: "lone backslash", line: `a\`, err: ErrDangling},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {2
t.Parallel()3
got, err := Split(tc.line)
if !errors.Is(err, tc.err) {
t.Fatalf("err = %v, want %v", err, tc.err)4
}
if !slices.Equal(got, tc.want) {
t.Errorf("got %q, want %q", got, tc.want)
}
})
}
}- 1A nil err means the case expects success, and errors.Is(nil, nil) is true.
- 2The inner t hides the outer one, so a failure belongs to this case.
- 3Safe with tc since Go 1.22: each iteration has its own variable.
- 4Fatal stops this case only. The next case still runs.
Every case gets a name and a t.Run, so the failure output names the case and I can run it alone.
// seed creates items and fails the test at the caller's line if one fails.
func seed(t *testing.T, s Store, items ...Item) {
t.Helper()1
for _, it := range items {
if err := s.Create(t.Context()2, it); err != nil {
t.Fatalf("seed %q: %v", it.Key, err)
}
}
}
// newServer starts the service and stops it after the last subtest.
func newServer(t *testing.T) (*httptest.Server, *MemStore) {
t.Helper()
s := NewMemStore()
srv := httptest.NewServer(Handler(s))
t.Cleanup(srv.Close)3
return srv, s
}- 1Failure reports skip this frame and name the caller.
- 2Ends with the test, so a stuck call cannot outlive it.
- 3The caller has nothing to remember. A cleanup runs even after Fatal.
Other built-in fixtures: t.TempDir removes a directory, t.Setenv restores a variable, and t.Chdir restores the working directory.
A helper takes t, calls t.Helper, and fails the test itself, so each test reads as three lines.
// loadItems reads a fixture from testdata. Tests run in their package
// directory, so the relative path always works.
func loadItems(t *testing.T, name string) []Item {
t.Helper()
raw, err := os.ReadFile(filepath.Join("testdata", name)1)
if err != nil {
t.Fatalf("read fixture: %v", err)2
}
var items []Item
if err := json.Unmarshal(raw, &items); err != nil {
t.Fatalf("parse fixture %s: %v", name, err)
}
return items
}- 1go test runs each test binary in its package directory, so the relative path always works.
- 2A missing fixture fails at the test that asked for it.
| the data is | keep it in |
|---|---|
| A few fields | A literal in the table |
| Large or binary | A file in testdata |
| Built with rules | A helper that takes options |
Fixture files live in testdata. The go tool ignores that directory, and tests run in the package directory.
var update = flag.Bool("update", false, "rewrite golden files")1
func TestReport(t *testing.T) {
got, err := Report(loadItems(t, "items.json"))
if err != nil {
t.Fatal(err)
}
path := filepath.Join("testdata", "report.golden")
if *update {
if err := os.WriteFile(path, []byte(got), 0o644); err != nil {
t.Fatal(err)
}
}
want, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read golden (run with -update): %v", err)
}
if got != string(want)2 {
t.Errorf("report differs from %s:\n%s", path, got)
}
}- 1Run go test -update once, then read the diff before you commit.
- 2The test compares bytes, so the output must be deterministic. Sort any map first.
KEY VALUE EXPIRES
alpha first never
bravo second 2026-11-23 09:30:00
charlie-long-key third neverFor long output, the expected text lives in a file. A flag rewrites it, and the diff shows in review.
func do(h http.Handler, method, path, body string) (int, string) {
w := httptest.NewRecorder()1
r := httptest.NewRequest(method, path, strings.NewReader(body))2
h.ServeHTTP(w, r)
return w.Code, w.Body.String()
}
func TestHandler(t *testing.T) {
tests := []struct {
name, method, path, body string
status int
want string
}{
{"created", "POST", "/items", `{"key":"b"}`, 201, `"key":"b"`},
{"found", "GET", "/items/a", "", 200, `"value":"1"`},
{"missing", "GET", "/items/z", "", 404, "not found"},
{"duplicate", "POST", "/items", `{"key":"a"}`, 409, "key exists"},
{"no key", "POST", "/items", `{}`, 400, "key is required"},
{"not JSON", "POST", "/items", `{`, 400, "not JSON"},
{"NUL byte", "POST", "/items", `{"key":"\u0000"}`, 400, "invalid"},
{"wrong method", "DELETE", "/items", "", 405, ""},4
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
s := NewMemStore()3
seed(t, s, Item{Key: "a", Value: "1"})
code, body := do(Handler(s), tc.method, tc.path, tc.body)
if code != tc.status || !strings.Contains(body, tc.want) {
t.Errorf("got %d %q, want %d %q", code, body, tc.status, tc.want)
}
})
}
}- 1A ResponseWriter in memory. No socket, so no port and no goroutine.
- 2Builds a server-side request. It panics on a bad input, so it needs no error check.
- 3Each case has its own store, so the parallel cases share nothing.
- 4net/http gives this 405 from the method in the route pattern. The table proves the pattern.
| tool | one request | use it for |
|---|---|---|
| NewRecorder | 4.0 µs | Handler logic |
| NewServer | 77 µs | A real client, TLS, redirects |
| NewTestServer | Fake network | A client in a synctest bubble |
I test through the handler with a recorder. One table covers routing, status codes and JSON, with no port.
func TestFetchRetries(t *testing.T) {
synctest.Test(t, func(t *testing.T) {1
calls := 0
srv := httptest.NewTestServer(t, http.HandlerFunc(2
func(w http.ResponseWriter, _ *http.Request) {
calls++
if calls < 3 {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
fmt.Fprint(w, "ok")
}))
start := time.Now()
got, err := Fetch(t.Context(), srv.Client(), srv.URL)
if err != nil || got != "ok" {
t.Fatalf("got %q, %v", got, err)
}
if d := time.Since(start); calls != 3 || d != 3*time.Second3 {
t.Errorf("%d calls in %v, want 3 calls in exactly 3s", calls, d)
}
})
}- 1Starts a bubble with a fake clock. The t inside belongs to the bubble.
- 2New in Go 1.27. The connection is in memory, so a blocked read is durably blocked.
- 3An exact check on a duration. The backoff is 1 s and 2 s, and the requests take no fake time.
Use NewTestServer here, not NewServer. A read on a real socket is not durable, so the fake clock cannot advance past it.
NewTestServer puts the network in the bubble, so a retry with backoff tests in no real time, and exactly.
// joinV1 is the first version of Join. It escapes commas and nothing else.
func joinV1(fields []string) string {
out := make([]string, len(fields))
for i, f := range fields {
out[i] = strings.ReplaceAll(f, ",", `\,`)1
}
return strings.Join(out, ",")
}
// splitV1 reads a backslash as an escape only in front of a comma.
func splitV1(line string) []string {
fields := []string{}
var b strings.Builder
for i := 0; i < len(line); i++ {
switch {
case line[i] == '\\' && i+1 < len(line) && line[i+1] == ','2:
i++
b.WriteByte(',')
case line[i] == ',':
fields = append(fields, b.String())
b.Reset()
default:
b.WriteByte(line[i])
}
}
return append(fields, b.String())
}- 1Escapes commas, and leaves a backslash as it is.
- 2A backslash that ends a field now reads as an escape of the separator.
| input | line | result |
|---|---|---|
| "a", "b" | a,b | Round trip holds |
| "a,b", "c" | a\,b,c | Round trip holds |
| "", "" | , | Round trip holds |
| "a\b", "c" | a\b,c | Round trip holds |
| "日本語", "x" | 日本語,x | Round trip holds |
| "\\", "0" | \,0 | Became [",0"] |
- The first 5 rows are the seed corpus. Every one passes on this code.
- The last row is what go test -fuzz wrote to testdata/fuzz. Two fields became one.
- The property is one line: Split(Join(x)) must return x. The fuzzer needs no expected value.
My table had every case I could think of, and it passed. The fuzzer found a failing input in under a second.
func FuzzRoundTrip(f *testing.F) {
for _, s := range seeds {
f.Add(s[0], s[1])1
}
f.Fuzz(func(t *testing.T, a, b string)2 {
in := []string{a, b}
got, err := Split(Join(in))
if err != nil {
t.Fatalf("split %q: %v", Join(in), err)
}
if !slices.Equal(got, in) {3
t.Errorf("%q became %q", in, got)
}
})
}- 1The seed corpus. Plain go test runs only these and the files in testdata/fuzz.
- 2The arguments after t set the types the fuzzer mutates.
- 3A property, not an example. Round trips suit fuzzing well.
// Join writes fields as one comma-separated line. A comma or a backslash
// inside a field gets a backslash in front of it.
func Join(fields []string) string {
var b strings.Builder
for i, f := range fields {
if i > 0 {
b.WriteByte(',')
}
for j := range len(f) {
if f[j] == ',' || f[j] == '\\' {1
b.WriteByte('\\')
}
b.WriteByte(f[j])
}
}
return b.String()
}
// Split reverses Join.
func Split(line string) ([]string, error) {
fields := []string{}
var b strings.Builder
for i := 0; i < len(line); i++ {
switch line[i] {
case '\\':
i++
if i == len(line) {
return nil, fmt.Errorf("split %q: %w", line, ErrDangling2)
}
b.WriteByte(line[i])
case ',':
fields = append(fields, b.String())
b.Reset()
default:
b.WriteByte(line[i])
}
}
return append(fields, b.String()), nil
}- 1The fix: escape the escape character too.
- 2A second target feeds Split any line, and a line can end in a lone backslash. That is an error, not a panic.
go test -fuzz=FuzzRoundTrip runs until a failure or -fuzztime ends, on one package and one target. Run it in a nightly job, with a time limit.
I keep the found input in testdata, so every plain go test replays it. It is a regression test forever.
// startSweep runs Sweep for the rest of the test. t.Context ends before
// cleanups run, so the wait in the cleanup always returns.
func startSweep(t *testing.T, s Store, every time.Duration) {
t.Helper()
done := make(chan struct{})
go func() {
defer close(done)
Sweep(t.Context(), s, every)1
}()
t.Cleanup(func() { <-done })2
}- 1The context ends after the test, and before cleanups.
- 2Waits for the goroutine to stop. The order in panel B makes this safe.
A cleanup that calls a database needs context.Background. t.Context has ended by then.
A goroutine in a test takes t.Context. The cleanup waits for it, so no goroutine outlives the test.
func TestSweepExpires(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
s := NewMemStore()
seed(t, s,
Item{Key: "short", ExpiresAt: time.Now().Add(90 * time.Second)1},
Item{Key: "long", ExpiresAt: time.Now().Add(time.Hour)},
)
startSweep(t, s, time.Minute)
synctest.Sleep(time.Minute)2
if n := count(t, s); n != 2 {
t.Fatalf("after 60 s: %d items, want 2", n)
}
synctest.Sleep(time.Minute)
if n := count(t, s); n != 1 {
t.Fatalf("after 120 s: %d items, want 1", n)3
}
})
}- 1Inside a bubble, time.Now reads the fake clock.
- 2Go 1.27: time.Sleep, then synctest.Wait. The sweep at 60 s has finished when it returns.
- 3The short item expired at 90 s. The sweep at 120 s removed it.
| a goroutine waits on | durable |
|---|---|
| Channel from this bubble, time.Sleep, Cond.Wait, WaitGroup.Wait | Approved |
| Mutex, a real socket, a system call | Time stops |
Measured: 4.3 ms for 3,600 sweeps across one fake hour.
Code that waits gets a synctest bubble. The clock is fake, so an hour of waits runs in milliseconds and the check is exact.
func TestStores(t *testing.T) {
t.Run("memory", func(t *testing.T) {
t.Parallel()
testStore(t, func(*testing.T) Store { return NewMemStore() })1
})
t.Run("postgres", func(t *testing.T) {
t.Parallel()
pool := labenv.PG(t, "golangtesting")
testStore(t, func(t *testing.T) Store { return newSchema(t, pool) })
})
}
// newSchema gives one test its own schema on a shared database. The server
// holds the search path per connection, so the test uses a pinned one.
func newSchema(t *testing.T, pool *pgxpool.Pool) *PGStore {2
t.Helper()
ctx := context.Background()
name := pgx.Identifier{"t" + strings.ToLower(rand.Text())}.Sanitize()
if _, err := pool.Exec(ctx, "CREATE SCHEMA "+name); err != nil {
t.Fatalf("create schema: %v", err)
}
t.Cleanup(func() {3
_, err := pool.Exec(ctx, "DROP SCHEMA "+name+" CASCADE")
if err != nil {
t.Errorf("drop schema: %v", err)
}
})
cfg := pool.Config()
cfg.ConnConfig.RuntimeParams["search_path"] = strings.Trim(name, `"`)
cfg.MaxConns = 8
scoped, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatalf("open pool: %v", err)
}
t.Cleanup(scoped.Close)
if _, err := scoped.Exec(ctx, Schema); err != nil {
t.Fatalf("create table: %v", err)
}
return NewPGStore(scoped)
}- 1The contract has 7 subtests. Each one opens its own store.
- 2Isolation by schema. It also works with code that commits or opens its own transactions.
- 3Drops the schema when the test ends, also after a failure.
One test function takes a constructor and runs on each store, so the fake cannot drift from Postgres.
| case | map | Postgres |
|---|---|---|
| Value holds a NUL byte | stored | rejected, SQLSTATE 22021 |
| Timestamp with nanoseconds | 05.123456789 | 05.123456000 |
| Zero time means no expiry | kept | deleted by the sweep |
| Sort of b, a, B | B a b | a b B (en-US) |
| Create the same key twice | second write replaces the first | rejected, SQLSTATE 23505 |
// normalize makes MemStore agree with Postgres, which cannot store a NUL
// byte and keeps timestamps to the microsecond.
func normalize(it Item) (Item, error) {
if strings.IndexByte(it.Key+it.Value, 0)1 >= 0 {
return Item{}, fmt.Errorf("item %q: %w", it.Key, ErrInvalid)
}
it.ExpiresAt = it.ExpiresAt.UTC().Truncate(time.Microsecond)2
return it, nil
}- 1Rejects a NUL byte before either store sees it.
- 2Both stores now return the same timestamp.
A map accepts things Postgres rejects. The same contract on both stores shows each difference.
// newTx gives one test a transaction that it never commits. The test sees
// its own writes, and the rollback removes them.
func newTx(t *testing.T, pool *pgxpool.Pool) Store {
t.Helper()
tx, err := pool.Begin(context.Background())1
if err != nil {
t.Fatalf("begin: %v", err)
}
t.Cleanup(func() {
if err := tx.Rollback(context.Background()); err != nil {
t.Errorf("rollback: %v", err)
}
})
return NewPGStore(tx)2
}- 1Not t.Context: the rollback in the cleanup must still work.
- 2The store takes a small interface that a pool and a transaction both satisfy.
| isolate by | per test | when |
|---|---|---|
| Transaction, rolled back | 1.0 ms | Code under test does not commit |
| Schema, dropped | 14 ms | Default |
| Database from a template | 101 ms | Tests change roles or extensions |
| Shared tables, truncated | Not measured | Tests cannot run in parallel |
I give each test a transaction when one connection is enough, and a schema when the code commits.
// Stats counts requests and keeps the last key.
type Stats struct {
hits atomic.Int64
last string
}
// Record has a data race: many goroutines write last with no lock.
func (s *Stats) Record(key string) {
s.hits.Add(1)
s.last = key1
}
func TestRecord(t *testing.T) {
var s Stats
var wg sync.WaitGroup
for range 8 {
wg.Go(func() { s.Record("k") })
}
wg.Wait()
if got := s.hits.Load(); got != 8 {2
t.Fatalf("hits = %d, want 8", got)
}
}- 1Eight goroutines write this field with no lock.
- 2The assertion reads the atomic counter, which is correct. It never looks at last.
| command | exit | result |
|---|---|---|
| go test | 0 | Pass, race not seen |
| go test -race | 1 | Fail, race found |
WARNING: DATA RACE in racy.(*Stats).Record
- The detector sees only code that runs. So a concurrent test must exercise the path, and many goroutines must reach it.
- The store benchmark ran 6 times slower with -race. The Go docs say 2 to 20 times slower and 5 to 10 times the memory for a typical program.
- Tests can carry that cost. In production, run a -race build on a canary only.
This test passes without -race. No assertion can see a data race, so CI runs -race.
| since | what changed | what it means here |
|---|---|---|
| 1.14 | t.Cleanup. | The base of every helper in this sheet. |
| 1.15 | t.TempDir. t.Deadline. | No manual cleanup of temporary files. |
| 1.17 | t.Setenv. The -shuffle flag. | -shuffle=on exposes tests that depend on order. |
| 1.18 | Fuzzing: testing.F, go test -fuzz. | Panels J and K. |
| 1.20 | go build -cover, with GOCOVERDIR. | Coverage from integration tests of a whole binary. |
| 1.21 | testing.Testing. The -fullpath flag. | Test logs can show full paths. |
| 1.22 | Each loop iteration has new variables. | No tc := tc before t.Parallel. |
| 1.24 | t.Context, t.Chdir. The vet tests analyzer runs in go test. synctest as an experiment. | Panel L. A misnamed test now fails go test. |
| 1.25 | testing/synctest is generally available. t.Attr, t.Output. AllocsPerRun panics in a parallel test. | Panel M. |
| 1.26 | t.ArtifactDir and the -artifacts flag. Server.Client sends example.com to the test server. | Keep the logs of a failed integration test. |
| 1.27 | synctest.Sleep. httptest.NewTestServer. go test runs the stdversion vet check. go test -json marks output with a type. | Panels I and M. |
| when | the moment | what to do or say |
|---|---|---|
| build | The first endpoint works. | Write a do helper with a recorder and one table now. Each new case then costs one line. |
| build | You add an endpoint. | Add rows for success, missing, bad input and conflict. Assert on status and a substring. |
| build | Test at which level? | Through the handler. One table then proves the route, the status codes and the JSON together. |
| build | The store has a mutex. | Start N goroutines with wg.Go, assert one winner, run go test -race. Say what the test proves. |
| build | Time is part of the feature. | Use synctest. Do not sleep in a test, and do not add a clock interface in the first 45 minutes. |
| build | Which tests to skip? | Skip golden files, fuzzing, mock libraries and test frameworks. They cost typing and prove less than a table. |
| talk | "How do you test the real store?" | Run the same contract on real Postgres. Name what a fake hides, from panel O. |
| talk | "How do tests stay fast and isolated?" | A schema per test, parallel subtests, and a table per endpoint. Give the numbers in panel P. |
| talk | "What do these tests miss?" | Race paths that no test runs, input that nobody thought of, and real load. Then name -race, fuzzing and a load test. |
| talk | "How do you stop flaky tests?" | Remove sleeps with synctest, use -shuffle=on and -count, and isolate data per test. |
I write the do helper first, then one table per endpoint, and I run it with -race before I add the next feature.
0 of 10 known
Predict the output.
package order import ( "fmt" "testing" ) func TestOrder(t *testing.T) { t.Cleanup(func() { fmt.Println("cleanup 1") }) t.Cleanup(func() { fmt.Println("cleanup 2") }) defer fmt.Println("defer") t.Run("sub", func(t *testing.T) { t.Cleanup(func() { fmt.Println("sub cleanup") }) }) fmt.Println("end of body") }Predict the output.
package order import ( "fmt" "testing" ) func TestContext(t *testing.T) { ctx := t.Context() t.Cleanup(func() { fmt.Println("in cleanup:", ctx.Err()) }) fmt.Println("in test:", ctx.Err()) }Predict the output. Read the line numbers.
package helper import "testing" func plain(t *testing.T, ok bool) { if !ok { t.Error("plain failed") } } func marked(t *testing.T, ok bool) { t.Helper() if !ok { t.Error("marked failed") } } func TestLines(t *testing.T) { plain(t, false) marked(t, false) }Predict the output.
package fatal import ( "fmt" "testing" ) func TestFatal(t *testing.T) { done := make(chan struct{}) go func() { defer close(done) t.Fatal("stop") fmt.Println("after Fatal") }() <-done fmt.Println("test goes on") }Predict the output.
package fatal import ( "fmt" "testing" ) func TestTable(t *testing.T) { for _, name := range []string{"a", "b"} { t.Run(name, func(t *testing.T) { t.Fatal("no") fmt.Println("not reached") }) fmt.Println("next case after", name) } }Predict the output.
package env import "testing" func TestEnv(t *testing.T) { t.Parallel() t.Setenv("MODE", "test") }Predict the output.
package names import ( "fmt" "testing" ) func TestNames(t *testing.T) { for _, name := range []string{"a b", "a b", "x/y"} { t.Run(name, func(t *testing.T) { fmt.Println(t.Name()) }) } }Predict the output.
package clock import ( "context" "fmt" "testing" "testing/synctest" "time" ) func TestClock(t *testing.T) { synctest.Test(t, func(t *testing.T) { start := time.Now() ctx, cancel := context.WithTimeout(t.Context(), time.Hour) defer cancel() <-ctx.Done() fmt.Println(start.UTC(), time.Since(start)) }) }Predict the output.
package clock import ( "testing" "testing/synctest" ) func TestStuck(t *testing.T) { synctest.Test(t, func(t *testing.T) { ch := make(chan int) go func() { <-ch }() }) }Predict the output.
package allocs import "testing" func TestAllocs(t *testing.T) { t.Parallel() testing.AllocsPerRun(10, func() {}) }
- recorder
- 4.0 µs per request; a real server costs about 19 times that.
- transaction
- 1.0 ms per test.
- schema
- 14 ms per test.
- database
- 101 ms per test.
- -race
- 6 times slower on the store benchmark.
- fuzz find
- 0.31 s to the first failing input.
Go 1.27.3, 8-core Intel i9 laptop, median of 5 interleaved rounds, on a busy machine. Use these as orders of magnitude.