34. Testing with go test — Homework solutions

The solutions are in exercises/34/homework/solutions/, one module per problem. Go into a solution's folder to run its tests, for example:

cd exercises/34/homework/solutions/01-clamp-test
go test -v

That folder is five levels down, so cd ../../../../.. takes you back to go-work.

Problem 1 — Clamp test

Problem. Test Clamp with three checks: inside the range, below it, and above it.

How to think about it. Each check is the same three steps as TestCount in the chapter: call, compare, report. Pick values whose answers you know without running the code: 5 in 0 to 10 stays 5, -3 becomes 0, and 99 becomes 10. Reuse one got variable with = after the first :=. The message names the call, the result, and the answer wanted.

Worked solution.

func TestClamp(t *testing.T) {
    got := Clamp(5, 0, 10)
    if got != 5 {
        t.Errorf("Clamp(5, 0, 10) = %d, want 5", got)
    }

    got = Clamp(-3, 0, 10)
    if got != 0 {
        t.Errorf("Clamp(-3, 0, 10) = %d, want 0", got)
    }

    got = Clamp(99, 0, 10)
    if got != 10 {
        t.Errorf("Clamp(99, 0, 10) = %d, want 10", got)
    }
}

Output with -v:

=== RUN   TestClamp
--- PASS: TestClamp (0.00s)
PASS
ok      clamp   0.193s

To check the test itself, break Clamp: change return hi to return x. The third check then fails with Clamp(99, 0, 10) = 99, want 10, and the other two still pass.

Common mistakes.

  • Writing got := ... a second time. Go stops with no new variables on left side of :=. The second and third calls use =.
  • A message like wrong answer. It fails at the right moment, but you then have to open the test to find out which call failed and what it gave.
  • Only testing the value inside the range. That passes even if Clamp just returns x, so the test proves nothing about clamping.

Problem 2 — Leap years

Problem. Turn one check into a table-driven test, and run one row with -run.

How to think about it. The struct for a row needs a field for each thing that changes from case to case: a name, the year, and the answer. That makes want a bool. The loop and t.Run are the ones from TestLetter, with %t in the message, the format verb for a bool. The four rows cover the four ways through IsLeap: one per return, plus a year that does not divide by 4 at all.

Worked solution.

