Pytest-cov does not consider a file for coverage analysis unless it is imported in one of the unit tests?
Asked Answered
S

2

4

I have 2 files in my project (a.py and b.py). a.py file is imported in the unit test file (test_prog.py) and there are tests written for it. Pytest-cov shows the coverage for this file.

However for the other file b.py - it is not seen in the code coverage output. Pytest-cov does not consider a file for coverage analysis unless it is imported in one of the unit tests?

Singlehearted answered 26/5, 2020 at 8:50 Comment(6)
Are you using the --cov argument?Chrissy
Yes --cov=folder_name where folder_name is a folder that contains the files on which I want to get code coverage analysis.Singlehearted
Hm, works without problems for me (pytest-5.4.2). Maybe these are files in subdirectories without an __init__.py?Chrissy
Please provide a minimal reproducible example. The issue usually lies in early importing modules (before the coverage plugin was loaded).Marla
@MrBeanBremen - Yes it happens when there is no __init__.py file. What is the reason for this?Singlehearted
Does this answer your question? Coverage.py does not discover tests without init.py file in sub directoriesChrissy
G
6

I have encountered the same issue.

After a quick search, I've found that you have to lay out __init__ structure in your source folder to be able to collect in the coverage report those files that are not being tested.

See this for more about __init__ files.

Graben answered 14/2, 2022 at 19:51 Comment(3)
Good point, this is also commented on github.com/pytest-dev/pytest-cov/issues/88Overblouse
Still seeing source files not included as zero coverage if not exercised by test cases, even with a __init__. However since we are "blind" to the project, we have to use --cov=. with PYTEST_ADDOPT - which may have be insufficient?Rriocard
Same issue, I had __init__.py in my folders, but it still wasn't being picked up in coverage. even with the include_namespace_packages option being set. Turns out I was using --cov which seems like it only picks up imported files actually imported in tests, and fixed it by using --cov=.Mohun
M
3

For people also ending here, there is the solution: set include_namespace_packages to true (pytest>=7.0.0)

add a config file .coverage_rc for your pytest-cov command
ex: pytest --cov=<folder> --cov-config=.coverage_rc

Content of .coverage_rc

[report]
include_namespace_packages = true

# might also be convenient to add one of these:
omit = **/__init__.py
skip_empty = true

Adapt the heading to [tool.coverage.report] if within a pyproject.toml file

Mydriasis answered 27/10, 2023 at 10:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.