Coverage "No source for code" with pytest

Question:

I am trying to measure code coverage by my pytest tests. I tried following the quick start guide of coverage (https://coverage.readthedocs.io/en/6.4.1/)

When I run my test with the following command, everything seems fine

coverage run -m pytest tests/
===================================== test session starts ======================================
platform linux -- Python 3.10.4, pytest-7.1.2, pluggy-1.0.0
rootdir: /home/arnaud/Documents/Github/gotcha
collected 4 items                                                                              

tests/preprocessing/test_preprocessing.py ....                                           [100%]

====================================== 4 passed in 0.30s =======================================

However, when I try to access the report with either of those commands,

coverage report

coverage html

I get the following message:

No source for code: '<project_directory>/config-3.py'.

I did not find an appropriate solution to this problem so far

Asked By: arnino

||

Answers:

It is possible to ignore errors using the command

coverage html -i

which solved my issue

Answered By: arnino

This issue is usually caused by older coverage result files, so you can either:

Answered By: omer.hazan

Another possible solution is to specify the source attribute. In my case, rather than the whole project (source = .), I specified the actual source folder (e.g. src). This can either be done on the commandline:

coverage run --source=src

or include it in your .coveragerc file:

[run]
source = src
...

I was getting this same issue because of a specific library I was importing*, but I never figured out why that library affected coverage, and others didn’t.

Though this might just be a workaround, it makes sense to just check your source folder, and ignoring all errors (with -i) isn’t much better.

* The library uses opencv-python-headless, which I think has the root cause of this issue.

Answered By: platelminto

This is related to https://github.com/nedbat/coveragepy/issues/1653

I temporary solution is to explicitly omit the opencv-python synthetic files that are created maybe at install time.

Add this to your .coveragerc file (or any other configuration file you’re using):

omit = 
    config.py
    config-3.py
Answered By: browser-bug