py.test gives Coverage.py warning: Module sample.py was never imported

Short answer: you need to run with the module name, not the file name: pytest --cov sample test.py

Long answer:

One comment in the answer you linked (How to properly use coverage.py in Python?) explains that this doesn’t seem to work if the file you are trying to get the coverage of is a module imported by the test. I was able to reproduce that:

./sample.py

def add(*args):
    return sum(args)

./test.py

from sample import add

def test_add():
    assert add(1, 2) == 3

And I get the same error:

$ pytest --cov sample.py test.py
========================================================================================== test session starts ===========================================================================================
platform darwin -- Python 3.7.2, pytest-4.3.1, py-1.8.0, pluggy-0.9.0
rootdir: /path/to/directory, inifile:
plugins: cov-2.6.1
collected 1 item

test.py .                                                                                                                                                                                          [100%]Coverage.py warning: Module sample.py was never imported. (module-not-imported)
Coverage.py warning: No data was collected. (no-data-collected)
/path/to/directory/.venv/lib/python3.7/site-packages/pytest_cov/plugin.py:229: PytestWarning: Failed to generate report: No data to report.

  self.cov_controller.finish()
WARNING: Failed to generate report: No data to report.

However, when using the module name instead:

pytest --cov sample test.py
========================================================================================== test session starts ===========================================================================================
platform darwin -- Python 3.7.2, pytest-4.3.1, py-1.8.0, pluggy-0.9.0
rootdir: /path/to/directory, inifile:
plugins: cov-2.6.1
collected 1 item

test.py .                                                                                                                                                                                          [100%]

---------- coverage: platform darwin, python 3.7.2-final-0 -----------
Name        Stmts   Miss  Cover
-------------------------------
sample.py       2      0   100%

The pytest-cov documentation seems to indicate you can use a PATH, but it might not be working in all cases…

Leave a Comment