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

Jacocks, Jeremy jjacocks at cars.com
Mon Jul 25 17:35:41 PDT 2011


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



More information about the testing-in-python mailing list