[TIP] [mock] Mocking referenced methods?

Tom Davis tom at recursivedream.com
Mon Oct 3 12:14:30 PDT 2011


First off, sorry for the vague term "referenced methods"; I don't know the
proper term for this. Basically, I cannot seem to mock a class method by
name if it is being called as a reference from another attribute. If that
still makes no sense, here's an example:

import mock


class Foo(object):
    def meth(self):
        return True

    STUFF = ((meth, True),)

    def do(self):
        for m, r in self.STUFF:
            assert m(self) == r

f = Foo()

f.do()

with mock.patch.object(f, 'meth') as meth:
    f.do()
    assert meth.called

with mock.patch('__main__.Foo.meth') as meth:
    f.do()
    assert meth.called


This example is a bit contrived, but should get the point across. I believe
I understand why the former doesn't work (I need to explicitly call "meth"
with "self", thus it isn't an instance attribute), but I don't understand
why the latter doesn't work, either...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20111003/85458843/attachment.htm>


More information about the testing-in-python mailing list