[更新:这是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
)。