Custom Search

Monday, January 26, 2015

Mocking Python builtin file open function

1)
Return custom text when invoking 'open("myfile.txt")'

>>>
>>> import mock
>>>
>>> open_mock = mock.mock_open(read_data='\nHello World\n')
>>>

>>>#* Here the target '__builtin__.open' is replaces with a new 'open_mock' object.
>>> with mock.patch('__builtin__.open', open_mock):
...     open("myfile.txt").read()

...
'\nHello World\n'
>>>
>>>


2)
Raise custom Exception when invoking 'open("myfile.txt")'
 
>>>
>>> with mock.patch('__builtin__.open') as open_mock:
...     open_mock.side_effect = IOError
...     open("myfile.txt").read()

...
Traceback (most recent call last):
  File "", line 3, in
  File "/usr/local/lib/python2.7/dist-packages/mock.py", line 955, in __call__
    return _mock_self._mock_call(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/mock.py", line 1010, in _mock_call
    raise effect
IOError
>>>
>>>



No comments:

Post a Comment