Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access coverage.py results programmatically?

Using coverage.py I can produce a report that looks like:

Name                      Stmts   Miss  Cover   Missing
-------------------------------------------------------
my_program.py                20      4    80%   33-35, 39
my_other_module.py           56      6    89%   17-23
-------------------------------------------------------
TOTAL                        76     10    87%

How do I programmatically access the value of 87 from the coverage results data to use as an input to another program?

like image 978
Jace Browning Avatar asked Feb 07 '23 19:02

Jace Browning


1 Answers

I will assume that you have already run

$ coverage run my_program.py arg1 arg2

and want to use the data it measured. Coverage.report() returns the total as a floating-point number (you can take it, or round it to a whole percentage if you like). But the function prints a report on the screen. To avoid that, we will open a file object to the null device to suck it up.

import coverage
import os
cov = coverage.Coverage()
cov.load()

with open(os.devnull, "w") as f:
    total = cov.report(file=f)

print("Total: {0:.0f}".format(total))
like image 62
Carsten Avatar answered Feb 16 '23 04:02

Carsten