Mocking a function to raise an Exception to test an except block
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Track title: CC L Beethoven - Piano Sonata No 8 in C
--
Chapters
00:00 Mocking A Function To Raise An Exception To Test An Except Block
01:42 Accepted Answer Score 215
02:36 Thank you
--
Full question
https://stackoverflow.com/questions/2830...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #unittesting #python27 #mocking #pythonmock
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Track title: CC L Beethoven - Piano Sonata No 8 in C
--
Chapters
00:00 Mocking A Function To Raise An Exception To Test An Except Block
01:42 Accepted Answer Score 215
02:36 Thank you
--
Full question
https://stackoverflow.com/questions/2830...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #unittesting #python27 #mocking #pythonmock
#avk47
ACCEPTED ANSWER
Score 221
Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:
barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
Additional keyword arguments to Mock() are set as attributes on the resulting object.
I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:
>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
... barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
... result = my_test.foo()
...
404 -
>>> result is None
True
You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.