3

I am using Mock for Python Unit Testing. I am testing a function foo which contains a function bar that doesn't return anything, but fills a variable x (type:io.StringIO) as a side effect. I have mocked bar using MagicMock, but I don't know how to assign to x from a test script.

I have the following situation:

def foo():
    x = io.StringIO()
    bar(x)                 # x is filled with some string by bar method
    here some operation on x

To write a Unit Test case for foo, I have mocked bar with MagicMock (return value=None) but how to assign to x which is needed by foo.

3
  • Can you be more clearer of what you want? Commented Dec 6, 2013 at 8:31
  • 1
    Is the variable passed to the nested function, or is it just relying on the closure? Commented Dec 6, 2013 at 9:09
  • You're lucky that's an external call, which can be mocked. For dirty local tricks, see here. Commented Mar 22 at 16:20

1 Answer 1

5

You need to mock io.StringIO and you can then replace it with something else:

@mock.patch('mymodule.io.StringIO')
def test_foo(self, mock_stringio):
    mock_stringio.return_value = mock.Mock()

Note the use of return_value which means you're mocking the instance that's returned from the StringIO() call.

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.