Skip to content

Instantly share code, notes, and snippets.

@cosimo
Last active November 11, 2016 16:33
Show Gist options
  • Save cosimo/65b23bce874e58b101e7bb366e3f7ee5 to your computer and use it in GitHub Desktop.
Save cosimo/65b23bce874e58b101e7bb366e3f7ee5 to your computer and use it in GitHub Desktop.
Example of usage of python's mock.patch.object()
# encoding: utf-8
import mock
class smtplib(object):
pass
@mock.patch.object(smtplib, "sendmail", create=True)
def test_mocked_method(*args):
"""
I want to call smtplib().sendmail("somebody")
"""
smtplib.sendmail("blah")
print("test_mocked_method:", smtplib.sendmail.call_args)
@mock.patch.object(smtplib, "sendmail", create=True)
def test_mocked_class_method(*args):
"""
I want to call smtplib.sendmail("somebody")
"""
s = smtplib()
s.sendmail("blah")
print("test_mocked_class_method:", s.sendmail.call_args)
def test_using_context_manager(*args):
"""
I want to call smtplib.sendmail("somebody")
"""
with mock.patch.object(smtplib, "sendmail", create=True) as sendmail:
sendmail("hoolla", "jalla", "ohyeah")
sendmail(1, 2, 3)
print("test_using_context_manager:", sendmail.call_args_list)
"""
Output:
('test_mocked_method:', call('blah'))
('test_mocked_class_method:', call('blah'))
('test_using_context_manager:', [call('hoolla', 'jalla', 'ohyeah'), call(1, 2, 3)])
"""
if __name__ == "__main__":
test_mocked_method()
test_mocked_class_method()
test_using_context_manager()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment