Pytest.importorskip test skipping
allows clean handling of numerous continuous integration challenges.
Many programs use advanced plotting that may not be desired to test on continuous integration.
For example, one might opt not to install
matplotlib as part of CI runs.
We put plotting routines in a separate file to facilitate this, allowing the core module functions to have a bare minimum set of prereqs.
This is useful for HPC, CI and cloud scenarios that either may not plot locally or that may use varied plotting systems depending on whether running on web or local PC.
is a vital tool to handle to cleanly and clearly handle these scenarios.
Imagine a Python package file hierarchy like:
mymod/ __init__.py plot.py adv.py tests/ test_mod.py test_plots.py
Skipping function imports is demonstrated in this example.
Suppose optional module
scikit-image, which itself has a lot of prereqs.
One might opt to have CI not install
scikit-image, and then use
pytest.importorskip() to cleanly skip complicated, optional tests on CI, HPC etc.
import pytest import mymod def test_advanced(): adv = pytest.importorskip('mymod.adv') ...
Skipping module imports is demonstrated in this example. Suppose “test_plots.py” has every function requiring Matplotlib. The whole file may be skipped instead of skipping each function like:
import pytest try: import matplotlib except ImportError: pytest.skip("Matplotlib not available", allow_module_level=True) def ...
Conditional skipping can handle more complicated cases by making a decorator with
import pytest import os @pytest.mark.skipif(os.name=='nt', reason='only for Unix-like systems') def test_unix(): ...
If you have more than one function to skip with the same test skip condition, make your own decorator:
import pytest import os unixonly = pytest.mark.skipif(os.name=='nt', reason='only for Unix-like systems') @unixonly def test_unix_plot(): ... @unixonly def test_unix_network(): ...