<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> 'blacklisted_domains',<br>
new_callable=mock.PropertyMock<br> )<br></div> cls.black_patch.return_value = ['some', 'manual', 'test', 'value']<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 <MagicMock name='blacklisted_domains()' id='34773392'>, 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> 'blacklisted_domains',<br> new_callable=mock.PropertyMock,<br></div><div> **{'return_value': ['some', 'manual', 'test', 'value']}</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'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>