Common Test: Code coverage on subdirectories

Code Coverage with Common Test in your Erlang Projects

Sometimes its useful to organice your source files into subdirectories. Thing is, it's not that easy to create html reports for code coverage for them. Let's see why, and a possible solution for this.

General overview of running Common Test and Generating Code Coverage with Rebar

Typically, you would use rebar in your erlang project, to make it easier to get dependencies, compile, and run tests, either with common_test or eunit.

Surely you will have your rebar.config file with at least the following entries:

And of course, a cover.spec file in the directory of the application, similar to this:

Then you can run common_test via rebar quite easily, like:

All of this will allow you to run the tests and generate coverage reports, but you will notice that there aren't any html reports for the source files that "live" into subdirectories in your src directory.

The reason why you won't get code coverage reports inside src subdirectories in your Erlang projects

The application that generates code coverage is actually shipped with erlang/otp, and it's called cover. Common test uses it but, when referring to the manual page, there's the following note:

Note: Currently, for Common Test to be able to print code coverage HTML files for the modules included in the analysis, the source code files of these modules must be located in the same directory as the corresponding .beam files. This is a limitation that will be removed later.

Quick fix to get code coverage with your Common Test tests

So a kind of dirty solution is to add to your Makefile something along these lines:

This will copy all source files (*.erl) into the ebin directory (where the .beam files are generated), run the tests, and then remove the source files, allowing common test to generate coverage reports for *all* the source files in src and its subdirectories.

Still here? Go have some fun reaching that 100% now :)