Python read(n)是否与mock_open兼容?
[更新:这是 有没有一种方法可以将Python read(n)是否与mock_open兼容?,python,python-mock,Python,Python Mock,[更新:这是 有没有一种方法可以将read(一些字节)与mock\u open一起使用 mock\u open在读取整个文件(read())或读取一行(readline())时按预期工作,但在读取大量字节(read(n))时无法使其工作 这些代码片段(改编自)工作(Python 2.7): 但是尝试只读取几个字节失败--mock\u open返回整个read\u数据: # consume first 3 bytes of the "file" with patch('__main__.open'
read(一些字节)
与mock\u open一起使用
mock\u open
在读取整个文件(read()
)或读取一行(readline()
)时按预期工作,但在读取大量字节(read(n)
)时无法使其工作
这些代码片段(改编自)工作(Python 2.7):
但是尝试只读取几个字节失败--mock\u open
返回整个read\u数据
:
# 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
我更喜欢模拟尽可能低的级别(open
而不是pickle.load
)。记录下,这个问题。这看起来像是mock\u open
中的一个bug(或者至少是一个缺陷)。考虑一下,谢谢你的提示-打开了一个问题。
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
with open('/path/to/file.pkl', 'rb') as f:
x = pickle.load(f) # this requires f.read(1) to work