Benchmarks and coverage
A benchmark measures what you repeated. Coverage shows which code ran, not which code is correct.
A benchmark is a function BenchmarkXxx(b *testing.B). The body spins b.N times. The runtime picks the number:
func BenchmarkRepeat(b *testing.B) {
for i := 0; i < b.N; i++ {
Repeat("go", 8)
}
}
The run: go test -bench=. -benchmem ./.... -benchmem shows allocations. Comparing "before and after" makes sense on the same code around the place being measured. If the benchmark contains an extra allocation you did not mean to optimize, the number lies.
The compiler may throw away a result that nobody uses. If the function is pure, save the result in a package variable through b.Loop in newer Go, or assign it to a var sink that you use. Otherwise the benchmark measures an empty loop.
Coverage: go test -cover ./.... The percentage is the share of statements the test executed. 100% does not mean the boundary values were checked: a branch may have run on the happy path. 40% in a package with logic is a reason to look at which file is bare. Chasing the percentage in main, where there is only wiring, is not needed.
An example in a test is a function ExampleMedian. The output is checked against the comment Output:. The example lands in the documentation. It is good for a library. In a service, ordinary tests are usually enough.
A test must not depend on the order of other tests. t.Parallel() lets subtests run alongside each other, and then shared mutable state has to disappear. A parallel test that writes into one package map is a race, and now also in CI with -race.
Practice
What b.N is
Who chooses how many times the body of a benchmark runs?
- The programmer. The number is always 1000
- go test, through the value b.N
- The operating system
- The package math/rand
What coverage means
A test gave 100% coverage of a function. What follows from that?
- The function is correct on every input
- Every statement ran at least once, and nothing more
- The tests can be deleted. The percentage is already good
- The race detector does not have to be run
A shared map in parallel tests
Two subtests with
t.Parallel()write into the same package map with no mutex. Is there a data race here? Writeyesorno.