【问题标题】:Mock not working on module function模拟不适用于模块功能
【发布时间】:2016-08-14 12:25:08
【问题描述】:

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

现在我必须测试send_formatted_email 是否使用预期的参数调用send_email。为此,我尝试使用patch 模拟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),但这也没有用。知道我做错了什么吗?

【问题讨论】:

标签: python python-2.7 python-unittest python-mock


【解决方案1】:

就像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)

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

缺点:

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

【讨论】:

    【解决方案2】:

    试试这个:

    import app.util
    
    ...
    
    return util.send_email(subject, message, to_email, from_email)
    

    或:

    @patch('app.views.send_email')
    
    ...
    
    return send_email(subject, message, to_email, from_email)
    

    【讨论】:

      猜你喜欢
      • 2019-07-30
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      • 2019-07-16
      • 2021-05-11
      • 2018-08-07
      • 2020-06-19
      相关资源
      最近更新 更多