TypeError:exception必须是旧式类或派生自BaseException,而不是MagicMock

时间:2014-09-02 14:00:09

标签: python exception mocking

我想在我的代码中测试异常处理:

def test_get_mails__exception_in_search(self):
    with mock.patch('imaplib.IMAP4', autospec=True) as imap_mock:
        imap_mock.return_value.create.return_value = ('OK', [''])
        imap_mock.return_value.search.side_effect=imap_mock.error
        self.get_mails()

但是模拟库提出了:

TypeError: exceptions must be old-style classes or derived from BaseException, 
not MagicMock

如何测试我的代码:我希望imaplib.search举起imaplib.error

1 个答案:

答案 0 :(得分:-1)

我找到了解决方案:

    with mock.patch('imaplib.IMAP4', autospec=True) as imap_mock:
        imap_mock.error=Exception # <----    This is needed, don't ask me why
        imap_mock.return_value.create.return_value = ('OK', [''])
        imap_mock.return_value.search.side_effect=imap_mock.error
        self.get_mails()