[英]Python mock requests.post to throw exception
Using Python 3.5, requests==2.18.4, Flask==0.12.2, urllib3==1.22使用 Python 3.5,requests==2.18.4,Flask==0.12.2,urllib3==1.22
I have a method some_method
in my main server.py
file, that is supposed to make a POST
to some url with some data:我的主
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
The server file defines: app = Flask(__name__)
, and some_method
is called from @app.route(... methods=['PATCH'])
.服务器文件定义:
app = Flask(__name__)
,并且some_method
是从@app.route(... methods=['PATCH'])
调用的。
If this method throws an error, the route will eventually return a 500
.如果此方法抛出错误,则路由最终将返回
500
。
Tests are run from a test file importing the app with import server
and app = server.app
, using unittest
, and importing mock.patch
.测试从使用
import server
和app = server.app
导入应用程序的测试文件运行,使用unittest
,并导入mock.patch
。
I am able to test the overall app behavior, with a test that shows that the app route behave as expected when the method returns an error and seeing that the route terminates at the right spot:我能够测试整个应用程序的行为,测试表明当方法返回错误并看到路由在正确的位置终止时,应用程序路由的行为符合预期:
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)
However, I would really like to have another test to test some_method
in isolation:但是,我真的很想进行另一个测试来
some_method
测试some_method
:
requests.post
to throw requests.exceptions.ConnectionError
requests.post
抛出requests.exceptions.ConnectionError
app.logger
and assert that it logged during the execution)app.logger
并断言它在执行期间记录了)Mock the requests.post
function, and on the mock set the side_effect
attribute to the desired exception:模拟
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.
From the linked documentation:从链接的文档:
This can either be a function to be called when the mock is called, an iterable or an exception (class or instance) to be raised.
这可以是在调用模拟时要调用的函数、可迭代或要引发的异常(类或实例)。
[...]
[...]
An example of a mock that raises an exception (to test exception handling of an API):
引发异常的模拟示例(用于测试 API 的异常处理):
>>> mock = Mock() >>> mock.side_effect = Exception('Boom!') >>> mock() Traceback (most recent call last): ... Exception: Boom!
(Bold emphasis mine). (粗体强调我的)。
This is also covered in the Quick Guide section :这也包含在快速指南部分:
side_effect
allows you to perform side effects, including raising an exception when a mock is called:side_effect
允许您执行副作用,包括在调用模拟时引发异常:>>> mock = Mock(side_effect=KeyError('foo')) >>> mock() Traceback (most recent call last): ... KeyError: 'foo'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.