简体   繁体   English

用Python unittest模拟side_effect

[英]Mocking a side_effect with Python unittest

I'm trying to mock out my requests.get to have a status code of 200 and make history[0].status_code trigger an IndexError (since there were no redirects). 我正在尝试模拟我的history[0].status_code ,使其状态代码为200 ,并使history[0].status_code触发IndexError (因为没有重定向)。 I'm able to get status_code to return 200 , but when I mock out history with the desired side effect, the IndexError is not triggered. 我能够使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)

Ok, I checked the code and I'd like to mention a few things. 好的,我检查了代码,并想提几件事。

First of all assertRises method receives callable as the second parameter ;) Its definition looks like this 首先assertRises方法接收callable作为第二个参数;)其定义如下所示

def assertRaises(self, excClass, callableObj=None, *args, **kwargs):

The second thing, if you are mocking status_code using 第二件事,如果您使用以下方式模拟status_code

mock_requests.return_value.status_code = 200

why not to try the same with history: 为什么不尝试与历史相同:

mock_requests.return_value.history = []

We are using the real list instead of some kind of mock, so I think that it's even better. 我们使用的是真实列表,而不是某种模拟,所以我认为它更好。 The test method could look like this: 测试方法如下所示:

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM