Code Coverage

Learn why code coverage is important and how to set up rest coverage.

Tests runners support coverage plugins (to be installed via pip) that provide useful information about what lines in the code have been executed as tests run. This information is of great help so that we know which parts of the code need to be covered by tests, as well as identifying improvements to be made (both in the production code and in the tests). What we mean by this is that detecting lines of our production code that are uncovered will force us to write a test for that part of the code (because remember that code that doesn't have tests should be considered broken). In that attempt to cover the code, several things can happen:

  • We might realize we are missing a test scenario completely.

  • We'll try to come up with more unit tests or unit tests that cover more lines of code.

  • We'll try to simplify our production code, removing redundancies, and making it more compact, meaning it's easier to be covered.

  • We might even realize that the lines of code we're trying to cover are unreachable (perhaps there was a mistake in the logic) and can be safely removed.

Keep in mind that even though these are positive points, coverage should never be a target, only a metric. This means trying to achieve a high coverage, just to reach 100%, won't be productive or effective. We should understand code coverage as a unit to identify obvious parts of the code that need testing and see how we can improve that. We can, however, set a minimum threshold of, say, 80% (a generally accepted value) as the minimum level of desired coverage to know that the project has a reasonable number of tests.

Get hands-on with 1400+ tech skills courses.