[英]Python mock requests.post to throw exception
使用 Python 3.5,requests==2.18.4,Flask==0.12.2,urllib3==1.22
我的主server.py
文件中有一個some_method
方法,它應該使用一些數據對某個 url 進行POST
:
def some_method(url, data):
...
error = None
try:
response = requests.post(url, json=data)
except requests.exceptions.ConnectionError as e:
...
app.logger.error(...)
response = None
error = str(e)
return error, response
服務器文件定義: app = Flask(__name__)
,並且some_method
是從@app.route(... methods=['PATCH'])
調用的。
如果此方法拋出錯誤,則路由最終將返回500
。
測試從使用import server
和app = server.app
導入應用程序的測試文件運行,使用unittest
,並導入mock.patch
。
我能夠測試整個應用程序的行為,測試表明當方法返回錯誤並看到路由在正確的位置終止時,應用程序路由的行為符合預期:
class ServerTestCase(unittest.TestCase):
...
@patch('server.some_method')
def test_route_response_status_500_when_throws(self, mock_response):
mock_response.return_value = 'some_error_string', None
response = self.app.patch(some_url, some_data, content_type='application/json')
self.assertEqual(response.status_code, 500)
但是,我真的很想進行另一個測試來some_method
測試some_method
:
requests.post
拋出requests.exceptions.ConnectionError
app.logger
並斷言它在執行期間記錄了)模擬requests.post
函數,並在模擬中將side_effect
屬性設置為所需的異常:
@patch('requests.post')
def test_request_post_exception(self, post_mock):
post_mock.side_effect = requests.exceptions.ConnectionError()
# run your test, code calling `requests.post()` will trigger the exception.
從鏈接的文檔:
這可以是在調用模擬時要調用的函數、可迭代或要引發的異常(類或實例)。
[...]
引發異常的模擬示例(用於測試 API 的異常處理):
>>> mock = Mock() >>> mock.side_effect = Exception('Boom!') >>> mock() Traceback (most recent call last): ... Exception: Boom!
(粗體強調我的)。
這也包含在快速指南部分:
side_effect
允許您執行副作用,包括在調用模擬時引發異常:>>> mock = Mock(side_effect=KeyError('foo')) >>> mock() Traceback (most recent call last): ... KeyError: 'foo'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.