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

Gorka Eguileor geguileo at redhat.com
Wed Sep 23 08:25:50 UTC 2015


On 23/09, 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

> __________________________________________________________________________
> OpenStack Development Mailing List (not for usage questions)
> Unsubscribe: OpenStack-dev-request at lists.openstack.org?subject:unsubscribe
> http://lists.openstack.org/cgi-bin/mailman/listinfo/openstack-dev

Hi,

There is something else going on with your code, as the code you are
showing us here should not even execute at all.  You should be getting a
couple of errors:

 TypeError: test_a() takes exactly 1 argument (2 given)
 TypeError: test_b() takes exactly 1 argument (2 given)

Because mocking the whole class will still pass the mock object as an
argument to the methods.

Anyway, if you accept the mocked object as an argument in your test
methods it would work.

Cheers,
Gorka.



More information about the OpenStack-dev mailing list