简体   繁体   English

奇怪行为模拟的side_effect函数

[英]Strange behaviour mock’s side_effect function

I have this piece of code: 我有这段代码:

import postie

def send_mail(self, outbox):
    try:
        postie.postmail(self.dbname, outbox)
    except postie.EmailDeliveryException:
        self.logger.error('Fail to send mail’)
        return False
    return True

And I want to test the case a postie.EmailDeliveryException is raised. 我想测试是否有引发postie.EmailDeliveryException的情况。 So I mock out postie.postmail and put the exception as aside effect of its call: 因此,我模拟出postie.postmail并将异常作为其调用的副作用:

import postie

@patch('postie.postmail')
def test_send_mail_False(self, postie_stub):
    ''' Mail send failed '''
    postie_stub.return_value = None
    postie_stub.side_effect = postie.EmailDeliveryException
    op = OutboxProcessor('db name', None, None)
    self.assertFalse(op.send_mail(Outbox()))

The above results in: 上面的结果是:

test_send_mail_False (test_outbox_processor.OutboxProcessorTestCase)
Mail send failed ... No handlers could be found for logger "outbox"
ok

Now I want to mock out the logger and check that the error function is also called in case of 'EmailDeliveryException'. 现在,我要模拟记录器,并检查是否在“ EmailDeliveryException”的情况下也调用了错误函数。 So I go: 所以我去:

@patch('postie.postmail')
@patch.object(Logger, 'error')
def test_send_mail_False(self, postie_stub, logger_stub):
    ''' Mail sending failed '''
    postie_stub.return_value = None
    postie_stub.side_effect = postie.EmailDeliveryException
    logger_stub.return_value = None

    op = OutboxProcessor('db name', None, None)
    self.assertFalse(op.send_mail(Outbox(), None))
    logger_stub.assert_called()

The result will be: 结果将是:

FAIL: test_send_mail_False (test_outbox_processor.OutboxProcessorTestCase)
Mail sending failed
AssertionError: True is not false

So it looks like the assertFalse does no longer succeed, (probably the exception is no longer raised). 因此,似乎assertFalse不再成功(可能不再引发异常)。 Anyone has any idea if anything interferes with my side_effect here? 任何人都知道有什么干扰我的side_effect吗? Thank you in advance! 先感谢您!

You have incorrect order of patch decorators (or stub arguments). 修补程序装饰器(或存根参数)的顺序不正确。 Here's an explanation from mock docs : 这是来自模拟文档的解释:

When you nest patch decorators the mocks are passed in to the decorated function in the same order they applied (the normal python order that decorators are applied). 当您嵌套补丁装饰器时,模拟将以其应用的顺序(装饰器的正常python顺序)传递给装饰的函数。 This means from the bottom up... 这意味着从下往上...

So it should be: 因此应该是:

@patch.object(Logger, 'error')
@patch('postie.postmail')
def test_send_mail_False(self, postie_stub, logger_stub):
    ''' Mail sending failed '''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM