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

John Wong gokoproject at gmail.com
Thu Aug 2 22:20:05 PDT 2012

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


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20120803/18bb386a/attachment.htm>

More information about the testing-in-python mailing list