[英]Mocking a side_effect with Python unittest
我正在嘗試模擬我的history[0].status_code
,使其狀態代碼為200
,並使history[0].status_code
觸發IndexError
(因為沒有重定向)。 我能夠使status_code
返回200
,但是當我模擬具有所需副作用的歷史記錄時,不會觸發IndexError
。
@patch('requests.get')
def test_no_redirect(self, mock_requests):
mock_requests.return_value.status_code = 200
mock_requests.history[0].status_code.side_effect = IndexError()
response = requests.get('example.com')
self.assertRaises(IndexError, response.history[0].status_code)
self.assertTrue(200, response.status_code)
好的,我檢查了代碼,並想提幾件事。
首先assertRises
方法接收callable作為第二個參數;)其定義如下所示
def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
第二件事,如果您使用以下方式模擬status_code
mock_requests.return_value.status_code = 200
為什么不嘗試與歷史相同:
mock_requests.return_value.history = []
我們使用的是真實列表,而不是某種模擬,所以我認為它更好。 測試方法如下所示:
@patch('requests.get')
def test_no_redirect(self, mock_requests):
mock_requests.return_value.status_code = 200
mock_requests.return_value.history = []
mock_requests.history[0].status_code.side_effect = IndexError
response = requests.get('example.com')
self.assertRaises(IndexError, lambda: response.history[0])
self.assertTrue(200, response.status_code)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.