Author ron.rothman
Recipients ron.rothman
Date 2017-10-23.21:03:10
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1508792590.83.0.213398074469.issue31855@psf.upfronthosting.co.za>
In-reply-to
Content
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
History
Date User Action Args
2017-10-23 21:03:10ron.rothmansetrecipients: + ron.rothman
2017-10-23 21:03:10ron.rothmansetmessageid: <1508792590.83.0.213398074469.issue31855@psf.upfronthosting.co.za>
2017-10-23 21:03:10ron.rothmanlinkissue31855 messages
2017-10-23 21:03:10ron.rothmancreate