[英]Mock requests exception not being thrown by side_effect
So I am trying to test exception handling code and side_effect is not working properly. 因此,我正在尝试测试异常处理代码,并且side_effect无法正常工作。 The printed output shows that it is making the calls but the raise_for_status is not correctly throwing the exception in side_effect.
打印的输出表明它正在进行调用,但是raise_for_status没有正确地在side_effect中引发异常。 Why is the exception not being thrown?
为什么不引发异常?
UPDATE: Okay, no idea why this works, but it does at least make it drop into the right except. 更新:好的,不知道为什么会这样,但是至少可以使它掉入正确的位置。 I changed it to use patch.object and gave both the mock raise_for_status and mock get objects HTTPError() for side_effect.
我将其更改为使用patch.object,并为side_effect提供了模拟raise_for_status和模拟获取对象HTTPError()。 That got it to drop down into the correct except block but it still did not throw the exception according to the unit tests.
这样可以将其放到正确的except块中,但是根据单元测试,它仍然没有引发异常。
This is the code test_src.py located in test_package: 这是位于test_package中的代码test_src.py:
import requests
import sys
import traceback
def test_requests_function():
try:
response = requests.get('https://google.com/api/test', verify=False)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as error:
return_message = "Exception: {0}".format(str(error))
return {'return_code' : 500, 'message' : return_message, 'traceback' : traceback.format_exc()}
except:
return_message = "Unknown Exception: {0}".format(str(sys.exc_info()[0]))
return {'return_code' : 500, 'message' : return_message, 'traceback' : traceback.format_exc()}
This is the test code: 这是测试代码:
import unittest
from pprint import pprint
import mock
import requests
from test_package import test_src
class TestRequestTestCase(unittest.TestCase):
@mock.patch.object(requests, 'get')
def test_request_exception(self, mock_get):
http_error = requests.exceptions.HTTPError('Unable to connect')
mock_raise_for_status = mock.Mock(side_effect=http_error)
mock_get.raise_for_status = mock_raise_for_status
mock_get.side_effect = http_error
return_json = test_src.test_requests_function()
print "\nMock_Get:"
print id(mock_get)
pprint(mock_get.__dict__)
print "\nMock_Raise_For_Status:"
print id(mock_raise_for_status)
pprint(mock_raise_for_status.__dict__)
print "\n"
pprint(return_json)
So the ouptut is: 所以输出是:
{'message': 'Exception: Unable to connect',
'return_code': 500,
'traceback': 'Traceback (most recent call last):\n File "/Users/yshaban/test/test_package/test_src.py", line 8, in test_requests_function\n response = requests.get(\'https://google.com/api/test\', verify=False)\n File "/Users/yshaban/test/lib/python2.7/site-packages/mock/mock.py", line 1062, in __call__\n return _mock_self._mock_call(*args, **kwargs)\n File "/Users/yshaban/test/lib/python2.7/site-packages/mock/mock.py", line 1118, in _mock_call\n raise effect\nHTTPError: Unable to connect\n'
}
======================================================================
FAIL: test_request_exception (__main__.TestRequestTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/yshaban/test/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
File "unit_tests.py", line 36, in test_request_exception
pprint(return_json)
AssertionError: RequestException not raised
----------------------------------------------------------------------
It seems you are patching the wrong object. 似乎您正在修补错误的对象。 You should patch the
get
function in test_src.requests
. 您应该在
test_src.requests
修补get
函数。 Change (do not move) the decorator to: 将装饰器更改(不要移动)为:
@mock.patch.object(test_src.requests, 'get')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.