read(n) 与 mock_open 兼容吗?
Is read(n) compatible with mock_open?
[更新:这是a known bug。]
有没有办法将 read(some_number_of_bytes)
与 mock_open
一起使用?
mock_open
在读取整个文件 (read()
) 或读取单行 (readline()
) 时按预期工作,但在读取文件时无法正常工作字节数 (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
returns 整个 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)
.
with open('/path/to/file.pkl', 'rb') as f:
x = pickle.load(f) # this requires f.read(1) to work
我更愿意模拟尽可能低的级别(open
而不是 pickle.load
)。
郑重声明,本期has been fixed in Python 3.7。
[更新:这是a known bug。]
有没有办法将 read(some_number_of_bytes)
与 mock_open
一起使用?
mock_open
在读取整个文件 (read()
) 或读取单行 (readline()
) 时按预期工作,但在读取文件时无法正常工作字节数 (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
returns 整个 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)
.
with open('/path/to/file.pkl', 'rb') as f:
x = pickle.load(f) # this requires f.read(1) to work
我更愿意模拟尽可能低的级别(open
而不是 pickle.load
)。
郑重声明,本期has been fixed in Python 3.7。