Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Quick mock example showing how to simulate errors
>>> from unittest import mock
>>> import json
>>> m_o = mock.mock_open()
>>> m_o.side_effect = OSError('Insufficient voltage')
>>> json.load(m_o('foo.json', 'rb'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/mock.py", line 896, in __call__
return _mock_self._mock_call(*args, **kwargs)
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/mock.py", line 952, in _mock_call
raise effect
OSError: Insufficient voltage
>>> with mock.patch('__main__.open', m_o, create=True):
... json.load(open('foo', 'rb'))
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/mock.py", line 896, in __call__
return _mock_self._mock_call(*args, **kwargs)
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/mock.py", line 952, in _mock_call
raise effect
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/mock.py", line 896, in __call__
return _mock_self._mock_call(*args, **kwargs)
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/mock.py", line 952, in _mock_call
raise effect
OSError: Insufficient voltage
>>> def read_the_json(filename):
... with open(filename, 'r') as f:
... return json.load(f)
...
>>> read_the_json('foo.json')
[0, 1, 2]
>>> with patch('__main__.open', m_o, create=True):
... read_the_json('foo.json')
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in read_the_json
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/mock.py", line 896, in __call__
return _mock_self._mock_call(*args, **kwargs)
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/mock.py", line 952, in _mock_call
raise effect
OSError: Insufficient voltage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.