[TIP] Mocking chain attribute returns MagicMock instead of the return_value

John Wong gokoproject at gmail.com
Fri Aug 3 08:30:57 PDT 2012


Thanks.
I made a mistake when copying the code. I was mocking `DBSession` instead
of `MyModel`. But like your example showed, when I called
self.mk.query().first.return_value it will give the return value. I am
guessing this is because queyr is a callable, and making
self.mk.query.first is like accessing a non-callable attribute.

Thank you.
John

On Fri, Aug 3, 2012 at 2:09 AM, Ronny Pfannschmidt <
Ronny.Pfannschmidt at gmx.de> wrote:

> Hi John,
>
> you are mocking the first attribute of the query method
> you want to mock the first attribute of a call result of the query method
>
> >>> m = mock.Mock()
> >>> m.method.x.return_value = 1
> >>> m.method().x.return_value = 2
> >>> m.method().x
> <Mock name='mock.method().x' id='24232272'>
> >>> m.method().x()
> 2
> >>> m.method.x()
> 1
>
>
> -- Ronny
>
>
> On 08/03/2012 07:20 AM, John Wong wrote:
>
>> Suppose I have this views function:
>>
>>      res = DBSession.query(MyModel).**first()
>>          return {'result': res}
>>
>> I want to use mock to write my unittest
>>
>>      def setUp(self):
>>          # I am setting up a global patch (Don't Repeat Yourself)
>>          self.p1 = patch('pyramid_app.views.**MyModel')
>>          self.mk1 = self.p1.start()
>>          self.mk1.query.first.return_**value = 'abc'
>>
>>
>>      def test(self):
>>          r = my_view(Request)
>>          self.assertEqual({'result': 'abc'}, r)
>>
>>
>> But the actual return is:
>>
>>      AssertionError: { 'result': 'abc'} != {'result': <MagicMock
>> name='DBSession.query().first(**)' id='185999084'>}
>>
>> But I already set the return_value on the mock object, why do I still
>> get the instance of the MagicMock and not the return_value?
>> I can, of course, access the `return_value`, but that is not a solution
>> at all.
>>
>>
>> Thanks.
>>
>> John
>>
>>
>> ______________________________**_________________
>> testing-in-python mailing list
>> testing-in-python at lists.idyll.**org <testing-in-python at lists.idyll.org>
>> http://lists.idyll.org/**listinfo/testing-in-python<http://lists.idyll.org/listinfo/testing-in-python>
>>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20120803/dcb6b425/attachment.htm>


More information about the testing-in-python mailing list