34. Testing with go test

How do you know a function works? So far, you ran the program and looked at what it printed. That works once. But every time you change the code, you would have to run it again, try all the cases again, and read all the output again. Nobody does that for long, so mistakes creep back in unnoticed.

A test is a small piece of code that does the checking for you. It calls your function with an input, compares the answer with the one you expect, and complains if they differ. Go has testing built in: the testing package to write tests, and the command go test to run them. This chapter shows how to write tests, how to run them, and how to test the cases that matter most: the edges, the errors, and code that writes files.

A first test

Tests live next to the code they test, in the same folder and the same package. Here is exercises/34/examples/01-first-test/:

01-first-test/
    go.mod
    words.go
    words_test.go

words.go is an ordinary package with two functions, as in Chapter 25:

package words

import "strings"

// Count returns the number of words in s. Words are separated by spaces,
// tabs or line endings.
func Count(s string) int {
    return len(strings.Fields(s))
}

// Shout returns s in upper case with "!" added.
func Shout(s string) string {
    return strings.ToUpper(s) + "!"
}

words_test.go holds the tests:

package words

import "testing"

func TestCount(t *testing.T) {
    got := Count("the quick brown fox")
    if got != 4 {
        t.Errorf("Count(\"the quick brown fox\") = %d, want 4", got)
    }

    got = Count("  two   words  ")
    if got != 2 {
        t.Errorf("Count(\"  two   words  \") = %d, want 2", got)
    }
}

func TestShout(t *testing.T) {
    got := Shout("hello")
    if got != "HELLO!" {
        t.Errorf("Shout(\"hello\") = %q, want %q", got, "HELLO!")
    }
}

Four rules make this a test file:

  • The file name ends in _test.go. go test reads these files. go run and go build leave them out, so tests never end up in your program.
  • It has the same package line as the code it tests, package words. Because it is the same package, a test can call lower case names too, which other packages cannot.
  • It imports testing.
  • Each test is a function whose name starts with Test, followed by a capital letter, and that takes one parameter, t *testing.T. It returns nothing.

The body is plain Go: call the function, and check the answer with if. When the answer is wrong, t.Errorf reports it. It takes a format, like fmt.Printf, and marks the test as failed. The \" inside the message is a quote mark inside a string, as in Chapter 12.

The message follows a habit that Go programmers share: the call, what it gave, and what was wanted, as in Shout("hello") = "HELLO?", want "HELLO!". When a test fails months later, that line alone tells you what went wrong, without opening the test file. %q puts quotes around strings, so that a stray space or an empty string is easy to see.

Running the tests

go test works on a module, like go run . in Chapter 25, so go into the folder first. From go-work:

cd exercises/34/examples/01-first-test
go test

Output:

PASS
ok      words   0.215s

PASS means every test passed. The last line names the package, words, and how long it took. That time is different on every run, and on your computer.

When everything passes, go test says little. To see each test, add -v ("verbose"):

go test -v

=== RUN   TestCount
--- PASS: TestCount (0.00s)
=== RUN   TestShout
--- PASS: TestShout (0.00s)
PASS
ok      words   0.198s

=== RUN is printed when a test starts, and --- PASS when it ends. Go finds the tests by their names: every Test function in every _test.go file of the folder. You never call them yourself.

When you are done in this folder, go back up to go-work. The folder is four levels down:

cd ../../../..

A failing test

A test is only useful if it fails when the code is wrong. Make it wrong on purpose. In words.go, change "!" to "?" in Shout, and run go test again:

--- FAIL: TestShout (0.00s)
    words_test.go:22: Shout("hello") = "HELLO?", want "HELLO!"
FAIL
exit status 1
FAIL    words   0.231s

Read it from the top:

  • --- FAIL: TestShout names the test that failed. TestCount passed, and a passing test prints nothing without -v.
  • words_test.go:22 is the file and line of the t.Errorf call, followed by its message.
  • FAIL at the end, and the exit code 1, mean that at least one test failed. A script can check that exit code, as Chapter 32 explained.

Change "?" back to "!", and the tests pass again.

Break Count instead: change it to return len(strings.Split(s, " ")). Run go test. Which of the two checks in TestCount fails, and why does the other one pass? Put it back afterwards.

Table-driven tests

TestCount checks two cases with two if blocks that look almost the same. With ten cases, that is ten copies. Go programmers write it differently: they put the cases in a table, a slice with one row per case, and loop over it with one if. This is exercises/34/examples/02-table-test/. The function in grade.go turns a score into a letter:

