[issue31855] mock_open is not compatible with read(n) (and pickle.load)
Ron Rothman
report at bugs.python.org
Mon Oct 23 17:03:10 EDT 2017
New submission from Ron Rothman <ron.rothman at gmail.com>:
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
----------
components: Library (Lib)
messages: 304841
nosy: ron.rothman
priority: normal
severity: normal
status: open
title: mock_open is not compatible with read(n) (and pickle.load)
type: behavior
versions: Python 2.7
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue31855>
_______________________________________
More information about the Python-bugs-list
mailing list