read(n)与mock_open兼容吗?

时间:2017-10-23 20:35:36

标签: python python-mock

[更新:这是a known bug。]

有没有办法将read(some_number_of_bytes)mock_open一起使用?

mock_open在阅读整个文件(read())或阅读单行(readline())时按预期工作,但在阅读多个文件时我无法正常工作bytes(read(n)

这些片段(改编自Mock documentation)的工作(Python 2.7):

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

但是尝试只读取几个字节失败 - mock_open会返回整个read_data

# 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

输出:

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

如果这是一个XY问题,我会注意到这个问题的原因是我正在嘲笑我传入pickle.load的文件,后者又调用read(1)。< / p>

with open('/path/to/file.pkl', 'rb') as f:
    x = pickle.load(f)  # this requires f.read(1) to work

我更愿意模仿可能的最低级别(open而不是pickle.load)。

1 个答案:

答案 0 :(得分:0)

作为记录,本期has been fixed in Python 3.7