Welcome to pytest-missing-modules’ documentation

Welcome to pytest-missing-modules’ documentation#

pytest_missing_modules.plugin.missing_modules(...)

Pytest fixture that can be used to create missing_modules contexts.

pytest_missing_modules.plugin.MissingModulesContextGenerator(...)

Context manager generator that raises ImportError for specified modules.

missing_modules(monkeypatch)[source]#

Pytest fixture that can be used to create missing_modules contexts.

Parameters:

monkeypatch (MonkeyPatch) – A monkeypatch fixture, provided by pytest.

Return type:

MissingModulesContextGenerator

Returns:

A context manager that can be used to create missing modules contexts.

Examples

This first examples shows the most basic usage of this module.

The following must be placed in a test file.#
import pytest


def test_missing_numpy(missing_modules):
    with missing_modules("numpy"):
        with pytest.raises(ImportError):
            # Will always raise an error, even if NumPy is installed
            import numpy

A more interesting example would be to check that your package can still be imported, even if a dependency is missing.

The following must be placed in a test file.#
import importlib
import importlib.util
import pytest
import my_package  # This succeeds


def test_missing_dependency(missing_modules):
    with missing_modules("plotly", patch_find_spec=False):
        # We check that Plotly is installed
        assert importlib.util.find_spec("plotly") is not None
        # .. but not importable
        with pytest.raises(ImportError):
            import plotly

        # We check our package can still be imported
        importlib.reload(my_package)
class MissingModulesContextGenerator(monkeypatch)[source]#

Context manager generator that raises ImportError for specified modules.

In the provided context, an import of any modules in that list will raise an ImportError.

Parameters:

monkeypatch (MonkeyPatch) – The monkeypatch object used to perform all patches.

__call__(*names, error_msg="Mocked import error for '{name}'", patch_import=True, patch_find_spec=True)[source]#

Enter the context manager.

Parameters:
Yields:

A monkeypatch instance that mocks imports of the specified modules.

Return type:

Iterator[MonkeyPatch]