2016-09-29 48 views
-1

我有一個簡單的函數,發送一個獲取請求到一個API,我想能夠寫一個單元測試來聲明,腳本打印錯誤,然後如果請求返回異常則退出。Python單元測試與嘲笑request.get,沒有引發特定的異常

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

您的示例代碼* does *會導致引發異常,但您的函數*捕獲並處理它*。 –

回答

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())