Alex Rivera | Logout

Mocking Functions Using Python Mock

Asked 2011-03-12T23:43:12.523
114

I am trying to Mock a function (that returns some external content) using the python mock module.

I'm having some trouble mocking functions that are imported into a module.

For example, in util.py I have

def get_content():
  return "stuff"

I want to mock util.get_content so that it returns something else.

I am trying this:

util.get_content=Mock(return_value="mocked stuff")

If get_content gets invoked inside another module, it never actually seems to return the mocked object. Am I missing something in terms of how to use Mock?

Note that if I invoke the following, things work correctly:

>>> util.get_content=Mock(return_value="mocked stuff")
>>> util.get_content()
"mocked stuff"

However, if get_content is called from inside another module, it invokes the original function instead of the mocked version:

>>> from mymodule import MyObj
>>> util.get_content=Mock(return_value="mocked stuff")
>>> m=MyObj()
>>> m.func()
"stuff"

Contents of mymodule.py

from util import get_content

class MyObj:    
    def func():
        get_content()

So I guess my question is - how do I get invoke the Mocked version of a function from inside a module that I call?

It appears that the from module import function may be to blame here, in that it doesn't point to the Mocked function.

Edit
Report

1 Answer

29

You have to patch the function where it is being used. In your case that would be in the mymodule module.

import mymodule
>>> mymodule.get_content = Mock(return_value="mocked stuff")
>>> m = mymodule.MyObj()
>>> m.func()
"mocked stuff"

There is a reference in the docs here: http://docs.python.org/dev/library/unittest.mock.html#where-to-patch

answered 2013-05-22T14:07:01.820

Your Answer