我有一个 python 方法执行以下操作:
- 使用 os.listdir(/test) 列出目录下的文件
- 正则表达式匹配目录下的一些文件,将这些文件放在一个列表中
- 从列表中的文件中读取内容,做一些聚合工作。
显然,我要测试的唯一有趣部分是 2、3,所以 1 绝对是我想要模拟的东西。我开始在我的 setUp() 和 tearDown() 中的/test 文件夹下创建/删除补丁文件。但是同事告诉我在 unitest 中做 I/O 不是个好主意。
那么在我的 unitest 中模拟 os.listdir() 构建的最佳方法是什么?或者有什么选择?
我能做些什么来实现这样的目标:
setUp() {
#mock a few files eg.test1.txt, test2.txt, test3.txt under directory /test
#without physically creating them using I/O
}
tearDown() {
#whatever cleanup required
}
最佳答案
使用 Mock 模块怎么样?
>>> import os
>>> from mock import MagicMock
>>> os.listdir = MagicMock(return_value=['file1.txt', 'file2.txt', 'file3.txt'])
>>> os.listdir('./test')
['file1.txt', 'file2.txt', 'file3.txt']
如果您不想对 os 进行 mokey-patch(即中断),那么您可以使用 mock_os 或类似的东西。
阅读有关启动和停止的信息:
http://docs.python.org/dev/py3k/library/unittest.mock.html#patch-methods-start-and-stop
并且:
http://docs.python.org/dev/py3k/library/unittest.mock.html#quick-guide
关于python - 如何在方法中模拟 python 构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10820545/