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

后端 未结 1 641
梦毁少年i
梦毁少年i 2020-12-12 16:47

I have a function (foo) which calls another function (bar). If invoking bar() raises an HttpError, I want to handle it sp

相关标签:
1条回答
  • 2020-12-12 17:19

    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.

    0 讨论(0)
提交回复
热议问题