在Python中模拟导入模块
我正在尝试为一个使用外部导入对象的函数编写单元测试。
比如说,helpers.py 文件是:
import os
import pylons
def some_func(arg):
...
var1 = os.path.exist(...)
var2 = os.path.getmtime(...)
var3 = pylons.request.environ['HTTP_HOST']
...
所以当我为它创建单元测试时,我会进行一些模拟(在我的情况下是使用minimock),并替换对pylons.request和os.path的引用:
import helpers
def test_some_func():
helpers.pylons.request = minimock.Mock("pylons.request")
helpers.pylons.request.environ = { 'HTTP_HOST': "localhost" }
helpers.os.path = minimock.Mock(....)
...
some_func(...)
# assert
...
这样做我觉得不太好。
有没有其他更好的方法或策略来替代Python中的导入函数/对象呢?
2 个回答
2
使用voidspace的模拟库,它有很好的修补和包装功能。
1
在minimock中,有一种比你上面使用的方法更简单的方式:
>>> from minimock import mock
>>> import os.path
>>> mock('os.path.isfile', returns=True)
你可以查看这个链接了解更多:http://pypi.python.org/pypi/MiniMock#creating-mocks
一旦你这样做了,任何调用 os.path.isfile("blah")
的模块都会返回 True
。你不需要去手动重新分配被测试模块的命名空间。