coverage-conditional-plugin Build Status Python Version wemake-python-styleguide

Conditional coverage based on any rules you define!

Some project have different parts that relies on different environments:

  • Python version, some code is only executed on specific versions and ignored on others
  • OS version, some code might be Windows, Mac, or Linux only
  • External packages, some code is only executed when some 3rd party package is installed

Current best practice is to use # pragma: no cover for this places in our project. This project allows to use configurable pragmas that include code to the coverage if some condition evaluates to true, and fallback to ignoring this code when condition is false.

Read the announcing post.


pip install coverage-conditional-plugin

Then you will need to add to your setup.cfg or .coveragerc file some extra configuration:

# Here we specify plugins for coverage to be used:
plugins =

# Here we specify our pragma rules:
rules =
  "sys_version_info >= (3, 8)": py-gte-38
  "is_installed('mypy')": has-mypy

Adapt rules to suit your needs!


Imagine that we have this code:

try:  # pragma: has-django
    import django
except ImportError:  # pragma: has-no-django
    django = None

def run_if_django_is_installed():
    if django is not None:  # pragma: has-django

And here's the configuration you might use:

rules =
  "is_installed('django')": has-django
  "not is_installed('django')": has-no-django

When running tests with and without django installed you will have 100% coverage in both cases.

But, different lines will be included. With django installed it will include both try: and if django is not None: conditions.

When running without django installed, it will include except ImportError: line.

Writting pragma rules

Format for pragma rules is:

"pragma-condition": pragma-name

Code inside "pragma-condition" is evaluted with eval. Make sure that the input you pass there is trusted! "pragma-condition" must return bool value after evaluation.

We also provide a bunch of helpers to make writing rules easier:

  • sys_version_info is the same as sys.version_info
  • os_name is the same as
  • os_environ is the same as os.environ
  • platform_system is the same as platform.system()
  • platform_release is the same as platform.release()
  • is_installed is our custom function that tries to import the passed string, returns bool value
  • package_version is our custom function that tries to get package version from pkg_resources and returns its parsed version




This project was generated with wemake-python-package. Current template version is: a61725009d8399ae77376b5ad9de354214bc1159. See what is updated since then.

当前网页内容, 由 大妈 ZoomQuiet 使用工具: ScrapBook :: Firefox Extension 人工从互联网中收集并分享;
若有不妥, 欢迎评注提醒:


订阅 substack 体验古早写作:

点击注册~> 获得 100$ 体验券: DigitalOcean Referral Badge

关注公众号, 持续获得相关各种嗯哼:


关于 ~ DebugUself with DAMA ;-)
公安备案号: 44049002000656 ...::