Subscribe

Golang Tutorial 17: Testing

Table-driven tests, subtests, t.Helper, httptest, coverage, the race detector and fuzzing in Go 1.27. The fuzzer found two real bugs in a base62 short code decoder in under a second each.

Golang Tutorial 17: Testing

Go ships its test tool in the box. No framework to pick, no config file, just go test. In this blog we will test two small packages from a URL shortener: one that turns numbers into short codes like aZ3, and an HTTP handler that redirects them. On the way we use table-driven tests, subtests, t.Helper, httptest, coverage, the race detector and fuzzing. The fuzzer found two real bugs in my decoder, which made this post a lot more fun to write than I planned.

Level is beginner, but you should have read the earlier tutorials up to Tutorial 14 for the goroutine parts. I used Go 1.27.3.

mkdir tut17 && cd tut17
go mod init example.com/tut17
mkdir shortcode api

The code under test

The short codes are base62: digits, then upper case, then lower case, same alphabet as the shorty app from the REST API post. This is the first version of Decode I wrote. Keep an eye on it, it has two bugs.

// Package shortcode turns numeric IDs into short base62 codes and back.
package shortcode

import (
    "errors"
    "strings"
)

const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

var ErrInvalid = errors.New("invalid short code")

func Encode(n uint64) string {
    if n == 0 {
        return "0"
    }
    var b []byte
    for n > 0 {
        b = append(b, alphabet[n%62])
        n /= 62
    }
    for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
        b[i], b[j] = b[j], b[i]
    }
    return string(b)
}

func Decode(s string) (uint64, error) {
    if s == "" {
        return 0, ErrInvalid
    }
    var n uint64
    for _, r := range s {
        i := strings.IndexRune(alphabet, r)
        if i < 0 {
            return 0, ErrInvalid
        }
        n = n*62 + uint64(i)
    }
    return n, nil
}

Table-driven tests and subtests

Test files end in _test.go and sit next to the code. A test is a function TestXxx(t *testing.T). The usual Go style is a table: a slice of cases, one loop, and t.Run to give every case its own name.

package shortcode

import (
    "errors"
    "testing"
)

func TestEncode(t *testing.T) {
    tests := []struct {
        name string
        in   uint64
        want string
    }{
        {"zero", 0, "0"},
        {"single digit", 7, "7"},
        {"last letter", 61, "z"},
        {"rolls over", 62, "10"},
        {"bigger", 125, "21"},
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := Encode(tt.in); got != tt.want {
                t.Errorf("Encode(%d) = %q, want %q", tt.in, got, tt.want)
            }
        })
    }
}

func TestDecodeInvalid(t *testing.T) {
    for _, in := range []string{"", "abc-1", "héllo", " "} {
        t.Run(in, func(t *testing.T) {
            if _, err := Decode(in); !errors.Is(err, ErrInvalid) {
                t.Errorf("Decode(%q) err = %v, want ErrInvalid", in, err)
            }
        })
    }
}
go test ./shortcode/
go test -v -run 'TestEncode/rolls' ./shortcode/

Subtests get names like TestEncode/rolls_over (spaces become underscores), and -run takes a regex on them, so you can run one case while you debug it. t.Errorf marks the test failed and carries on, t.Fatalf stops this test or subtest right there. Use Fatal when the rest makes no sense, for example after a nil response.

Adding case is one line. That's the main reason for tables, honestly. When someone reports a bug you add the input that broke it as a new row and it stays there.

Both tests passed. So I thought Decode was fine, it was not.

Fuzzing found two bugs

A fuzz test gives Go a property that must always hold and lets it invent inputs. Here the property is: if Decode accepts a string, encoding the number again must give back the same string. Otherwise two different codes would point to one link.

func FuzzRoundTrip(f *testing.F) {
    f.Add("0")
    f.Add("abc")
    f.Add("z10")
    f.Fuzz(func(t *testing.T, s string) {
        n, err := Decode(s)
        if err != nil {
            return // invalid input is fine, it just has to be rejected
        }
        if back := Encode(n); back != s {
            t.Errorf("Decode(%q) = %d, but Encode(%d) = %q", s, n, n, back)
        }
    })
}
go test -run=^$ -fuzz=FuzzRoundTrip -fuzztime=30s ./shortcode/

It failed in the first second itself.

fuzz: elapsed: 0s, minimizing
    shortcode_test.go:49: Decode("00") = 0, but Encode(0) = "0"
    Failing input written to testdata/fuzz/FuzzRoundTrip/...

Leading zeros. "00", "007" and "7" all decode to 7. In a URL shortener that means /007 would quietly redirect to the same place as /7, which nobody would notice for months. I fixed it by rejecting a leading zero unless the whole code is "0", and ran the fuzzer again.

    shortcode_test.go:49: Decode("X0000000000") = 9250134999945675776, but Encode(9250134999945675776) = "B1JiPytpiRk"

Overflow this time, the fuzzer found it just as quick. Eleven base62 characters can be bigger than a uint64, so n*62 wrapped around silently and two codes mapped to one number. The fix is to check before multiplying. Here's the final Decode (add "math" to the imports).

func Decode(s string) (uint64, error) {
    if s == "" || (len(s) > 1 && s[0] == '0') {
        return 0, ErrInvalid // no leading zeros, "007" must not equal "7"
    }
    var n uint64
    for _, r := range s {
        i := strings.IndexRune(alphabet, r)
        if i < 0 {
            return 0, ErrInvalid
        }
        if n > (math.MaxUint64-uint64(i))/62 {
            return 0, ErrInvalid // would overflow uint64
        }
        n = n*62 + uint64(i)
    }
    return n, nil
}

