Jan 20, 2012

Mocking

Mock basics

mock = Mock(name='bar', return_value='fish')
mock(1, 2, spam = 99)
# 'fish'
mock.assert_called_once_with(1, 2, spam = 99)
mock.called
# True
mock.call_count
# 1
mock.call_args
# ((1, 2), {'spam': 99})
From: http://blip.tv/pycon-us-videos-2009-2010-2011/pycon-2011-testing-with-mock-4899484

Magic Mock basics

mock = MagicMock()
mock[5]
# <mock.Mock object at 0x2f90690>
mock.__str__.return_value = 'bzzzz'
str(mock)
# 'bzzzz'

Mock exceptions handling test

mock = Mock(side_effect=KeyError('boom'))
mock()
# Traceback (most recent call last)
# ....
# KeyError: 'boom'

Mock file write

>>> open_name = '%s.open' % __name__
>>> with patch(open_name, create=True) as mock_open:
...     mock_open.return_value = MagicMock(spec=file)
...
...     with open('/some/path', 'w') as f:
...         f.write('something')
...

>>> file_handle = mock_open.return_value.__enter__.return_value
>>> file_handle.write.assert_called_with('something')
http://stackoverflow.com/questions/1289894/how-do-i-mock-an-open-used-in-a-with-statement-using-the-mock-framework-in-pyth
http://www.voidspace.org.uk/python/mock/magicmock.html

Mock file and raw_post_data

from mock import Mock, MagicMock

class SomeTestCase(TestCase):

    def testRawPostData(self):
        ...

        request = Mock(spec=request)
        request.raw_post_data = 'myrawdata'
        print request.raw_post_data  # prints 'myrawdata'

        file_mock = MagicMock(spec=file)
        file_mock.read.return_value = 'myfiledata'
        request.FILES = {'myfile': file_mock}    
        print request.FILES['myfile'].read()  # prints 'myfiledata'

Mocking stdout

outstream = StringIO()
with patch('sys.stdout', new=outstream) as out:
    ...
    actual_out = out.getvalue()

Video: 
A Gentle Introduction to Mock for Python
Why Use Mock?
Mock and Django

No comments: