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

Ned Batchelder ned at nedbatchelder.com
Tue Jul 26 02:57:37 PDT 2011


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
>



More information about the testing-in-python mailing list