gpt4 book ai didi

python - 如何模拟 ZipFile 构造函数?

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:42 24 4
gpt4 key购买 nike

我正在尝试测试此代码:

def read_classes(file):
if CLASSES in file:
classes = open(file, "rb").read()
else:
with ZipFile(file, "r") as archive:
classes = archive.read(CLASSES)
return classes

对我来说重要的是,当提供的文件包含 CLASSES 时以它的名字,open将被调用,否则,ZipFile将会被使用。我已经能够测试第一部分,但是,我无法模拟 ZipFile为了返回一个模拟对象( archive ) - 然后我可以断言它具有 read方法调用。这是我到目前为止一直在尝试的:

@patch('zipfile.ZipFile')
def test_givenFile_whenReadClasses_expectArchiveCalled(self, mock_zipfile):
file = 'sample.file'
archive = Mock()
mock_zipfile.return_value = archive

read_classes(file)

archive.read.assert_called_once_with("classes.file")

当我这样做时,它会继续执行原始的 ZipFile构造函数,给我: IOError: [Errno 2] No such file or directory: 'sample.file'

最佳答案

开门见山:

@patch('zipfile.ZipFile')
def test_givenFile_whenReadClasses_expectArchiveCalled(self, mocked_zip_file):
file = 'file'
archive = Mock()
mocked_read = Mock()
archive.return_value.read = mocked_read
mocked_zip_file.return_value.__enter__ = archive

read_classes(dex_file)

mocked_read.assert_called_once_with('another_file')

关于python - 如何模拟 ZipFile 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47592395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com