问题描述
是否有标准方法(无需安装第三方库)在 Python 中进行跨平台文件系统模拟?如果我必须使用第三方库,哪个库是标准的?
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) 做你想做的事——一个假文件系统;它是第三方,尽管该方是 Google.请参阅如何替换文件访问引用被测模块用于讨论使用.
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.
对于模拟,unittest.mock 是 Python 3.3+ 的标准库(PEP 0417);对于早期版本,请参阅 PyPI: mock(对于 Python 2.5+)(主页).
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).
测试和模拟中的术语不一致;使用 Gerard Meszaros 的 Test Double 术语,您要求的是假货":行为类似于文件系统(您可以创建、打开和删除文件),但不是实际的文件系统(在这种情况下它在内存中),因此您不需要有测试文件或临时目录.
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.
在经典模拟中,您会模拟系统调用(在 Python 中,模拟 os
模块中的函数,例如 os.rm
和 os.listdir
),但这要繁琐得多.
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 单元测试中模拟文件系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!