Python – Mock not working on module function

pythonpython-2.7python-mockpython-unittest

I have written the function send_formatted_email which formats email subject and message then calls the send_email function in a separate module.

Now I have to test that send_formatted_email is calling send_email with the expected arguments. For this purpose I am trying to mock send_email using patch, but it is not getting mocked.

test.py

@patch('app.util.send_email')
def test_send_formatted_email(self, mock_send_email):
    mock_send_email.return_value = True
    response = send_formatted_email(self.comment, to_email)
    mock_send_email.call_args_list
    ....

views.py

def send_formatted_email(comment, to_email):
    ...
    message = comment.comment
    subject = 'Comment posted'
    from_email = comment.user.email
    ...
    return send_email(subject, message, to_email, from_email)

util.py

def send_email(subject, message, to, from):
    return requests.post(
        ...
    )

I even tried app.util.send_email = MagicMock(return_value=True) but this didn't work either. Any idea what I am doing wrong?

Best Answer

Like jonrsharpe already mentioned there is already an answer under another question.

In my case I were not able to use one of the alternatives that are provided (reload or patching my own module).

But I now just importing the needed method right before usage:

def send_formatted_email(comment, to_email):
    ...
    message = comment.comment
    subject = 'Comment posted'
    from_email = comment.user.email
    ...
    from app.util import send_email
    return send_email(subject, message, to_email, from_email)

This will load the module method after you patched it.

Cons:

  • The import is executed before each method call.