Skip to content

Code executed by exec excluded from coverage #380

@nedbat

Description

@nedbat

Originally reported by mb2297 (Bitbucket: mb2297, GitHub: Unknown)


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:

#!python
# impl.py

def foo():
    print "foo"
 
def bar():
    print "bar"
#!python
# impl2.py

print "the answer to life, the universe and everything is: {}".format(undeclared_var)
#!python
# 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.


Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions