Making a Python test think an installed package is not available

I ended up with the following pytest-only solution, which appears to be more robust in the setting of a larger project.

import builtins
import pytest


@pytest.fixture
def hide_available_pkg(monkeypatch):
    import_orig = builtins.__import__

    def mocked_import(name, *args, **kwargs):
        if name == 'pkg':
            raise ImportError()
        return import_orig(name, *args, **kwargs)

    monkeypatch.setattr(builtins, '__import__', mocked_import)


@pytest.mark.usefixtures('hide_available_pkg')
def test_message():
    with pytest.raises(ImportError, match='Install "pkg" to use test_function'):
        foo('test_function')

You can mock builtins.__import__.

from unittest import mock

import pytest


def foo(caller):
    try:
        import pkg
    except ImportError:
        raise ImportError(f'Install "pkg" to use {caller}')
    pkg.bar()

with mock.patch("builtins.__import__", side_effect=ImportError):
    with pytest.raises(ImportError, match='Install "pkg" to use test_function'):
        foo('test_function')

Tags:

Python

Pytest