Skip to content

Instantly share code, notes, and snippets.

@incfly
Last active August 29, 2015 14:24
Show Gist options
  • Save incfly/e848e78f67eabcc515dc to your computer and use it in GitHub Desktop.
Save incfly/e848e78f67eabcc515dc to your computer and use it in GitHub Desktop.
Mock module.function
############################################################
# how mock really work: just replace the attribute.
############################################################
class MyClass(object):
def getname(self):
return 'real getname'
def fake_getname():
return 'fake getname'
cls = MyClass()
cls.getname = fake_getname
print cls.getname()
cls.getname = Mock(return_value='from mock library')
print cls.getname()
############################################################
# patch module level function
############################################################
i = 1
def GetInfo():
global i
i += 1
return i
def mock_GetInfo():
global i
i += 1
return 2 * i
def PrintInfo():
print GetInfo()
print GetInfo()
@patch('__main__.GetInfo')
def testPrintInfo(mock_fn):
mock_fn.return_value = 1
mock_fn.side_effect = mock_GetInfo
PrintInfo()
testPrintInfo()
############################################################
# patch class method.
############################################################
class MyClass(object):
def getname(self, first, last):
return first + " " + last
def mock_getname(first, last):
return "mocked: " + first + " " + last
@patch.object(MyClass, 'getname')
def patched_fn(mock_run):
mock_run.return_value = 123
mock_run.side_effect = mock_getname
cls = MyClass()
print cls.getname("jianfei", "hu")
patch_fn()
############################################################
# patch entire class.
############################################################
@patch('__main__.MyClass')
def patched_cls(mock_cls):
# mock_run = MagicMock()
# #mock_run.side_effect = fake_showrun
# mock_run.return_value = 12345
# mocked_cls.showrun = mock_run
mock_op = MagicMock(return_value="always same")
mock_op.return_value = "always same" # class name will be called and treated as function in eyes of Mock()
mock_instance = MagicMock()
mock_instance.getname = mock_op
mock_cls.return_value = mock_instance
cls = MyClass()
print cls.getname("jianfei", "hu")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment