Trying to mock.patch a call to smtplib.SMTP.sendmail
in a unittest. The sendmail
method appears to be successfully mocked and we can query it as MagicMock
, but the called
and called_args
attributes of the sendmail mock are not correctly updated. It seems likely I'm not applying the patch correctly.
Here's a simplified example of what I'm trying:
import unittest.mock
with unittest.mock.patch('smtplib.SMTP', autospec=True) as mock:
import smtplib
smtp = smtplib.SMTP('localhost')
smtp.sendmail('me', 'me', 'hello world\n')
mock.assert_called() # <--- this succeeds
mock.sendmail.assert_called() # <--- this fails
This example generates:
AssertionError: Expected 'sendmail' to have been called.
If I alter the patch to smtp.SMTP.sendmail
; eg:
with unittest.mock.patch('smtplib.SMTP.sendmail.', autospec=True) as mock:
...
I can successfully access the called_args
and called
attributes of the mock in this case, but because the smtplib.SMTP
initialization was allowed to take place, an actual smtp-session is established with a host. This is unittesting, and I'd prefer no actual networking take place.