[英]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.