[issue31855] mock_open is not compatible with read(n) (and pickle.load)

2017-10-23 Thread Ron Rothman

New submission from Ron Rothman :

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 
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 
<https://bugs.python.org/issue31855>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue31855] mock_open is not compatible with read(n) (and pickle.load)

2017-10-23 Thread Ron Rothman

Ron Rothman  added the comment:

Confirmed that the behavior exists in Python 3.6 as well.

--
versions: +Python 3.6

___
Python tracker 
<https://bugs.python.org/issue31855>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com