pip install mock # https://pypi.python.org/pypi/mock
# attributes, methods are easy to mock
self.mock_user = Mock()
self.mock_user.is_guest = False
self.mock_user.can_run = Mock(return_value=True)
self.patch('user.User.load', self.mock_user)
yield Controller.user_check(self.session)
self.mock_user.can_run.assert_called_with(self.session.user_id)
- - -
def patch(self, path, return_value=None):
"""Mock patching helper since it's a little weird with deferreds
See: http://code.google.com/p/mock/issues/detail?id=96
"""
patcher = mock.patch(path)
self.patches[path] = patcher
obj = patcher.start()
obj.return_value = defer.succeed(return_value)
return obj
- - -
from mock import Mock
real = ProductionClass()
real.method = Mock( return_value=3 )
real.method(3, 4, 5, key='value')
real.method.assert_called_with(3, 4, 5, key='value') # verify the mock was used correctly
- - -
# "side effects" allow overriding the mock for different return values or Exceptions
>>> mock = Mock(side_effect=KeyError('foo'))
>>> mock()
Traceback (most recent call last):
...
KeyError: 'foo'
>>> values = {'a': 1, 'b': 2, 'c': 3}
>>> def side_effect(arg):
... return values[arg]
...
>>> mock.side_effect = side_effect
>>> mock('a'), mock('b'), mock('c')
(1, 2, 3)
>>> mock.side_effect = [5, 4, 3, 2, 1]
>>> mock(), mock(), mock()
(5, 4, 3)
- - -
from mock import patch
import DependencyDBService
def test_example_path( self , service ):
with patch.object( DependencyDBService, 'write_to_db_new_account') as mock_write_to_db_new_account:
mock_write_to_db_new_account.return_value = False
result = service.create_account( name='test' )
print result # verify that the under test service reacts correctly to the DB layer returning False
@patch('test_module.ClassName1')
@patch('test_module.ClassName2')
def test(MockClass2, MockClass1):
test_module.ClassName1()
test_module.ClassName2()
assert MockClass1.called
assert MockClass2.called
test()
# override a dictionary only for a single execution (i.e. during the specific test runtime)
>>> foo = {'key': 'value'}
>>> original = foo.copy()
>>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
... assert foo == {'newkey': 'newvalue'}
...
>>> assert foo == original
# Mock python "magic methods" like __str__
from mock import MagicMock
mock = MagicMock()
mock.__str__.return_value = 'foobarbaz'
str( mock ) # 'foobarbaz'
mock.__str__.assert_called_once_with()