[openstack-dev] [cinder] How to make a mock effactive for all method of a testclass

Gorka Eguileor geguileo at redhat.com
Thu Sep 24 14:11:26 UTC 2015


On 23/09, Eric Harney wrote:
> On 09/23/2015 04:06 AM, liuxinguo wrote:
> > Hi,
> > 
> > In a.py we have a function:
> > def _change_file_mode(filepath):
> > utils.execute('chmod', '600', filepath, run_as_root=True)
> > 
> > In test_xxx.py, there is a testclass:
> > class xxxxDriverTestCase(test.TestCase):
> > def test_a(self)
> >     ...
> >     Call a. _change_file_mode
> > ...
> > 
> > def test_b(self)
> >     ...
> >     Call a. _change_file_mode
> > ...
> > 
> > I have tried to mock like mock out function _change_file_mode like this:
> > @mock.patch.object(a, '_change_file_mode', return_value=None)
> > class xxxxDriverTestCase(test.TestCase):
> > def test_a(self)
> >     ...
> >     Call a. _change_file_mode
> > ...
> > 
> > def test_b(self)
> >     ...
> >     Call a. _change_file_mode
> > ...
> > 
> > But the mock takes no effort, the real function _change_file_mode is still executed.
> > So how to make a mock effactive for all method of a testclass?
> > Thanks for any input!
> > 
> > Wilson Liu
> 
> The simplest way I found to do this was to use mock.patch in the test
> class's setUp() method, and tear it down again in tearDown().
> 
> There may be cleaner ways to do this with tools in oslotest etc. (I'm
> not sure), but this is fairly straightforward.
> 
> See here -- self._clear_patch stores the mock:
> http://git.openstack.org/cgit/openstack/cinder/tree/cinder/tests/unit/test_volume.py?id=8de60a8b#n257
> 

When doing the mock in the setUp it is recommended to add the stop to
the cleanup instead of doing it in the tearDown, in that code it would
be: self.addCleanUp(self._clear_patch.stop)



More information about the OpenStack-dev mailing list