<div dir="ltr"><div><div>Hello all,<br><br></div>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.<br><br>What I first tried was defining a patch in the classSetUp classmethod, then call its .start() method, and its .stop() method in tearDownClass.<br>

<br>@classmethod<br>def setUpClass(cls):<br>    # patch the Dataminer.blacklisted_domains so that it does not<br>    # communicate with the database<br>    cls.black_patch = mock.patch.object(<br>       Dataminer,<br>       &#39;blacklisted_domains&#39;,<br>

       new_callable=mock.PropertyMock<br>    )<br></div>    cls.black_patch.return_value = [&#39;some&#39;, &#39;manual&#39;, &#39;test&#39;, &#39;value&#39;]<br><div>    cls.black_patch.start()<br><br>@classmethod<br>def tearDownClass(cls):<br>

    cls.black_patch.stop()<br><br></div><div><br></div><div>However, when I called the Dataminer.blacklisted_domains property later in a test, it returned &lt;MagicMock name=&#39;blacklisted_domains()&#39; id=&#39;34773392&#39;&gt;, and not the value I defined.<br>

<br></div><div>What worked for me was passing the return_value as a kwarg to patch.object:<br><br>@classmethod<br>    def setUpClass(cls):<br>        # patch the Dataminer.blacklisted_domains so that it does not<br>        # communicate with the database<br>

        cls.black_patch = mock.patch.object(<br>            Dataminer,<br>            &#39;blacklisted_domains&#39;,<br>            new_callable=mock.PropertyMock,<br></div><div>            **{&#39;return_value&#39;: [&#39;some&#39;, &#39;manual&#39;, &#39;test&#39;, &#39;value&#39;]}</div>

<div>        )<br>        cls.black_patch.start()<br><br>    @classmethod<br>    def tearDownClass(cls):<br>        cls.black_patch.stop()<br><br><br></div><div>With this method, the return value of the blacklisted_domains property of my Dataminer instance was what I defined in the classSetUp.<br>

<br></div><div>Could anyone walk me through the differences between these two methods, as it&#39;s not really clear to me why the first would fail when the second would work..<br></div><div><br>Thank you very much!<br>--<br>

</div><div>Balthazar Rouberol<br></div></div>