5

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("some_mail@domain.com") == False

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

Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57

2 Answers2

14

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.

safwan
  • 383
  • 2
  • 6
0

You can set the side_effect value to None.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135