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¶
- Try it yourself first — move the solution
.goaside and re-implement from the prompt. - Run
go test ./...from this directory. - Compare with the provided solution; log differences in your day note's "Mistakes" section.
Prompts¶
- reverse: implement
Reverse(s string) stringthat reverses by rune (not byte) so multibyte UTF-8 stays valid. Cover it with a table-driven test, aFuzzReverseasserting the round-trip (Reverse(Reverse(s)) == s) and UTF-8-validity invariants, and aBenchmarkReversewithb.ReportAllocs(). - wordfreq: implement
Count(text string) map[string]int(case-insensitive, letters/digits are words) andTop(text string, n int) []string(most frequent, ties alphabetical, clampn). Test with namedt.Runsubtests and factor map comparison into at.Helper()assertion. - greeter: implement
Handler() http.HandleransweringGET /greet?name=NAME->"Hello, NAME!", 400 on missing/blank name, 405 +Allowheader on non-GET. Test it withhttptest.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 ./....