Mocking imported modules in Python

Posted by Evgenyt on Stack Overflow See other posts from Stack Overflow or by Evgenyt
Published on 2010-02-27T19:49:24Z Indexed on 2010/03/12 4:27 UTC
Read the original article Hit count: 256

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about unit-testing

Related posts about python