4

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?

2 Answers 2

2

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

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.