简体   繁体   中英

python mock side-effect return value

I am trying to test some code that makes an external call. I want to mock that call out. The call takes keyword args, so I wrote this little helper function in my test:

def mock_function(*args, **kwargs)
    io_obj = StringIO()
    for k,v in kwargs.iteritems():
        io_obj.write("{}: {}\n".format(k, v)
    print "\n{}".format(io_obj.getvalue()) # for testing purposes
    return io_obj

in my setUp function for the test class, I have this:

@patch('function_to_test')
def setUp(self, mock_dude):
    self.mock_client = mock_dude.return_value
    self.mock_client.function_to_test.side_effect = mock_function
    self.client = ClientClass()

in my test function, I am calling the function that calls the external function. I get the printout from mock_function, so I know that I am mocking the function correctly. My question is this:

How can I get at the io_obj that is created in mock_function? My external function doesn't return anything.

The Mock object actually captures the arguments it's called with, so you don't need to write your own function to do that. You can access the arguments directly using Mock.call_args , or assert that the mock was called with certain arguments using assert_called_with .

Example:

>>> m = mock.Mock()
>>> m(1,2,3)
<Mock name='mock()' id='139905514719504'>
>>> m.call_args
call(1, 2, 3)
>>> m.assert_called_with(1,2,4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib64/python2.6/site-packages/mock.py", line 835, in assert_called_with
    raise AssertionError(msg)
AssertionError: Expected call: mock(1, 2, 4)
Actual call: mock(1, 2, 3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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