// Letter turns a score from 0 to 100 into a letter grade.
func Letter(score int) string {
    switch {
    case score >= 90:
        return "A"
    case score >= 80:
        return "B"
    case score >= 70:
        return "C"
    case score >= 60:
        return "D"
    default:
        return "F"
    }
}

And grade_test.go tests it with a table:

func TestLetter(t *testing.T) {
    tests := []struct {
        name  string
        score int
        want  string
    }{
        {"top score", 100, "A"},
        {"lowest A", 90, "A"},
        {"just below A", 89, "B"},
        {"lowest C", 70, "C"},
        {"lowest D", 60, "D"},
        {"just below D", 59, "F"},
        {"zero", 0, "F"},
    }

    for _, tc := range tests {
        t.Run(tc.name, func(t *testing.T) {
            got := Letter(tc.score)
            if got != tc.want {
                t.Errorf("Letter(%d) = %q, want %q", tc.score, got, tc.want)
            }
        })
    }
}

Two things are new here.

A struct with no name. []struct { ... } is a slice of structs whose type is written right where it is used, without a type line. The table is the only place that needs this type, so it gets no name. Each row in the second pair of braces fills the fields in order: {"lowest A", 90, "A"} sets name, score and want. The loop variable is usually called tc, for "test case".

t.Run runs one row as a subtest, with its own name. The test itself is a function literal, as in Chapter 31. Its parameter is also called t: inside, t means the subtest. Each row passes or fails on its own, and its name shows up in the output:

cd exercises/34/examples/02-table-test
go test -v

=== RUN   TestLetter
=== RUN   TestLetter/top_score
=== RUN   TestLetter/lowest_A
=== RUN   TestLetter/just_below_A
=== RUN   TestLetter/lowest_C
=== RUN   TestLetter/lowest_D
=== RUN   TestLetter/just_below_D
=== RUN   TestLetter/zero
--- PASS: TestLetter (0.00s)
    --- PASS: TestLetter/top_score (0.00s)
    --- PASS: TestLetter/lowest_A (0.00s)
    --- PASS: TestLetter/just_below_A (0.00s)
    --- PASS: TestLetter/lowest_C (0.00s)
    --- PASS: TestLetter/lowest_D (0.00s)
    --- PASS: TestLetter/just_below_D (0.00s)
    --- PASS: TestLetter/zero (0.00s)
PASS
ok      grade   0.204s

A subtest's full name is the test's name, a /, and the row's name, with spaces turned into _.

Adding a case is now one line. Look at which cases the table holds: 90 and 89, 60 and 59. Mistakes hide at the edges, where the answer changes. Writing > where >= was meant gets 85 right and 90 wrong. A good table tests each edge from both sides, plus the very top and bottom.

Running only some tests

-run picks which tests to run. It takes part of a test's name, and runs the tests whose name contains it. For a subtest, give the test's name, a /, and part of the row's name:

go test -v -run TestLetter/lowest

=== RUN   TestLetter
=== RUN   TestLetter/lowest_A
=== RUN   TestLetter/lowest_C
=== RUN   TestLetter/lowest_D
--- PASS: TestLetter (0.00s)
    --- PASS: TestLetter/lowest_A (0.00s)
    --- PASS: TestLetter/lowest_C (0.00s)
    --- PASS: TestLetter/lowest_D (0.00s)
PASS
ok      grade   0.187s

This is handy when one row fails: run just that row while you fix it. Write the underscores, as in the output: -run TestLetter/just_below_D.

A -run that matches nothing is not an error. Mistype the name, and go test runs no tests at all, prints testing: warning: no tests to run, and still says ok. Use -v with -run, so that you can see what really ran.

Go back up to go-work with cd ../../../.. before the next example.

Errorf and Fatalf

t.Errorf marks the test as failed and carries on. That is usually what you want: if several checks are wrong, you see all of them in one run.

Sometimes carrying on makes no sense. exercises/34/examples/03-testing-errors/ has a function that reads a percentage, such as "85" or "85%", and returns an error for bad text. In percent.go:

// ErrOutOfRange means the number was not from 0 to 100.
var ErrOutOfRange = errors.New("percent must be from 0 to 100")

// Parse turns text such as "85" or "85%" into a number from 0 to 100.
func Parse(text string) (int, error) {
    text = strings.TrimSpace(text)
    text = strings.TrimSuffix(text, "%")

    number, err := strconv.Atoi(text)
    if err != nil {
        return 0, fmt.Errorf("%q is not a number", text)
    }
    if number < 0 || number > 100 {
        return 0, fmt.Errorf("%d: %w", number, ErrOutOfRange)
    }
    return number, nil
}

