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

Matthew Wilson matt at tplus1.com
Sun Sep 6 17:39:13 PDT 2009


On Sun, Sep 6, 2009 at 8:32 PM, Michael Foord<fuzzyman at voidspace.org.uk> wrote:
> 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()
>

Just tried that out, and it works fine.  Thanks!



More information about the testing-in-python mailing list