Conditional coverage based on any rules you define!
Some projects 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
some extra configuration:
[coverage:run] # Here we specify plugins for coverage to be used: plugins = coverage_conditional_plugin [coverage:coverage_conditional_plugin] # Here we specify our pragma rules: rules = "sys_version_info >= (3, 8)": py-gte-38 "is_installed('mypy')": has-mypy
Or to your
[tool.coverage.run] # Here we specify plugins for coverage to be used: plugins = ["coverage_conditional_plugin"] [tool.coverage.coverage_conditional_plugin.rules] # Here we specify our pragma rules: py-gte-38 = "sys_version_info >= (3, 8)" has-mypy = "is_installed('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:
[coverage:coverage_conditional_plugin] rules = "is_installed('django')": has-django "not is_installed('django')": has-no-django
When running tests with and without
you will have
100% coverage in both cases.
But, different lines will be included.
django installed it will include
if django is not None: conditions.
When running without
it will include
except ImportError: line.
Writing pragma rules
Format for pragma rules is:
"pragma-condition" is evaluted with
Make sure that the input you pass there is trusted!
"pragma-condition" must return
bool value after evaluation.
sys_version_infois the same as
os_environis the same as
is_installedis our custom function that tries to import the passed string, returns
package_versionis our custom function that tries to get package version from
pkg_resourcesand returns its parsed version
get_env_info to get values for the current environment:
from coverage_conditional_plugin import get_env_info get_env_info()