模拟不适用于模块功能

Afn*_*zir 7 python python-2.7 python-mock python-unittest

我编写了send_formatted_email格式化电子邮件主题和消息的send_email函数,然后在单独的模块中调用该函数。

现在我要测试send_formatted_email的调用send_email与预期的参数。为此,我试图模拟send_emailusing patch,但它并没有被模拟。

测试文件

@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
    ....
Run Code Online (Sandbox Code Playgroud)

视图.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)
Run Code Online (Sandbox Code Playgroud)

实用程序

def send_email(subject, message, to, from):
    return requests.post(
        ...
    )
Run Code Online (Sandbox Code Playgroud)

我什至尝试过,app.util.send_email = MagicMock(return_value=True)但这也不起作用。知道我做错了什么吗?

Eru*_*nos 4

就像jonrsharpe已经提到的那样,另一个问题下已经有了答案。

就我而言,我无法使用提供的替代方案之一(重新加载或修补我自己的模块)。

但我现在只是在使用之前导入所需的方法:

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)
Run Code Online (Sandbox Code Playgroud)

这将在您修补模块方法后加载它。

缺点:

  • 导入在每个方法调用之前执行。