Python 使用大小变量的模拟文件读取方法
我正在尝试使用python模拟库模拟一个文件。虽然足够简单,但我仍然不理解当read函数必须接收size参数时如何模拟它。我试图使用副作用创建一个替代函数,该函数将读取作为值传递的足够数据 这就是想法:Python 使用大小变量的模拟文件读取方法,python,mocking,python-mock,Python,Mocking,Python Mock,我正在尝试使用python模拟库模拟一个文件。虽然足够简单,但我仍然不理解当read函数必须接收size参数时如何模拟它。我试图使用副作用创建一个替代函数,该函数将读取作为值传递的足够数据 这就是想法: def mock_read(value): test_string = "abcdefghijklmnopqrs" ''' Now it should read enough values from the test string, but I haven
def mock_read(value):
test_string = "abcdefghijklmnopqrs"
'''
Now it should read enough values from the test string, but
I haven't figured out a way to store the position where the
"read" method has stopped.
'''
mock_file = MagicMock(spec=file)
mock_file.read.side_effect = mock_read
但是,我还没有弄清楚如何在side_effect函数中存储读卡器的当前位置,以便在这之后读取。我认为可能有更好的方法,但我仍然找到了它。不幸的是,它不支持部分读取,而且您使用python 2.7(我假设它是因为您编写了MagicMock(spec=file)
)和mock\u open
非常有限
我们可以概括你的问题,就像我们能写出能保持状态的副作用一样。在python中有一些方法可以做到这一点,但最简单的方法是使用一个类来实现\uu调用\uu
(这里不能使用生成器,因为mock
像解释副作用列表一样解释生成器):
此外,我们可以将该实现注入mock\u open
处理程序中,以修补mock\u open.read()
方法
from mock patch, mock_open
with patch("__builtin__.open", new_callable=mock_open) as mo:
mock_file = mo.return_value
mock_file.read.side_effect = my_read_side_effect("abcdefghijklmnopqrs")
assert "abcdef" == mock_file.read(6)
assert "ghijklm" == mock_file.read(7)
assert "nopqrs" == mock_file.read()
这为您提供了一种在测试中使用它的简单方法,其中文件在函数中打开,而不是作为参数传递。对不起,我没有很好地阅读您的问题。。。。我改变了我的答案,现在它涵盖了你的问题。你还对这个话题感兴趣吗?是的,谢谢你的回答,它解决了我的问题。我试图创建BytesIO对象,并将模拟对象的read方法指向BytesIO对象的read方法,但是您的答案提供了更好的方法。
from mock patch, mock_open
with patch("__builtin__.open", new_callable=mock_open) as mo:
mock_file = mo.return_value
mock_file.read.side_effect = my_read_side_effect("abcdefghijklmnopqrs")
assert "abcdef" == mock_file.read(6)
assert "ghijklm" == mock_file.read(7)
assert "nopqrs" == mock_file.read()