1

I am testing a function in which both

def foo():
    with open('input.dat', 'r') as f:
        ....
    with open('output.dat', 'w') as f:
        ....

are used. But I only want to mock the write part. Is it possible to do that? Or some other strategy should be used for testing such a function?

with patch('__builtin__.open') as m:
    foo()

would fail to read the data.

Thanks in advance.

nos
  • 19,875
  • 27
  • 98
  • 134
  • Possible duplicate of [Conditional mocking: Call original function if condition does match](https://stackoverflow.com/questions/29562460/conditional-mocking-call-original-function-if-condition-does-match) – quamrana Aug 10 '17 at 15:12
  • @quamrana Although my question is about conditional mocking, being a special case, it has a more convenient answer than the general solution in that cited question. – nos Aug 13 '17 at 02:25

1 Answers1

0

I found the following solution:

from mock import patch, mock_open

with open('ref.dat') as f:
    ref_output = f.read()
with open('input.dat') as f:
    input = f.read()

with patch('__builtin__.open', mock_open(read_data=input)) as m:
    foo()
    m.assert_called_with('output.dat', 'w')
    m().write.assert_called_once_with(ref_output)
nos
  • 19,875
  • 27
  • 98
  • 134