I ran a sample code from this thread. How to properly use coverage.py in Python?
However, when I executed this command py.test test.py --cov=sample.py
it gave me a warning, therefore, no report was created.
platform linux2 -- Python 2.7.12, pytest-3.2.3, py-1.4.34, pluggy-0.4.0 rootdir: /media/sf_Virtual_Drive/ASU/CSE565_testand validation/Assignments/temp, inifile: plugins: cov-2.5.1 collected 3 items test.py ...Coverage.py warning: Module sample.py was never imported. (module-not-imported) Coverage.py warning: No data was collected. (no-data-collected)
Anyone has an idea why coverage.py
does not work?
hence, if I run coverage run -m py.test test.py
separately, it does not show any warning.
Short answer: you need to run with the module name, not the file name: pytest --cov sample test.py
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With