I want to test the exception handling in my code:
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()
But the mock library raises:
TypeError: exceptions must be old-style classes or derived from BaseException,
not MagicMock
How can I test my code: I want imaplib.search
to raise imaplib.error
I found a solution:
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.