3 Test coverage and optimization

 

This chapter covers

  • Measuring test coverage to see what percentage of code is tested
  • Optimizing for performance using benchmarks and profiling
  • Parallel testing to reduce test runtime and detect data race issues

Chapter 2 introduced idioms and testing, and we implemented and tested a package called url using the testing package and the go test tool. In this chapter, we’ll measure our package’s test coverage to identify what we still need to test. Then we’ll improve our code’s performance by benchmarking and profiling, (Idiomatic code is efficient and eliminates unnecessary inefficiencies.) Last, we’ll look at running parallel tests and detecting possible data race issues.

3.1 Test coverage

As radar scans for objects within a radius, test coverage examines our code to identify which parts are tested and which are not. Test coverage is a way of cross-checking which sections of code our tests are exercising and verifying—in other words, covering. This section discusses test coverage. We’ll measure the test coverage of our url package and see what it means to reach 100% test coverage. Then we’ll start fixing bugs in our code.

3.1.1 Measuring test coverage

We can measure the test coverage of the url package by using the coverprofile flag:

$ go test ./url -coverprofile cover.out #1
. . .coverage: 87.5% of statements

3.1.2 Perfecting test coverage

3.1.3 100% test coverage != bug-free code

3.2 Benchmarking and optimization

3.2.1 Writing and running benchmarks

3.2.2 Using sub-benchmarks

3.2.3 Profiling: Chasing out memory allocations

3.2.4 Optimizing code

Summary