I use python-mock to mock an open file. I would like to be able to pass fake data this way, so I can verify that the read() call is being called, as well as using test data without getting into the file system during testing.
Here is what I have so far:
file_mock = MagicMock(spec=file) file_mock.read.return_value = 'test' with patch('__builtin__.open', create=True) as mock_open: mock_open.return_value = file_mock with open('x') as f: print f.read()
The result of this is <mock.Mock object at 0x8f4aaec> int 'test' , as I expected. What am I doing wrong in building this layout?
Edit:
It looks like:
with open('x') as f: f.read()
and this:
f = open('x') f.read()
- different objects. Using the layout as a context manager forces it to return a new Mock , while calling it directly returns everything that I defined in mock_open.return_value . Any ideas?
source share