如何在Python单元测试中模拟文件系统? [英] How do I mock the filesystem in Python unit tests?

查看:227
本文介绍了如何在Python单元测试中模拟文件系统?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在使用Python进行跨平台文件系统模拟的标准方法(无需安装第三方库)?如果我必须使用第三方库,那么哪个库是标准库?

解决方案

pyfakefs (首页)可以满足您的要求-一个 fake 文件系统;它是第三方,尽管该第三方是Google.请参阅如何替换文件访问引用测试中的模块以讨论使用情况.

对于模拟 unittest.mock 是适用于Python 3.3+的标准库( PEP 0417 );对于早期版本,请参见 PyPI:模拟(适用于Python 2.5 +)(测试Double 术语,您要的是假"东西:行为类似于文件系统(可以创建,打开和删除文件),但不是实际的文件系统(在这种情况下,它在内存中),因此不需要测试文件或临时目录. /p>

在经典的模拟中,您可以 mock 退出系统调用(在Python中,模拟os模块中的函数,例如os.rmos.listdir),但这要多得多乖乖地

Is there a standard way (without installing third party libraries) to do cross platform filesystem mocking in Python? If I have to go with a third party library, which library is the standard?

解决方案

pyfakefs (homepage) does what you want – a fake filesystem; it’s third-party, though that party is Google. See How to replace file-access references for a module under test for discussion of use.

For mocking, unittest.mock is the standard library for Python 3.3+ (PEP 0417); for earlier version see PyPI: mock (for Python 2.5+) (homepage).

Terminology in testing and mocking is inconsistent; using the Test Double terminology of Gerard Meszaros, you’re asking for a "fake": something that behaves like a filesystem (you can create, open, and delete files), but isn’t the actual file system (in this case it’s in-memory), so you don’t need to have test files or a temporary directory.

In classic mocking, you would instead mock out the system calls (in Python, mock out functions in the os module, like os.rm and os.listdir), but that’s much more fiddly.

这篇关于如何在Python单元测试中模拟文件系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