After that it ran a full minute clean: about 24.8 million inputs on 10 workers on my Mac. The two failing inputs stay in testdata/fuzz/FuzzRoundTrip/ and plain go test runs them every time from now on, like table rows I didn't have to write. Commit that folder.

I would not have wrote either of those as table cases. That's the whole argument for fuzzing anything that parses input.

Testing an HTTP handler

The redirect handler keeps a map of codes and counts hits.

// Package api serves redirects for short codes.
package api

import (
    "net/http"
    "sync"
)

type Server struct {
    links map[string]string // code -> long URL

    mu   sync.Mutex
    hits map[string]int
}

func NewServer(links map[string]string) *Server {
    return &Server{links: links, hits: map[string]int{}}
}

func (s *Server) Handler() http.Handler {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /{code}", s.redirect)
    return mux
}

func (s *Server) redirect(w http.ResponseWriter, r *http.Request) {
    code := r.PathValue("code")
    long, ok := s.links[code]
    if !ok {
        http.NotFound(w, r)
        return
    }
    s.mu.Lock()
    s.hits[code]++
    s.mu.Unlock()
    http.Redirect(w, r, long, http.StatusFound)
}

func (s *Server) Hits(code string) int {
    s.mu.Lock()
    defer s.mu.Unlock()
    return s.hits[code]
}

Basically, httptest.NewRecorder is a fake ResponseWriter. You call the handler directly, no network, and look at what it wrote. The two helpers call t.Helper(), so when an assert fails the error points at the line in the test that called it, not at a line inside the helper.

package api

import (
    "net/http"
    "net/http/httptest"
    "sync"
    "testing"
)

func newTestServer(t *testing.T) *Server {
    t.Helper()
    return NewServer(map[string]string{
        "abc": "https://example.com/a/very/long/path",
    })
}

func assertStatus(t *testing.T, got, want int) {
    t.Helper()
    if got != want {
        t.Fatalf("status = %d, want %d", got, want)
    }
}

func TestRedirect(t *testing.T) {
    s := newTestServer(t)
    h := s.Handler()

    t.Run("known code", func(t *testing.T) {
        rec := httptest.NewRecorder()
        req := httptest.NewRequest("GET", "/abc", nil)
        h.ServeHTTP(rec, req)

        assertStatus(t, rec.Code, http.StatusFound)
        if loc := rec.Header().Get("Location"); loc != "https://example.com/a/very/long/path" {
            t.Errorf("Location = %q", loc)
        }
    })

    t.Run("unknown code", func(t *testing.T) {
        rec := httptest.NewRecorder()
        h.ServeHTTP(rec, httptest.NewRequest("GET", "/nope", nil))
        assertStatus(t, rec.Code, http.StatusNotFound)
    })
}

func TestRedirectOverHTTP(t *testing.T) {
    s := newTestServer(t)
    srv := httptest.NewServer(s.Handler())
    t.Cleanup(srv.Close)

    client := srv.Client()
    client.CheckRedirect = func(*http.Request, []*http.Request) error {
        return http.ErrUseLastResponse // don't follow, we want to see the 302
    }

    req, _ := http.NewRequestWithContext(t.Context(), "GET", srv.URL+"/abc", nil)
    resp, err := client.Do(req)
    if err != nil {
        t.Fatal(err)
    }
    defer resp.Body.Close()
    assertStatus(t, resp.StatusCode, http.StatusFound)
}

httptest.NewServer starts a real server on a local port, which is useful when you want middleware, real headers and a real client. t.Context() (Go 1.24) is a context that is cancelled when the test ends, so a stuck request can't outlive the test. Contexts were Tutorial 15.

Go 1.27 added httptest.NewTestServer(t, handler). It closes itself at the end of the test and uses an in-memory network by default, which is mainly meant for testing/synctest. It worked fine in a normal test too when I tried it.

The race detector

The first version of the handler had no mutex, just s.hits[code]++. I wrote a test that sends 50 requests at once.

func TestConcurrentHits(t *testing.T) {
    s := newTestServer(t)
    h := s.Handler()

    var wg sync.WaitGroup
    for range 50 {
        wg.Go(func() {
            h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/abc", nil))
        })
    }
    wg.Wait()
    if got := s.Hits("abc"); got != 50 {
        t.Errorf("hits = %d, want 50", got)
    }
}

I actually expected to need -race to see the problem. I didn't. Plain go test crashed the whole test binary.

fatal error: concurrent map writes

goroutine 92 [running]:
...
example.com/tut17/api.(*Server).redirect(...)
    .../api/api.go:30 +0xd4

Go maps has a cheap built-in check for this. It doesn't catch every case, and with an int counter instead of a map you would only get wrong numbers, never a crash. That's where go test -race comes in: it reported WARNING: DATA RACE with both stack traces pointing into redirect and the hits map. With the mutex added, both runs pass.

go test -race ./...

Make -race the default in CI. The CI workflow post has a GitHub Actions setup for exactly that.

Coverage

go test -cover ./...
go test -coverprofile=cover.out ./...
go tool cover -func=cover.out
go tool cover -html=cover.out
ok      example.com/tut17/api   0.925s  coverage: 100.0% of statements
ok      example.com/tut17/shortcode 0.465s  coverage: 100.0% of statements

100% on toy package, of course. The -html view is the useful one: red lines are code no test ran. I don't chase a coverage number on real services. I look at the red lines in code that handles money, auth or parsing, and make sure those aren't red.

Exercise

Write the fuzz test the other way round: for any uint64, Decode(Encode(n)) must give back n with no error. Seed it with 0, 61 and ^uint64(0) (the largest uint64). Run it with -fuzz for 15 seconds. If you got the overflow check wrong by one, this is the test that tells you, because the largest value sits right on the edge.