unittest mock.patch only once

Viewed 976

I am testing a function doing two times a "requests.post". Si I stub the call to this function. However, I want that the first stub return a fake data, and the second stub another fake data. How to do it ? Currently, I have :

@mock.patch('requests.post', side_effect=mocked_object)
def test_function_ok(self, mock_post):
    ...

And I want something like this :

@mock.patch_once('requests.post', side_effect=mocked_1)
@mock.patch_once('requests.post', side_effect=mocked_2)
def test_function_ok(self, mock_post):
    ...
2 Answers

Thanks to MrBean Bremen. However, I must call the elements in the list, like this :

@mock.patch('requests.post', side_effect=[mocked_1(), mocked_2()])
def test_function_ok(self, mock_post):
    ...

You can send different data to be mocked to the request twice it will mock the method and return the expected data that is specified in return_value

@patch('the_function_path_you_want_to_mock')
def test_data(self, mock_obj):
    mock_obj.return_value.function_to_be_mocked.return_value = [data_to_mocked]
    response = self.client.post('/request', data=json.dumps(self.input_data), content_type='application/vnd.api+json', )

    mock_obj.return_value.function_to_be_mocked.return_value = [data_to_mocked]
    response = self.client.post('/request', data=json.dumps(self.input_data), content_type='application/vnd.api+json', )
Related