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.

Example:

# impl.py

def foo():
    print "foo"

def bar():
    print "bar"
# impl2.py

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

from impl import foo

foo()

namespace = {
    'undeclared_var': 42
}

with open('impl2.py') as f:
    code = compile(f.read(), 'impl2.py', 'exec')
    exec(code, globals(), namespace)

Results in the following on both OS X and Ubuntu:

$ coverage run --source . test.py
foo
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 https://gist.github.com/mattbennett/f57a5286bd77ee52651e 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