添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Python模拟request.post来抛出异常

5 人关注

使用 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
        response = requests.post(url, json=data)
    except requests.exceptions.ConnectionError as e:
        app.logger.error(...)
        response = None
        error = str(e)
    return error, response

服务器文件定义了。替换代码4】,而some_method是由@app.route(... methods=['PATCH'])调用的。
如果这个方法抛出一个错误,路由最终会返回一个500

测试是从用import serverapp = 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的隔离。

  • Mock requests.post to throw requests.exceptions.ConnectionError
  • Show that the method logs an error (I know I can mock my app.logger and assert that it logged during the execution)
  • 1 个评论
    那么你在哪里卡住了?你可以很好地模拟 requests.post ,而且你可以通过设置 side_effects 属性让模拟程序引发异常。
    python
    unit-testing
    mocking
    python-requests
    camelBack
    camelBack
    发布于 2018-02-11
    1 个回答
    Martijn Pieters
    Martijn Pieters
    发布于 2018-02-11
    已采纳
    0 人赞同

    模拟 requests.post 函数,并在模拟中设置 side_effect attribute to the desired exception:

    @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.
    

    来自链接的文件。

    这可以是一个在调用mock时被调用的函数,也可以是一个可迭代的或一个要引发的异常(类或实例)。

    [...]

    一个引发异常的模拟例子(用于测试API的异常处理)。

    >>> mock = Mock()
    >>> mock.side_effect = Exception('Boom!')
    >>> mock()
    Traceback (most recent call last):
    Exception: Boom!
    

    (黑体字强调是我的)。

    这也包括在Quick Guide section:

    替换代码1】允许你执行副作用,包括当一个模拟被调用时引发一个异常。

    >>> mock = Mock(side_effect=KeyError('foo'))
    >>> mock()