How can I exclude certain files or directories from pytest coverage reports?

How can I exclude certain files or directories from pytest coverage reports?

Hi Tim,

Use the --cov-config option with a .coveragerc file where you can specify exclude patterns under the [run] section to ignore certain paths or files.

For more info generating pytest code coverage reports, please check this article:

When running pytest with pytest-cov plugin, you can use command line options to exclude specific files or directories from coverage.

Use --cov-exclude option followed by a comma-separated list of paths or glob patterns to exclude from coverage.

pytest --cov=my_module --cov-exclude=test_*,*/config.py

This command excludes files starting with “test_” and any config.py file under subdirectories from coverage analysis.

For this, you can use .coveragerc file as well:

Create a .coveragerc file in your project directory or configure an existing one. Specify exclude patterns under the [run] section to ignore certain paths or files from coverage analysis.

Example .coveragerc file content:

[run]
omit =
    */test_*
    */config.py

This configuration excludes files starting with “test_” and any config.py file under subdirectories from coverage reporting.