开发者

Mocking imported modules in Python

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

For example helpers.py is:

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:

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?


Use voidspace's mocking library and it's patching/wrapping ability.

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:

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

See 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. You don't need to go and explicitly reassign the module-under-test's namespace.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