Reduce pragma no cover comments with tool.coverage.report exclude_also

If you’re using Coverage.py or pytest-cov in your Python project, you probably end up with # pragma: no cover comments all over the place to prevent odd lines from being marked as missing coverage, like this:

class Foobar:

  def do_something():  # pragma: no cover
    raise NotImplementedError()

You can reduce the need for these # pragma: no cover comments by configuring Coverage.py to ignore certain patterns by default. This can be configured in the pyproject.toml file like this:

[tool.coverage.report]
exclude_also = [
    "def __repr__",
    "if self.debug:",
    "if settings.DEBUG",
    "raise AssertionError",
    "raise NotImplementedError",
    "if 0:",
    "if False:",
    "if __name__ == .__main__.:",
    "if TYPE_CHECKING:",
    "class .*\\bProtocol\\):",
    "@(abc\\.)?abstractmethod",
    "\\.\\.\\.",
]

Those are some common patterns that you will likely want to skip coverage for. With this configuration, you no longer need to add a # pragma: no cover comment on those lines, as they’ll be ignored by default.


View post: Reduce pragma no cover comments with tool.coverage.report exclude_also