Setting up rest coverage

In the case of pytest, we have to install the pytest-cov package (at the time of this writing, version 2.5.1 is used in this book). Once installed, when the tests are run, we have to tell the pytest runner that pytest-cov will also run, and which package (or packages) should be covered (among other parameters and configurations).

This package supports multiple configurations, like different sorts of output formats, and it's easy to integrate it with any CI tool, but among all these features a highly recommended option is to set the flag that will tell us which lines haven't been covered by tests yet, because this is what's going to help us diagnose our code and allow us to start writing more tests.

To show you an example of what this would look like, use the following command:

pytest 
--cov-report term-missing
--cov=coverage_1
test_coverage_1.py

This will produce an output similar to the following:

test_coverage_1.py ................ [100%]

----------- coverage: platform linux, python 3.6.5-final-0 -----------
Name Stmts Miss Cover Missing
---------------------------------------------
coverage_1.py 38 1 97% 53

Here, it's telling us that there is a line that doesn't have unit tests so that we can take a look and see how to write a unit test for it. This is a common scenario where we realize that to cover those missing lines, we need to refactor the code by creating smaller methods. As a result, our code will look much better, as in the example we saw at the beginning of this chapter.

The problem lies in the inverse situation—can we trust the high coverage? Does it mean our code is correct? Unfortunately, having good test coverage is necessary but in sufficient condition for clean code. Not having tests for parts of the code is clearly something bad. Having tests is actually very good (and we can say this for the tests that do exist), and actually asserts real conditions that they are a guarantee of quality for that part of the code. However, we cannot say that is all that is required; despite having a high level of coverage, even more tests are required.

These are the caveats of test coverage, which we will mention in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.37.120