Is it possible to make a code coverage statement in Python?

When I write tests or debugging code, I would like to add a Python line that will tell me if this line is ever executed. Is it possible?

For example, I want to write code, for example:

def f(x): if x==0: check_covered() return 1 elif x==1: check_covered() return 2 else: check_covered() return 3 f(1) f(2) print_all_missing_cases() 

And I would like the result to tell me that one of the branches was never covered.

What i tried

Approach 1

I can do this for functions with a decorator as follows:

 missing_fns = set() def covered(h): missing_fns.add(h.func_name) def h2(*args): missing_fns.remove(h.func_name) return h(*args) return h2 @covered def f(a): return a+1 @covered def g(a): return a+2 f(0) for x in missing_fns: print x,'is never called' 

But I'm struggling to find something that activates while compiling a function that I could connect to.

Approach 2

It is also quite simple if I pass the incremental value to each instance (e.g. check_covered (0), check_covered (1), check_covered (2), ...), but it gets messy when I copy or delete the code.

Approach 3

You can get this information by running the code coverage tool, but if possible, I would prefer to do it with the simple Python code that I have for understanding.

+6
source share
1 answer

I highly recommend using the coverage module.

Here is a good tutorial on how to get the best score here.

The use is simple:

 $ coverage run my_program.py arg1 arg2 

The more results you can see with the coverage report

 $ coverage report -m Name Stmts Miss Cover Missing ------------------------------------------------------- my_program 20 4 80% 33-35, 39 my_other_module 56 6 89% 17-23 ------------------------------------------------------- TOTAL 76 10 87% 
+5
source

All Articles