views:

218

answers:

3

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?

A: 

I think you could look to different mock object libraries here: http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy I never used mock objects, only nose, sorry.

Dmitry Kochkin
+1  A: 

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

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

Almad
+1  A: 

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.

Peter Lyons