python - 在 python 中模拟 zipfile

标签 python unit-testing python-mock

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

我要测试的示例源:

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

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

示例单元测试代码:

emptyList=[]

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

mockZip.__enter__ = Mock(return_value=emptyList)
mockZip.__exit__ = Mock(return_value=True)

现在,我想模拟 archive.write,这样它就被 mockWrite 函数取代,而不是实际的 write 调用,这样我就可以获得所有应该被压缩的文件的列表。

我试过:

mockZip.write = Mock(side_effect=mockWrite)

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

mockZip.__enter__().write = Mock(side_effect=mockWrite)

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

最佳答案

与其让 mockZip.__enter__ 返回一个空列表,不如让它返回一个如下所示的对象:

class MockZipFile:
    def __init__(self):
        self.files = []
    def __iter__(self):
        return iter(self.files)
    def write(self, fname):
        self.files.append(fname)

您可以根据需要添加方法和实现以满足您的模拟需求。

关于python - 在 python 中模拟 zipfile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31412214/

相关文章:

security - 在企业 bean 中使用 getUserPrincipal() 和 isCallerInRole() 方法时如何编写 JUnit 测试?

python - 内部函数中模拟默认参数值

python - 在 pandas 中按组替换列/系列

python - 将基于 uWSGI 的 Django 网络应用程序转换为基于 gunicorn 的应用程序

iphone - 无法在单元测试中设置 NSMutableDictionary 中的值

c# - 即使有 DoNotCallBase,Nsubstitute 在 When 中调用方法

python - 继承一个补丁类

python - 模拟函数参数名称以与 inspect.getargspec 一起使用

python - 为什么 SQLAlchemy 不更新 Flask WSGI 服务器中的行值?

python - 防止在 __init__ 之外创建新属性