1

E.g., I wrote some data to the file and then try to read them:

mocked_open = mock_open()
with patch('__builtin__.open', mocked_open, create=True):
    with open('file', 'w') as f:
        f.write('text')

    with open('file', 'r') as f:
        res = f.read()

But after this,res is empty. How to get written data for this file?

Bred
  • 11
  • 5
  • `res` is out of scope as written. If you define res to be, say, an empty string or `None` outside of the with block, you should be able to read it. – BlackVegetable Feb 13 '15 at 17:31
  • Lots on mocking `open` here: http://stackoverflow.com/questions/1289894/how-do-i-mock-an-open-used-in-a-with-statement-using-the-mock-framework-in-pyth – jlb83 Feb 13 '15 at 17:36
  • My guess is that is a [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). I don't think you want test a code where it write some data in a file and then read it from the same file. Maybe you need to test a code that read a file or a code where it write some data, but not both. If you need just read try with `mocked_open=mock_open(read_data="text")` and it should work as you want. – Michele d'Amico Feb 16 '15 at 11:40

0 Answers0