Code executed by exec excluded from coverage

Issue #380 resolved
mb2297 created an issue

It might be unrealistic to expect this to work, but python files that are read and then executed with exec (or with execfile) aren't counted towards the coverage report.



def foo():
    print "foo"

def bar():
    print "bar"

print "the answer to life, the universe and everything is: {}".format(undeclared_var)

from impl import foo


namespace = {
    'undeclared_var': 42

with open('') as f:
    code = compile(, '', 'exec')
    exec(code, globals(), namespace)

Results in the following on both OS X and Ubuntu:

$ coverage run --source .
the answer to life, the universe and everything is: 42
$ coverage report
Name    Stmts   Miss  Cover
impl        4      1    75%
impl2       1      1     0%
test        6      0   100%
TOTAL      11      2    82%

The example is also at if you want to clone and verify.

Comments (3)

  1. Ned Batchelder repo owner

    Looks like exec'ing code gets the called code and the calling code confused in the frame. I've added a warning when this happens here: b981d945481a. There's probably a way to get this right, still working on it.

  2. Log in to comment