Search code examples
pythonexceptionpython-unittestpython-3.5python-mock

How to throw exception from mocked instance's method?


This demo function I want to test is pretty straight forward:

def is_email_deliverable(email):
    try:
        return external.verify(email)
    except Exception:
        logger.error("External failed failed")
        return False

This function uses an external service, which I want to mock out.

But I can't figure out how to throw an exception from external.verify(email) i.e. how to force the except clause to be executed.

My attempt:

@patch.object(other_module, 'external')
def test_is_email_deliverable(patched_external):    
    def my_side_effect(email):
        raise Exception("Test")

    patched_external.verify.side_effects = my_side_effect
    # Or,
    # patched_external.verify.side_effects = Exception("Test")
    # Or,
    # patched_external.verify.side_effects = Mock(side_effect=Exception("Test"))

    assert is_email_deliverable("[email protected]") == False

This question claims to have the answer, but it didn't work for me.


Solution

  • You have used side_effects instead of side_effect. Its something like this

    @patch.object(Class, "attribute")
    def foo(attribute):
        attribute.side_effect = Exception()
        # Other things can go here
    

    BTW, its not good approach to catch all the Exception and handle according to it.