[TIP] [mock] Mocking referenced methods?

Gary Bernhardt gary.bernhardt at gmail.com
Mon Oct 3 13:19:59 PDT 2011


You can also try to figure out what the tests are telling you. :)
Maybe the STUFF dispatch table and the methods that do the work can be
in separate classes, tested separately?

--
Gary
http://destroyallsoftware.com



On Mon, Oct 3, 2011 at 1:17 PM, Tom Davis <tom at recursivedream.com> wrote:
>
>
> On Mon, Oct 3, 2011 at 4:10 PM, Gary Bernhardt <gary.bernhardt at gmail.com>
> wrote:
>>
>> 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.
>
> Right, I was thinking over that and the only thing I can really do, then, is
> to instantiate Foo(), change the inner stuff to lists, and then manually
> replace foo.STUFF[0][0] with a mock object? That just seems extra ugly.
>
>>
>> --
>> 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