func TestIsLeap(t *testing.T) {
    tests := []struct {
        name string
        year int
        want bool
    }{
        {"divides by 4", 2024, true},
        {"does not divide by 4", 2023, false},
        {"divides by 100", 1900, false},
        {"divides by 400", 2000, true},
    }

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

To run only the 1900 row, give the subtest's name with underscores:

go test -v -run TestIsLeap/divides_by_100

=== RUN   TestIsLeap
=== RUN   TestIsLeap/divides_by_100
--- PASS: TestIsLeap (0.00s)
    --- PASS: TestIsLeap/divides_by_100 (0.00s)
PASS
ok      leap    0.188s

Common mistakes.

  • -run TestIsLeap/divides by 100, with spaces. The terminal splits it into separate arguments, and go test complains about them. Use the underscores, as the -v output shows.
  • -run divides_by_100 without the test name. The first part is matched against the test's name, TestIsLeap, which does not contain it, so nothing runs and you only get testing: warning: no tests to run.
  • Leaving out 1900 or 2000. Those are the rows that test the two special rules, and they are the ones a wrong IsLeap usually gets wrong.

Problem 3 — Average

Problem. Find and fix a bug from a failing test, then test the empty case.

How to think about it. The test run says:

--- FAIL: TestOf (0.00s)
    --- FAIL: TestOf/half_result (0.00s)
        average_test.go:30: Of([1 2]) = 1, want 1.5
FAIL
exit status 1
FAIL    average 0.205s

Only the row with a half fails, and it lost exactly the half. That points at division. sum / len(numbers) divides two ints, which drops the part after the point, as Chapter 13 showed with 7 / 2. Here 3 / 2 is 1. Turning the result into a float64 afterwards is too late. Turn both numbers into float64 before dividing.

The empty case is a test for a particular error, so it uses errors.Is and the sentinel ErrEmpty, as TestParseOutOfRange did in the chapter.

Worked solution. In average.go, the last line becomes:

    return float64(sum) / float64(len(numbers)), nil

And the new test, with "errors" added to the imports of average_test.go:

func TestOfEmpty(t *testing.T) {
    _, err := Of([]int{})
    if !errors.Is(err, ErrEmpty) {
        t.Errorf("Of([]) error = %v, want ErrEmpty", err)
    }
}

go test now prints PASS and the ok line.

Common mistakes.

  • Changing the test's want to 1. The test then passes, and the bug stays. When a test fails, first ask whether the code or the test is wrong. Here the average of 1 and 2 is 1.5, so the code is wrong.
  • Writing float64(sum) / len(numbers). Go does not mix number types, and stops with mismatched types float64 and int.
  • Checking only err == nil in TestOfEmpty. That passes for any error. errors.Is checks that it is the right one.

Challenge — Visit counter

Problem. Test a function that reads and writes a file, using t.TempDir().

How to think about it. Each suggested test becomes one Test function, and each one makes its own file name with filepath.Join(t.TempDir(), ...). Then:

  • Counting up. Call Next three times on the same file. The loop variable can be the answer wanted: the first call should give 1, the second 2, and so on. An error stops the test with t.Fatalf, since the counts after it would mean nothing.
  • Separate files. Two names in one temporary folder. Count the first one up twice; the second should still start at 1.
  • Not a number. The test has to make the bad file itself, with os.WriteFile, before calling Next. If setting up fails, that is not Next's fault, so it stops with its own message.

Worked solution.

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

    for want := 1; want <= 3; want++ {
        got, err := Next(filename)
        if err != nil {
            t.Fatalf("call %d: %v", want, err)
        }
        if got != want {
            t.Errorf("call %d returned %d, want %d", want, got, want)
        }
    }
}

func TestNextSeparateFiles(t *testing.T) {
    dir := t.TempDir()
    first := filepath.Join(dir, "first.txt")
    second := filepath.Join(dir, "second.txt")

    _, err := Next(first)
    if err != nil {
        t.Fatalf("Next(first): %v", err)
    }
    _, err = Next(first)
    if err != nil {
        t.Fatalf("Next(first): %v", err)
    }

    got, err := Next(second)
    if err != nil {
        t.Fatalf("Next(second): %v", err)
    }
    if got != 1 {
        t.Errorf("Next(second) = %d, want 1", got)
    }
}

func TestNextNotANumber(t *testing.T) {
    filename := filepath.Join(t.TempDir(), "visits.txt")
    err := os.WriteFile(filename, []byte("abc\n"), 0644)
    if err != nil {
        t.Fatalf("setting up: %v", err)
    }

    _, err = Next(filename)
    if err == nil {
        t.Fatal("Next on a file holding \"abc\" gave no error")
    }
}

The imports are "os", "path/filepath" and "testing". In TestNextSeparateFiles, t.TempDir() is called once and kept in dir, so both files are in the same folder. That makes the test stronger: the files sit side by side, and still do not mix.

go test -cover ends with:

ok      counter 0.231s  coverage: 84.6% of statements

The two lines no test reaches are the return 0, err after os.ReadFile fails for a reason other than a missing file, and the one after os.WriteFile fails. Making those happen on purpose, for example with a file you are not allowed to read, is fiddly and differs between Windows and Linux. 84.6% with every normal path and the bad-content path tested is a good result.

Common mistakes.

  • Using "visits.txt" with no t.TempDir(). The first run passes and leaves the file behind. The second run starts at 4, and TestNextCountsUp fails.
  • Calling t.TempDir() separately for first and second and expecting them in the same folder. Every call makes a new folder. The test still passes, but it no longer checks two files side by side.
  • Forgetting to import "testing". The starter's file has none, and Go stops with undefined: testing.

Done?

You can now prove that your code works, and keep it working when you change it. The next chapter, Time and dates, is the last tool the To-do list needs: reading the clock, writing dates, and counting days. It also shows how to test code that depends on the time.