Pytest.importorskip test skipping

Pytest 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.

pytest.importorskip() is a vital tool to handle to cleanly and clearly handle these scenarios.

Example

Imagine a Python package file hierarchy like:

mymod/
  __init__.py
  plot.py
  adv.py
  tests/
    test_mod.py
    test_plots.py

Skip function imports

Suppose optional module mymod.adv() requires 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.

“test_mod.py”:

import pytest
import mymod


def test_advanced():

    adv = pytest.importorskip('mymod.adv')

    ...

Skip module imports

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

Handle more complicated cases and make a decorator with pytest.skipif.

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():
    ...