Cover by Donald Bruce Stewart, Bryan O'Sullivan, John Goerzen

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Measuring Test Coverage with HPC

HPC (Haskell Program Coverage) is an extension to the compiler to observe what parts of the code were actually executed during a given program run. This is useful in the context of testing, as it lets us observe exactly which functions, branches, and expressions were evaluated. The result is precise knowledge about the percent of code tested that’s easy to obtain. HPC comes with a simple utility to generate useful graphs of program coverage, making it easy to zoom in on weak spots in the test suite.

To obtain test coverage data, all we need to do is add the -fhpc flag to the command line when compiling the tests:

$ ghc -fhpc Run.hs --make

Then run the tests as normal:

$ ./Run
                 simple : .....                            (1000)
                complex : ..                               (400)

During the test run, the trace of the program is written to .tix and .mix files in the current directory. Afterwards, these files are used by the command-line tool, hpc, to display various statistics about what happened. The basic interface is textual. To begin, we can get a summary of the code tested during the run using the report flag to hpc. We’ll exclude the test programs themselves (using the --exclude flag), so as to concentrate only on code in the pretty-printer library. Entering the following into the console:

$ hpc report Run --exclude=Main --exclude=QC 18% expressions used (30/158) 0% boolean coverage (0/3) 0% guards (0/3), 3 unevaluated 100% 'if' conditions (0/0) 100% qualifiers (0/0) 23% alternatives used (8/34) 0% local declarations ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required