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条经验 获得超3个赞
我将 Dustymugs 的帖子标记为答案,但我发现了另一种技术来对依赖于模拟 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_)
添加回答
举报