我如何模拟ZipFile构造函数?

时间:2017-12-01 11:27:34

标签: python unit-testing

我试图测试此代码:

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'

1 个答案:

答案 0 :(得分:0)

直截了当:

@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')