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

Ronny Pfannschmidt Ronny.Pfannschmidt at gmx.de
Thu Aug 2 23:09:04 PDT 2012


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
> http://lists.idyll.org/listinfo/testing-in-python




More information about the testing-in-python mailing list