0

I am new to unit testing and I am trying to write unit test using patch.object to mock the function calls. The mocked function getObj() is called twice in the function which I am testing. First time when its called I am expecting None as return_value and second time I am expecting some_string. I am not getting how to do it.

The code is as follows:

def test_create(self):
    with contextlib.nested(
        patch.object(agent, 'try_connect',
        patch.object(util, 'get_obj', return_value = None),
        ) as (mock_try_connect, mock_get_obj):
        proxy_info = self.util.create(data)

I tried using side_effects, and give it as input to return_value but every time its returning None.

mock_value=Mock()
mock_value.side_effect = [None, 'some_string']
patch.object(util, 'get_obj', return_value = mock_value())
4
  • Why are you using a set as the side_effect? Surely you want something ordered? Could you expand on "not working correctly"? Commented Jan 28, 2016 at 10:03
  • @jonrsharpe The side_effect solution I founded out from some other answer here. Not working properly means, everytime when the call is made to get_obj its return value is `None'. Commented Jan 28, 2016 at 10:19
  • Then edit the question to say that. You probably want a list, not a set. And which "other answer"? Commented Jan 28, 2016 at 10:21
  • @jonrsharpe its not working with list too. The other answer which I referred is from [stackoverflow.com/questions/24897145/… Commented Jan 28, 2016 at 10:23

1 Answer 1

0

Use assert_has_calls to verify the mocked out object is being called exactly how you expect it to be called. This will help you debug your issue.

def test_create(self):
    with contextlib.nested(
            patch.object(agent, 'try_connect',
            patch.object(util, 'get_obj', side_effect = [None, 'some_string']),
            ) as (mock_try_connect, mock_get_obj):
        proxy_info = self.util.create(data)
        mock_try_connect.assert_has_calls([mock.call(#params), ...])
        mock_get_obj.assert_has_calls([...])

Now once you've debugged the issue you can delete the last two statements since they add nothing to your test coverage and make your code harder to maintain.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.