奇怪行为模拟的副作用函数

2024-09-29 19:30:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段代码:

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

我想测试一个案例posite.EmailDeliveryException异常升起。 所以我开玩笑邮递把例外情况放在一边,作为其调用的影响:

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

上述结果如下:

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

现在我想模拟这个记录器,并检查在“EmailDeliveryException”的情况下是否也调用了error函数。所以我说:

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

结果将是:

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

因此看起来assertFalse不再成功(可能不再引发异常)。有人知道有什么干扰了我的副作用吗?提前谢谢!你知道吗


Tags: testselfnonesendfalsereturnmaillogger
1条回答
网友
1楼 · 发布于 2024-09-29 19:30:25

修补程序装饰程序(或存根参数)的顺序不正确。以下是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). This means from the bottom up...

所以应该是:

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

相关问题 更多 >

    热门问题