[TIP] How do I mock/patch a function imported from a module?

Matthew Wilson matt at tplus1.com
Sun Sep 6 17:28:22 PDT 2009


I'm using Mock (http://www.voidspace.org.uk/python/mock/index.html)
and I want to substitute a mock object for the send_through_pager
function in the code below:

from clepy import send_through_pager

def foo():
    send_through_pager("abcdef")


So I tried this, but it doesn't seem to do anything:

@patch("clepy.send_through_pager")
def test_foo(m1)
    foo()


The original send_through_pager function still gets called.

I can rewrite foo to look like this:

import clepy

def foo():
    clepy.send_through_pager("abcdef")

And then the patching works exactly right.

But I don't want to rewrite my code unless I have to.  Do I have to?


Matt


-- 
W. Matthew Wilson
matt at tplus1.com
http://tplus1.com



More information about the testing-in-python mailing list