小编use*_*703的帖子

在 python 中模拟 zipfile

我正在尝试使用 Python 模拟库来模拟 zipfile 模块的一些方法。

我想测试的示例源:

def zipStuff(listOfPathToFiles):
    with ZipFile(fName, 'w') as archive:
        for each in listOfPathToFiles:
             archive.write(each, strippedfName)
    return archive
Run Code Online (Sandbox Code Playgroud)

正常执行时上面的“存档”将被忽略,但在测试期间将是文件列表。

单元测试代码示例:

emptyList=[]

def mockWrite(fName):
    emptyList.append(fName)
    return

mockZip.__enter__ = Mock(return_value=emptyList)
mockZip.__exit__ = Mock(return_value=True)
Run Code Online (Sandbox Code Playgroud)

现在,我想模拟 archive.write,以便将其替换为 mockWrite 函数,而不是实际的写入调用,这样我就可以获得应该压缩的所有文件的列表。

我试过了:

mockZip.write = Mock(side_effect=mockWrite)
Run Code Online (Sandbox Code Playgroud)

但这并没有被调用。调试显示该函数正在调用mockZip。输入().write。如果我尝试:

mockZip.__enter__().write = Mock(side_effect=mockWrite)
Run Code Online (Sandbox Code Playgroud)

Python 发出“list”没有属性 write 的错误(这是正确的)。我是 Mock 和 Python 的新手,非常感谢任何指点。建议?

python unit-testing python-mock

2
推荐指数
1
解决办法
4144
查看次数

标签 统计

python ×1

python-mock ×1

unit-testing ×1