mock.mock_open works as expected when reading the entire file (read()) or when reading a single line (readline()), but it seems to not support reading a number of bytes (read(n)).
These work as expected:
from mock import mock_open, patch
# works: consume entire "file"
with patch('__main__.open', mock_open(read_data='bibble')) as m:
with open('foo') as h:
result = h.read()
assert result == 'bibble' # ok
# works: consume one line
with patch('__main__.open', mock_open(read_data='bibble\nbobble')) as m:
with open('foo') as h:
result = h.readline()
assert result == 'bibble\n' # ok
But trying to read only a few bytes fails--mock_open returns the entire read_data instead:
# consume first 3 bytes of the "file"
with patch('__main__.open', mock_open(read_data='bibble')) as m:
with open('foo') as h:
result = h.read(3)
assert result == 'bib', 'result of read: {}'.format(result) # fails
Output:
Traceback (most recent call last):
File "/tmp/t.py", line 25, in <module>
assert result == 'bib', 'result of read: {}'.format(result)
AssertionError: result of read: bibble
The unfortunate effect of this is that mock_open cannot be used with pickle.load.
with open('/path/to/file.pkl', 'rb') as f:
x = pickle.load(f) # this requires f.read(1) to work |