简体   繁体   English

在Python中模拟导入的模块

[英]Mocking imported modules in Python

I'm trying to implement unit tests for function that uses imported external objects. 我正在尝试为使用导入的外部对象的函数实现单元测试。

For example helpers.py is: 例如helpers.py是:

import os
import pylons

def some_func(arg):
   ...
   var1 = os.path.exist(...)
   var2 = os.path.getmtime(...)
   var3 = pylons.request.environ['HTTP_HOST']
   ...

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: 因此,当我为它创建单元测试时,我会做一些模拟(在我的情况下为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
    ...

This does not look good for me. 这对我来说不太好看。

Is there any other better way or strategy to substitute imported function/objects in Python? 是否还有其他更好的方法或策略来替换Python中导入的函数/对象?

Use voidspace's mocking library and it's patching/wrapping ability. 使用voidspace的模拟库和它的修补/包装能力。

http://www.voidspace.org.uk/python/mock/patch.html http://www.voidspace.org.uk/python/mock/patch.html

Well, in minimock there is an easier paradigm for this than what you are using above: 好吧,在minimock中,有一个比你上面使用的更简单的范例:

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

See http://pypi.python.org/pypi/MiniMock#creating-mocks 请参见http://pypi.python.org/pypi/MiniMock#creating-mocks

Once you do that, any module that does os.path.isfile("blah") is going to get True back. 一旦你这样做,任何执行os.path.isfile("blah")模块都将返回True You don't need to go and explicitly reassign the module-under-test's namespace. 您无需明确重新分配测试模块的命名空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM