2 回答

TA貢獻1906條經驗 獲得超3個贊
我今天遇到了同樣的問題,忘記了我正在使用上下文,所以只需更改
mock.sendmail.assert_called()
到
mock.return_value.__enter__.return_value.sendmail.assert_called()
這看起來很混亂,但這是我的例子:
msg = EmailMessage()
msg['From'] = 'no@no.com'
msg['To'] = 'no@no.com'
msg['Subject'] = 'subject'
msg.set_content('content');
with patch('smtplib.SMTP', autospec=True) as mock_smtp:
misc.send_email(msg)
mock_smtp.assert_called()
context = mock_smtp.return_value.__enter__.return_value
context.ehlo.assert_called()
context.starttls.assert_called()
context.login.assert_called()
context.send_message.assert_called_with(msg)

TA貢獻1780條經驗 獲得超4個贊
我將 Dustymugs 的帖子標記為答案,但我發(fā)現(xiàn)了另一種技術來對依賴于模擬 method_calls 的調用進行單元測試。
import unittest.mock
with unittest.mock.patch('smtplib.SMTP', autospec=True) as mock:
? ? import smtplib
? ? smtp = smtplib.SMTP('localhost')
? ? smtp.sendmail('me', 'you', 'hello world\n')
? ? # Validate sendmail() was called
? ? name, args, kwargs = smtpmock.method_calls.pop(0)
? ? self.assertEqual(name, '().sendmail')
? ? self.assertEqual({}, kwargs)
? ? # Validate the sendmail() parameters
? ? from_, to_, body_ = args
? ? self.assertEqual('me', from_)
? ? self.assertEqual(['you'], to_)
? ? self.assertIn('hello world', body_)
添加回答
舉報