Python单元测试request.get与mocking,而不是提出特定的异常

时间:2016-09-29 14:27:32

标签: python unit-testing

我有一个简单的函数,它向API发送一个get请求,我希望能够编写一个Unit测试来断言scriprt输出错误,然后在请求返回异常时退出。

def fetch_members(self):
    try:
        r = requests.get(api_url, auth=('user', api_key))
    except requests.exceptions.HTTPError as error:
        print(error)
        sys.exit(1)

我已尝试过以下测试,但从未提出HTTPError

import requests
from unittest.mock import patch

@patch('sys.exit')
@patch('sys.stdout', new_callable=StringIO)
@patch('requests.get')
def test_fetch_members_with_bad_request(self, mock_get, mock_stdout,
                                        mock_exit):
    response = requests.Response()
    response.status_code = 400  # Bad reqeust
    mock_get.return_value = response
    mock_get.side_effect = requests.exceptions.HTTPError
    with self.assertRaises(requests.exceptions.HTTPError):
        fetch_members()
        mock_exit.assert_called_once_with(1)
        self.assertIsNotNone(mock_stdout.getvalue())

我如何才能正确修补requests.get以便总是引发某种错误?

1 个答案:

答案 0 :(得分:1)

您的函数捕获并处理异常:

except requests.exceptions.HTTPError as error:

这意味着永远不会进一步传播,因此assertRaises()失败。只是声称sys.exit()已被调用,这就足够了。

设置返回值也没有意义;该调用引发了异常。以下就足够了:

@patch('sys.exit')
@patch('sys.stdout', new_callable=StringIO)
@patch('requests.get')
def test_fetch_members_with_bad_request(self, mock_get, mock_stdout,
                                        mock_exit):
    mock_get.side_effect = requests.exceptions.HTTPError
    fetch_members()
    mock_exit.assert_called_once_with(1)
    self.assertIsNotNone(mock_stdout.getvalue())