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

Michael Foord fuzzyman at voidspace.org.uk
Sun Sep 6 17:32:44 PDT 2009


Matthew Wilson wrote:
> 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 important thing with patching is that you patch the namespace *where 
the object is used* and not where it is defined. If your first example 
code (that does the import) is in a foo module then you should patch 
like this:

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


All the best,

Michael

> 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
>
>
>   


-- 
http://www.ironpythoninaction.com/
http://www.voidspace.org.uk/blog





More information about the testing-in-python mailing list