System Design

G20

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.

Not startedSaved in this browser only.
  1. 1Register shared resources with t.Cleanup, not defer. A defer runs before parallel subtests resume.
  2. 2Test the handler through a table, and keep every store behind one contract test.
  3. 3A fake hides what the real database does. Run the same contract on real Postgres.
  4. 4Time, races and odd input need their own tools: synctest, -race and fuzzing. Assertions alone do not find them.
G20
    A

    The trap

    one word: defer
    a server shared by parallel subtestsgo
    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()
        })
      }
    }
    1. 1Runs when TestAPI returns. The subtests have paused and have not sent a request yet.
    2. 2Pauses this subtest. It resumes after the parent function has returned.
    3. 3The server has closed, so every request fails.
    lineexitstatus
    defer srv.Close()1Both subtests fail
    t.Cleanup(srv.Close)0Both pass
    recorded output, with deferoutput
        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.

    B

    The model: one test, step by step

    recorded: each step is one line the run printed
    the run belowgo
    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())
    }
    1. 1The subtest pauses here, and t.Run returns to the parent.
    2. 2Runs before the parallel subtest resumes.
    TestLifeserialparallel1234567
    parent body

    The test function starts. Its context is live.

    line 1 of 7

    The order is: body, serial subtests, defers, parallel subtests, then context cancel and cleanups.

    C

    The rules

    what to do and what to avoid
    rulewhystatus
    One table, one loop, one t.Run per caseEach case has a name, runs alone with -run, and fails alone.Approved
    Call t.Helper first in a helperThe failure points at the test line, not the helper.Approved
    Use t.Cleanup for resources that subtests shareIt waits for parallel subtests. See panel A.Approved
    Use t.Context for work the test startsIt ends before cleanups, so a cleanup can wait for the work to stop.Approved
    Use a real Postgres for store testsA fake has different rules. See panel O.Approved
    Use -race in CI on every packageIt finds races that no assertion sees. See panel Q.Approved
    Use t.Parallel on pure table casesIt shortens the run and exposes shared state.Not with Setenv or Chdir
    Assert on errors with errors.IsThe text of a wrapped error can change.Approved
    Keep a mock for a third party you cannot runA mock tests your guess at its behaviour.Only at a process boundary
    Use time.Sleep to wait for a goroutineIt is slow when it passes and flaky under load. Use synctest.Not approved
    Call t.Fatal from another goroutineIt 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 showA 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.

    D

    Table tests

    tested
    fields_testgo
    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)
          }
        })
      }
    }
    1. 1A nil err means the case expects success, and errors.Is(nil, nil) is true.
    2. 2The inner t hides the outer one, so a failure belongs to this case.
    3. 3Safe with tc since Go 1.22: each iteration has its own variable.
    4. 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.

    E

    Helpers

    tested
    helpersgo
    // 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
    }
    1. 1Failure reports skip this frame and name the caller.
    2. 2Ends with the test, so a stuck call cannot outlive it.
    3. 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.

    F

    Fixtures and testdata

    tested
    fixturego
    // 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
    }
    1. 1go test runs each test binary in its package directory, so the relative path always works.
    2. 2A missing fixture fails at the test that asked for it.
    the data iskeep it in
    A few fieldsA literal in the table
    Large or binaryA file in testdata
    Built with rulesA helper that takes options

    Fixture files live in testdata. The go tool ignores that directory, and tests run in the package directory.

    G

    Golden files

    tested
    goldengo
    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)
      }
    }
    1. 1Run go test -update once, then read the diff before you commit.
    2. 2The test compares bytes, so the output must be deterministic. Sort any map first.
    report.goldenfile
    KEY               VALUE   EXPIRES
    alpha             first   never
    bravo             second  2026-11-23 09:30:00
    charlie-long-key  third   never

    For long output, the expected text lives in a file. A flag rewrites it, and the diff shows in review.

    H

    httptest: a table over the handler

    tested
    handler tablego
    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)
          }
        })
      }
    }
    1. 1A ResponseWriter in memory. No socket, so no port and no goroutine.
    2. 2Builds a server-side request. It panics on a bad input, so it needs no error check.
    3. 3Each case has its own store, so the parallel cases share nothing.
    4. 4net/http gives this 405 from the method in the route pattern. The table proves the pattern.
    toolone requestuse it for
    NewRecorder4.0 µsHandler logic
    NewServer77 µsA real client, TLS, redirects
    NewTestServerFake networkA client in a synctest bubble

    I test through the handler with a recorder. One table covers routing, status codes and JSON, with no port.

    I

    httptest on a fake network

    tested, Go 1.27
    retry with backoffgo
    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)
        }
      })
    }
    1. 1Starts a bubble with a fake clock. The t inside belongs to the bubble.
    2. 2New in Go 1.27. The connection is in memory, so a blocked read is durably blocked.
    3. 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.

    J

    Fuzzing: a real find

    recorded: found in a median of 0.31 s over 3 cold runs
    first version of the encodergo
    // 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())
    }
    1. 1Escapes commas, and leaves a backslash as it is.
    2. 2A backslash that ends a field now reads as an escape of the separator.
    inputlineresult
    "a", "b"a,bRound trip holds
    "a,b", "c"a\,b,cRound trip holds
    "", "",Round trip holds
    "a\b", "c"a\b,cRound trip holds
    "日本語", "x"日本語,xRound trip holds
    "\\", "0"\,0Became [",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.

    K

    The fuzz target and the fix

    tested
    fuzz targetgo
    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)
        }
      })
    }
    1. 1The seed corpus. Plain go test runs only these and the files in testdata/fuzz.
    2. 2The arguments after t set the types the fuzzer mutates.
    3. 3A property, not an example. Round trips suit fuzzing well.
    fixed encodergo
    // 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
    }
    1. 1The fix: escape the escape character too.
    2. 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.

    L

    t.Context

    tested, Go 1.24
    start a worker for one testgo
    // 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
    }
    1. 1The context ends after the test, and before cleanups.
    2. 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.

    M

    testing/synctest

    tested, Go 1.25; Sleep Go 1.27
    a sweep on a fake clockgo
    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
        }
      })
    }
    1. 1Inside a bubble, time.Now reads the fake clock.
    2. 2Go 1.27: time.Sleep, then synctest.Wait. The sweep at 60 s has finished when it returns.
    3. 3The short item expired at 90 s. The sweep at 120 s removed it.
    a goroutine waits ondurable
    Channel from this bubble, time.Sleep, Cond.Wait, WaitGroup.WaitApproved
    Mutex, a real socket, a system callTime 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.

    N

    One contract, every store

    tested on memory and on real Postgres
    run the contract on both storesgo
    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)
    }
    1. 1The contract has 7 subtests. Each one opens its own store.
    2. 2Isolation by schema. It also works with code that commits or opens its own transactions.
    3. 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.

    O

    What a fake hides

    recorded: same operation on a map and on a real table
    casemapPostgres
    Value holds a NUL bytestoredrejected, SQLSTATE 22021
    Timestamp with nanoseconds05.12345678905.123456000
    Zero time means no expirykeptdeleted by the sweep
    Sort of b, a, BB a ba b B (en-US)
    Create the same key twicesecond write replaces the firstrejected, SQLSTATE 23505
    the fix: one rule for both storesgo
    // 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
    }
    1. 1Rejects a NUL byte before either store sees it.
    2. 2Both stores now return the same timestamp.

    A map accepts things Postgres rejects. The same contract on both stores shows each difference.

    P

    Isolate a test on a real database

    measured, one test
    a transaction per testgo
    // 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
    }
    1. 1Not t.Context: the rollback in the cleanup must still work.
    2. 2The store takes a small interface that a pool and a transaction both satisfy.
    isolate byper testwhen
    Transaction, rolled back1.0 msCode under test does not commit
    Schema, dropped14 msDefault
    Database from a template101 msTests change roles or extensions
    Shared tables, truncatedNot measuredTests cannot run in parallel

    I give each test a transaction when one connection is enough, and a schema when the code commits.

    Q

    The race detector

    recorded: the same test, two ways
    a test that passes and hides a racego
    // 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)
      }
    }
    1. 1Eight goroutines write this field with no lock.
    2. 2The assertion reads the atomic counter, which is correct. It never looks at last.
    commandexitresult
    go test0Pass, race not seen
    go test -race1Fail, 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.

    R

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.14t.Cleanup.The base of every helper in this sheet.
    1.15t.TempDir. t.Deadline.No manual cleanup of temporary files.
    1.17t.Setenv. The -shuffle flag.-shuffle=on exposes tests that depend on order.
    1.18Fuzzing: testing.F, go test -fuzz.Panels J and K.
    1.20go build -cover, with GOCOVERDIR.Coverage from integration tests of a whole binary.
    1.21testing.Testing. The -fullpath flag.Test logs can show full paths.
    1.22Each loop iteration has new variables.No tc := tc before t.Parallel.
    1.24t.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.25testing/synctest is generally available. t.Attr, t.Output. AllocsPerRun panics in a parallel test.Panel M.
    1.26t.ArtifactDir and the -artifacts flag. Server.Client sends example.com to the test server.Keep the logs of a failed integration test.
    1.27synctest.Sleep. httptest.NewTestServer. go test runs the stdversion vet check. go test -json marks output with a type.Panels I and M.
    S

    In the round

    what the first 45 minutes want from your tests
    whenthe momentwhat to do or say
    buildThe first endpoint works.Write a do helper with a recorder and one table now. Each new case then costs one line.
    buildYou add an endpoint.Add rows for success, missing, bad input and conflict. Assert on status and a substring.
    buildTest at which level?Through the handler. One table then proves the route, the status codes and the JSON together.
    buildThe store has a mutex.Start N goroutines with wg.Go, assert one winner, run go test -race. Say what the test proves.
    buildTime 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.
    buildWhich 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.

    T

    Drill

    each answer is the output of a real run

    0 of 10 known

    1. 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")
      }
    2. 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())
      }
    3. 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)
      }
    4. 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")
      }
    5. 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)
        }
      }
    6. Predict the output.

      package env
      
      import "testing"
      
      func TestEnv(t *testing.T) {
        t.Parallel()
        t.Setenv("MODE", "test")
      }
    7. 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()) })
        }
      }
    8. 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))
        })
      }
    9. 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 }()
        })
      }
    10. Predict the output.

      package allocs
      
      import "testing"
      
      func TestAllocs(t *testing.T) {
        t.Parallel()
        testing.AllocsPerRun(10, func() {})
      }
    U

    Numbers to say

    measured
    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.