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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With