Mocking a function to raise an Exception to test an except block
我有一个函数(
我试图围绕这个
下面是我的代码,它说明了我的问题:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | import unittest import mock from apiclient.errors import HttpError class FooTests(unittest.TestCase): @mock.patch('my_tests.bar') def test_foo_shouldReturnResultOfBar_whenBarSucceeds(self, barMock): barMock.return_value = True result = foo() self.assertTrue(result) # passes @mock.patch('my_tests.bar') def test_foo_shouldReturnNone_whenBarRaiseHttpError404(self, barMock): barMock.side_effect = HttpError(mock.Mock(return_value={'status': 404}), 'not found') result = foo() self.assertIsNone(result) # fails, test raises HttpError @mock.patch('my_tests.bar') def test_foo_shouldRaiseHttpError_whenBarRaiseHttpErrorNot404(self, barMock): barMock.side_effect = HttpError(mock.Mock(return_value={'status': 500}), 'error') with self.assertRaises(HttpError): # passes foo() def foo(): try: result = bar() return result except HttpError as error: if error.resp.status == 404: print '404 - %s' % error.message return None raise def bar(): raise NotImplementedError() |
我按照模拟文档的说明,您应该将
我还查看了一些其他相关的stackoverflow q&as,看起来我正在做与它们所做的相同的事情,它们的模拟会引发异常。
- https://stackoverflow.com/a/10310532/346561
- 如何使用python mock引发异常-但将errno设置为给定值
为什么设置
您的模拟会引发异常,但缺少
1 | barMock.side_effect = HttpError(mock.Mock(status=404), 'not found') |
我把你的
1 2 3 4 5 6 7 8 9 | >>> 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 |
你甚至可以看到