[TIP] [mock] Mocking referenced methods?
Gary Bernhardt
gary.bernhardt at gmail.com
Mon Oct 3 13:10:38 PDT 2011
STUFF is created at class definition time, before your patches are
run. The patches are successfully patching the method, but STUFF
already holds a reference to the original, so that's what's getting
called.
--
Gary
http://destroyallsoftware.com
On Mon, Oct 3, 2011 at 12:14 PM, Tom Davis <tom at recursivedream.com> wrote:
> 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...
> _______________________________________________
> 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