Coverage.py 100% but unused python files not detected

We’ve been using coverage.py, and getting 100% coverage, but just realised that some .py files were not being imported anywhere and so were effectively dead files. We’ve just fixed the issue by making sure those files are imported and used, but is there any way that coverage.py could automatically detect this?

Does this make sense @nedbat ?

Many thanks in advance

Coverage.py has a --source=somewhere option. It will then explore the tree at somewhere looking for files that weren’t imported. The usual value for somewhere is “.”: --source=.

https://coverage.readthedocs.io/en/7.3.2/config.html#run-source

3 Likes

Adding to Ned’s comments, here’s a snippet from our .coveragerc, which also includes omit to suppress those files intentionally ignored/unused.

[run]
branch        = True
cover_pylib   = False
concurrency   = thread
data_file     = $PROJECT_COVERDIR/.coverage
debug         =
source        =
    $PROJECT_ROOT/src
    $PROJECT_ROOT/install/Examples
    $PROJECT_ROOT/projects
    $PROJECT_ROOT/tests/scripted
    $PROJECT_ROOT/tools
timid         = False
omit          =
    $PROJECT_ROOT/main/dicom_xlate/*
    */_art.py
1 Like

excellent thanks! Just what we were looking for :slight_smile:

Mhm… I do have similar problems. I try to setup a demo project to illustrate the use of coverage. I have an untested file in there and it is not discovered when using “source=”.

There is also an Issue about that.

The setup in my pyproject.toml

[tool.coverage.run]
command_line = "--module pytest"
source = ["."]
omit = ["*/tests/*"]

This is the project tree where foo.py is ignored by coverage.

06_test_coverage
├── LICENSE
├── pyproject.toml
├── README.md
├── src
│   └── fruits
│       ├── foo.py
│       ├── __init__.py
│       └── __main__.py
└── tests
    ├── __init__.py
    └── test_fruits.py

That is the report output

Name                     Stmts   Miss  Cover
--------------------------------------------
src/fruits/__init__.py       8      0   100%
--------------------------------------------
TOTAL                        8      0   100%