The Python Oracle

Mocking a function to raise an Exception to test an except block

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island Looping

--

Chapters
00:00 Question
01:59 Accepted answer (Score 199)
02:59 Thank you

--

Full question
https://stackoverflow.com/questions/2830...

Question links:
[Mock docs]: http://www.voidspace.org.uk/python/mock/...
https://stackoverflow.com/a/10310532/346...
[How to use Python Mock to raise an exception - but with Errno set to a given value]: https://stackoverflow.com/q/20547038/346...

Accepted answer links:
[HttpError]: https://github.com/google/google-api-pyt...

--

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.