Skip to content

Table of Contents

Month 2 · Week 3 — Exercises

Practice for the testing package: table-driven tests, subtests, helpers, httptest, benchmarks, and fuzzing. Each folder is its own package with a solution and *_test.go files. Standard library only.

Exercise Concept Day Run tests
reverse/ table-driven test + FuzzReverse + BenchmarkReverse 043, 047, 048 go test ./reverse
wordfreq/ named subtests (t.Run) + a t.Helper() assertion 043–044 go test ./wordfreq
greeter/ httptest.NewRecorder handler tests (status/header/body) 045 go test ./greeter

How to use

  1. Try it yourself first — move the solution .go aside and re-implement from the prompt.
  2. Run go test ./... from this directory.
  3. Compare with the provided solution; log differences in your day note's "Mistakes" section.

Prompts

  • reverse: implement Reverse(s string) string that reverses by rune (not byte) so multibyte UTF-8 stays valid. Cover it with a table-driven test, a FuzzReverse asserting the round-trip (Reverse(Reverse(s)) == s) and UTF-8-validity invariants, and a BenchmarkReverse with b.ReportAllocs().
  • wordfreq: implement Count(text string) map[string]int (case-insensitive, letters/digits are words) and Top(text string, n int) []string (most frequent, ties alphabetical, clamp n). Test with named t.Run subtests and factor map comparison into a t.Helper() assertion.
  • greeter: implement Handler() http.Handler answering GET /greet?name=NAME -> "Hello, NAME!", 400 on missing/blank name, 405 + Allow header on non-GET. Test it with httptest.NewRecorder (no real server).

Try the other tooling

go test -v ./reverse                                  # see subtests
go test -bench=. -benchmem ./reverse                  # benchmark
go test -fuzz=FuzzReverse -fuzztime=10s ./reverse     # actually fuzz
go test -cover ./...                                  # coverage for the week

Results

Exercise Tests Status
reverse TestReverse, FuzzReverse, BenchmarkReverse
wordfreq TestCount, TestTop
greeter TestHandler, TestHandlerAllowHeader

Tip: run all of Week 3 at once with go test ./....


Exercises