[TIP] Unit testing, patching a function in a module...

Robert Madole robmadole at gmail.com
Tue Jul 26 06:42:15 PDT 2011


Instead of mocking the utility object itself, you can mock the module that uses it.

So this:

  with patch.object(utility, 'download', self.my_download_patch):

Becomes this:

  with patch.object('module.code_to_test.download', self.my_download_patch):

This may not make a lot of sense. Check out this page from the Mock documenation, it does a better job of explaining:

http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch

Rob

On Jul 26, 2011, at 4:57 AM, Ned Batchelder wrote:

> This is a natural outcome of how Python's modules and import work.  In your first code, you create the name "download" in your module, giving it the same value as the name "download" in the utility module.  Then with mock, you change the value of the name utility.download.  This doesn't change the value of your name "download".    In the second example, your code uses the name "utility.download" at run time, so when you use mock to change "utility.download", your code sees the mocked value.
> 
> --Ned.
> 
> On 7/25/2011 8:35 PM, Jacocks, Jeremy wrote:
>> Hello all,
>> 
>> I'm writing some unit tests and I have a question about mock, and patching functions in a module.  The function I want to patch is being imported and used in another module.  It seems that unless I import the entire module (containing the function I patched), and reference the (patched) function explicitly, the patch doesn't work.. here is an example of what I mean....
>> 
>> from my.packages.utility import download
>> 
>> class ToBeTested(object):
>> 
>>     [....]
>> 
>>     def __call__(self):
>>         download()
>> 
>> ## new file, new module ##
>> 
>> [....]
>> from my.packages import utility
>> 
>> class ToBeTested_test(TestCase):
>> 
>>     [....]
>> 
>>     def call_test(self):
>>         with patch.object(utility, 'download', self.my_download_patch):
>>             obj = ToBeTested()
>>             obj.__call__()                ## this is using my.packages.utility.download, not my patch
>> 
>> 
>> However, if the implementation of ToBeTested looks like this, the patch in the test works.....
>> 
>> from my.packages import utility
>> 
>> class ToBeTested(object):
>> 
>>     [....]
>> 
>>     def __call__(self):
>>         utility.download()
>> 
>> 
>> Is this the expected behavior?
>> 
>> Thanks,
>> 
>> Jeremy Jacocks
>> 
>> _______________________________________________
>> testing-in-python mailing list
>> testing-in-python at lists.idyll.org
>> http://lists.idyll.org/listinfo/testing-in-python
>> 
> 
> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://lists.idyll.org/listinfo/testing-in-python




More information about the testing-in-python mailing list