简体   繁体   English

read(n) 与 mock_open 兼容吗?

[英]Is read(n) compatible with mock_open?

[ Update: This is a known bug .] [更新:这是一个已知错误。]

Is there a way to use read(some_number_of_bytes) with mock_open ?有没有办法将read(some_number_of_bytes)mock_open一起mock_open

mock_open works as expected when reading the entire file ( read() ) or when reading a single line ( readline() ), but I can't get it working when reading a number of bytes ( read(n) ) mock_open在读取整个文件 ( read() ) 或读取单行 ( readline() ) 时按预期工作,但在读取多个字节 ( read(n) ) 时无法正常工作

These snippets (adapted from the Mock documentation ) work (Python 2.7):这些片段(改编自Mock 文档)有效(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

But trying to read only a few bytes fails-- mock_open returns the entire read_data instead:但是尝试只读取几个字节失败了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

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

In case this is an XY problem, I'll note that the reason for this question is that I'm mocking a file that I pass into pickle.load , which in turn calls read(1) .如果这是一个 XY 问题,我会注意到这个问题的原因是我在pickle.load一个传递给pickle.load的文件,它反过来调用read(1)

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

I'd prefer to mock the lowest level possible ( open rather than pickle.load ).我更愿意模拟尽可能低的级别( open而不是pickle.load )。

作为记录,此问题已在 Python 3.7 中修复

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM