python – 模拟不工作模块功能

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

现在我必须测试send_formatted_email是否使用预期的参数调用send_email.为此我试图使用补丁模拟send_email,但它没有被嘲笑.

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(
        ...
    )

我甚至尝试过app.util.send_email = MagicMock(return_value = True),但这也无效.知道我做错了什么吗?

最佳答案 像
jonrsharpe已经提到的那样,在
another question下已经有了答案.

在我的情况下,我无法使用提供的替代方案之一(重新加载或修补我自己的模块).

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

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)

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

缺点:

>导入在每次方法调用之前执行.

点赞