ErrOutOfRange is a sentinel error, and the %w wraps it, as Chapter 33 showed. strings.TrimSuffix removes % from the end, if it is there.

The test for good input, in percent_test.go:

    for _, tc := range tests {
        t.Run(tc.text, func(t *testing.T) {
            got, err := Parse(tc.text)
            if err != nil {
                t.Fatalf("Parse(%q) gave the error %v", tc.text, err)
            }
            if got != tc.want {
                t.Errorf("Parse(%q) = %d, want %d", tc.text, got, tc.want)
            }
        })
    }

If Parse returns an error, the number next to it means nothing, as Chapter 21 said. Comparing it with want would only add a second, confusing message. t.Fatalf marks the test as failed and stops it right there. In a subtest, only that subtest stops: the other rows still run.

The rule of thumb:

  • t.Errorf when the next checks still make sense.
  • t.Fatalf when they do not: an error you did not expect, a file that could not be written, a slice too short to index.

t.Error and t.Fatal, without the f, do the same with a plain message, as fmt.Println does compared with fmt.Printf.

Testing errors

Good tests check the bad cases too. A function that should refuse bad input, but quietly accepts it, is a bug. There are three things a test can want from an error, and percent_test.go has one of each.

No error. That is TestParseGood above: err != nil is a failure.

Some error, any kind. Text that is not a number must give an error. Which message it is does not matter here:

func TestParseNotANumber(t *testing.T) {
    _, err := Parse("abc")
    if err == nil {
        t.Fatal("Parse(\"abc\") gave no error")
    }
}

A particular error. A number outside 0 to 100 must give ErrOutOfRange, and nothing else. errors.Is from Chapter 33 checks that, and it looks through the wrapping:

func TestParseOutOfRange(t *testing.T) {
    for _, text := range []string{"-1", "101", "150%"} {
        t.Run(text, func(t *testing.T) {
            _, err := Parse(text)
            if !errors.Is(err, ErrOutOfRange) {
                t.Errorf("Parse(%q) error = %v, want ErrOutOfRange", text, err)
            }
        })
    }
}

The table here is just a slice of strings, since each row needs nothing else. For "150%", the error's text is 150: percent must be from 0 to 100, yet errors.Is still finds ErrOutOfRange inside it. You could compare the error's text instead, but then the test breaks whenever someone rewords the message. The sentinel is what callers check, so it is what the test checks.

Now break Parse: delete the line with strings.TrimSuffix, and run go test from the folder:

--- FAIL: TestParseGood (0.00s)
    --- FAIL: TestParseGood/85% (0.00s)
        percent_test.go:25: Parse("85%") gave the error "85%" is not a number
--- FAIL: TestParseOutOfRange (0.00s)
    --- FAIL: TestParseOutOfRange/150% (0.00s)
        percent_test.go:46: Parse("150%") error = "150%" is not a number, want ErrOutOfRange
FAIL
exit status 1
FAIL    percent 0.226s

Two rows fail, each with one clear line. t.Fatalf stopped the 85% row before it could add Parse("85%") = 0, want 85. The 150% row shows why checking the kind of error matters: it still got an error, just the wrong one. Put the line back before moving on.

Tests that use files

Code that reads and writes files needs files to test with. Writing them into your own folder is a bad idea: a test could overwrite something you care about, and leftover files from the last run could make the next one pass when it should not.

t.TempDir() gives the test a new, empty folder of its own, somewhere in your computer's temporary folder. Go deletes it, and everything in it, when the test ends. Every call gives a different folder, so tests never see each other's files.

exercises/34/examples/04-temp-dir/notes.go saves notes to a file and loads them back:

// Save writes the notes to a file, one per line.
func Save(filename string, notes []string) error {
    text := strings.Join(notes, "\n") + "\n"
    return os.WriteFile(filename, []byte(text), 0644)
}

// Load reads the notes back. Empty lines are skipped.
func Load(filename string) ([]string, error) {
    data, err := os.ReadFile(filename)
    if err != nil {
        return nil, err
    }

    notes := []string{}
    for _, line := range strings.Split(string(data), "\n") {
        line = strings.TrimSpace(line)
        if line != "" {
            notes = append(notes, line)
        }
    }
    return notes, nil
}

The tests in notes_test.go:

