在Python中模拟导入的模块 [英] Mocking imported modules in Python

查看:97
本文介绍了在Python中模拟导入的模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对使用导入的外部对象的功能实施单元测试.

I'm trying to implement unit tests for function that uses imported external objects.

例如 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的引用:

So when I'm creating unit test for it I do some mocking (minimock in my case) and replacing references to pylons.request and 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中导入的函数/对象吗?

Is there any other better way or strategy to substitute imported function/objects in Python?

推荐答案

好吧,在minimock中,有一个比上面使用的更简单的范例:

Well, in minimock there is an easier paradigm for this than what you are using above:

>>> from minimock import mock
>>> import os.path
>>> mock('os.path.isfile', returns=True)

请参见 http://pypi.python.org/pypi/MiniMock#creating-模拟

完成此操作后,执行os.path.isfile("blah")的任何模块都将收回True.您无需去明确地重新分配被测模块的名称空间.

Once you do that, any module that does os.path.isfile("blah") is going to get True back. You don't need to go and explicitly reassign the module-under-test's namespace.

这篇关于在Python中模拟导入的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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