Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python testing: Simulate ImportError [duplicate]

I have the following code

try:
    from foo_fast import bar
except ImportError
    from foo import bar


def some_function(a, b):
    return bar(a, b)

I now want to test the two cases where foo_fast could be imported and where it couldn't.

Using pytest and pytest-mock, I naturally want to encapsulate the two situations in a pytest fixture, so I thought I would use

@pytest.fixture(params=(True, False))
def use_fast(request, mock):

    if not request.param:
        mock.patch("foo_fast.bar", side_effect=ImportError)

    return request.param


def test_foo(use_fast):
    assert some_function(1, 2)

However it seems the import statement is only run once before the test starts so I cannot mock the ImportError.

How does one mock these ImportError cases?

like image 897
Nils Werner Avatar asked Dec 24 '22 23:12

Nils Werner


1 Answers

It is possible with the mock library:

def test_import_error(self):
    with mock.patch.dict('sys.modules', {'foo_fast.bar': None}):
        # your tests with foo.bar

In this case from foo_fast import bar will raises ImportError.

like image 159
ikoverdyaev Avatar answered Dec 31 '22 14:12

ikoverdyaev