func TestSaveThenLoad(t *testing.T) {
    filename := filepath.Join(t.TempDir(), "notes.txt")
    want := []string{"buy milk", "call Arif"}

    err := Save(filename, want)
    if err != nil {
        t.Fatalf("Save: %v", err)
    }

    got, err := Load(filename)
    if err != nil {
        t.Fatalf("Load: %v", err)
    }
    if !slices.Equal(got, want) {
        t.Errorf("Load gave %q, want %q", got, want)
    }
}

func TestLoadMissingFile(t *testing.T) {
    filename := filepath.Join(t.TempDir(), "missing.txt")

    _, err := Load(filename)
    if !errors.Is(err, os.ErrNotExist) {
        t.Errorf("Load of a missing file: error = %v, want os.ErrNotExist", err)
    }
}
  • filepath.Join from Chapter 31 builds a path inside the temporary folder.
  • TestSaveThenLoad checks the two functions together: what Save writes, Load must read back the same. This round trip is the natural test for any pair of functions that write and read a format.
  • Slices cannot be compared with ==. slices.Equal from the slices package (Chapter 24) says whether two slices have the same length and the same items in the same order. %q on a slice of strings prints each one in quotes: ["buy milk" "call Arif"].
  • TestLoadMissingFile uses a name inside an empty folder, so the file is certain not to exist. The os.ErrNotExist check is the one from Chapter 31.

Run them from the folder:

cd exercises/34/examples/04-temp-dir
go test -v

=== RUN   TestSaveThenLoad
--- PASS: TestSaveThenLoad (0.00s)
=== RUN   TestLoadMissingFile
--- PASS: TestLoadMissingFile (0.00s)
PASS
ok      notes   0.241s

Look in the folder afterwards: no notes.txt was left behind.

How much is tested?

-cover adds one more number to the result: how much of the code the tests ran.

go test -cover

PASS
coverage: 100.0% of statements
ok      notes   0.219s  coverage: 100.0% of statements

100% means every line of Save and Load ran at least once during the tests. A lower number points at code no test reached, often the error handling. But a line that ran is not a line that was checked: a test with no if at all can reach 100%. Use the number to find what you forgot, not as a score.

Writing code that is easy to test

Some code is easy to test, and some is not. Compare two versions of a word counter:

  • One reads a file name from os.Args, opens the file, counts the words, and prints the count.
  • The other is a function Count(s string) int.

The second is easy: give it a string, check the number. To test the first, you would have to run the whole program and read its output. So the habit is: put the work in functions that take values and return values, and keep main thin. main reads the arguments, calls the functions, and prints. The functions do the thinking, and the tests check the functions. Packages help, as in this chapter: the work lives in a package with tests, and package main only uses it.

The Part 7 mini-project is built this way. Its tasks package does all the work and has the tests, and its main.go only handles the command line. When a module has packages in several folders, run go test ./... from its top folder to test them all, the same way go vet ./... checks them all in Chapter 25.

Homework

Each homework problem is a module of its own in exercises/34/homework/. cd into its folder and run go test there, as in this chapter. The starters all run. Some pass because they check nothing yet, and some fail until you fix them.

Problem 1 — Clamp test

Folder: exercises/34/homework/01-clamp-test/. clamp.go is finished: Clamp(x, lo, hi) keeps x inside the range from lo to hi. In clamp_test.go, write TestClamp with three checks using t.Errorf: a value inside the range, one below it, and one above it. Each message shows the call, what it gave, and what was wanted. Then break Clamp on purpose, and see your test catch it.

Problem 2 — Leap years

Folder: exercises/34/homework/02-leap-table/. leap.go is finished. Turn the single check in leap_test.go into a table-driven test with t.Run. Each row has a name, a year, and the answer. Cover at least 2024 (leap), 2023 (not), 1900 (not, divides by 100) and 2000 (leap, divides by 400). Then use -run to run only the row for 1900.

Problem 3 — Average

Folder: exercises/34/homework/03-average/. Run go test: one row of the table fails. Read the message, find the bug in average.go, and fix it. Then write TestOfEmpty, which calls Of with an empty slice and uses errors.Is to check that the error is ErrEmpty.

Challenge — Visit counter

Folder: exercises/34/homework/04-visit-counter/. counter.go is finished: Next reads a number from a file, adds 1, writes it back, and returns it. A missing file counts as 0. Write the tests in counter_test.go, with every file inside t.TempDir(): the first call returns 1 and the next ones count up, two files count separately, and a file that holds abc gives an error. Then run go test -cover, and work out which lines no test reached.

Stuck or done? Open the homework solutions page.