[TIP] Return value of a read-only attribute only settable via 'return_value' kwarg

Balthazar Rouberol rouberol.b at gmail.com
Tue Apr 30 05:38:15 PDT 2013


Hello all,

I wanted to mock an class read only property (which only does some I/O with
mongoDB) by setting its return_value in an entire unittest.TestCase scope.

What I first tried was defining a patch in the classSetUp classmethod, then
call its .start() method, and its .stop() method in tearDownClass.

@classmethod
def setUpClass(cls):
    # patch the Dataminer.blacklisted_domains so that it does not
    # communicate with the database
    cls.black_patch = mock.patch.object(
       Dataminer,
       'blacklisted_domains',
       new_callable=mock.PropertyMock
    )
    cls.black_patch.return_value = ['some', 'manual', 'test', 'value']
    cls.black_patch.start()

@classmethod
def tearDownClass(cls):
    cls.black_patch.stop()


However, when I called the Dataminer.blacklisted_domains property later in
a test, it returned <MagicMock name='blacklisted_domains()' id='34773392'>,
and not the value I defined.

What worked for me was passing the return_value as a kwarg to patch.object:

@classmethod
    def setUpClass(cls):
        # patch the Dataminer.blacklisted_domains so that it does not
        # communicate with the database
        cls.black_patch = mock.patch.object(
            Dataminer,
            'blacklisted_domains',
            new_callable=mock.PropertyMock,
            **{'return_value': ['some', 'manual', 'test', 'value']}
        )
        cls.black_patch.start()

    @classmethod
    def tearDownClass(cls):
        cls.black_patch.stop()


With this method, the return value of the blacklisted_domains property of
my Dataminer instance was what I defined in the classSetUp.

Could anyone walk me through the differences between these two methods, as
it's not really clear to me why the first would fail when the second would
work..

Thank you very much!
--
Balthazar Rouberol
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20130430/323b98fa/attachment.html>


More information about the testing-in-python mailing list