misbehavior in run --source (?)

Issue #328 resolved
Anonymous created an issue

The below script reproduces the problem. In summary, I expect that when the argument to -m and --source are equal, I should never see the code run, and get a warning "module x was never imported", but this is not the current behavior.

#!/usr/bin/env python
# pylint:disable=missing-docstring
'''
$ python repro.py
in example:
true
exiting example...

Coverage.py warning: Module example was never imported.
Coverage.py warning: No data was collected.
Name    Stmts   Miss  Cover
---------------------------

$ pip freeze | grep coverage
coverage==3.7.1
$ python -V
Python 2.7.8
'''


def main():
    from shutil import rmtree
    rmtree('repro', ignore_errors=True)

    from os import mkdir
    mkdir('repro')
    mkdir('repro/code')
    with open('repro/code/example.py', 'w') as examplepy:
        examplepy.write(r'''\
print('in example:')
if True:
    print('true')
else:
    print('false')
print('exiting example...\n')''')

    mkdir('repro/workdir')

    from os import environ
    from os.path import realpath
    env = environ.copy()
    env['PYTHONPATH'] = realpath('repro/code')

    from subprocess import Popen
    Popen(
        ('coverage', 'run', '--source=example', '-m', 'example'),
        cwd='repro/workdir',
        env=env,
    ).wait()

    Popen(
        ('coverage', 'report'),
        cwd='repro/workdir',
    ).wait()


if __name__ == '__main__':
    exit(main())

Comments (5)

  1. Buck Evan

    This happens because the module's name is __main__ when imported via -m.

    The unexpected thing is that the module-name as --source sees it is not always equal to the module-name as -m sees it.

    I should have thought of this much earlier, but didn't. I think this is surprising enough that I'd like to make it work as expected. Is there any way to calculate the "real" name of a __main__ module?

  2. Buck Evan

    I note that providing --source=__main__ does not provide a workaround to this problem, as the current code sees coveragepy as the __main__ module and then stops looking.

  3. Log in to comment