blob: ca81d4d605cf40514fb819780a349ce586c0fccb [file] [log] [blame]
Matthew Treinish9e26ca82016-02-23 11:43:20 -05001# Copyright 2013 IBM Corp.
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may
4# not use this file except in compliance with the License. You may obtain
5# a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations
13# under the License.
14
15import mock
16from oslotest import base
Matthew Treinish9e26ca82016-02-23 11:43:20 -050017
18
19class TestCase(base.BaseTestCase):
20
Matthew Treinish9e26ca82016-02-23 11:43:20 -050021 def patch(self, target, **kwargs):
22 """Returns a started `mock.patch` object for the supplied target.
23
24 The caller may then call the returned patcher to create a mock object.
25
26 The caller does not need to call stop() on the returned
27 patcher object, as this method automatically adds a cleanup
28 to the test class to stop the patcher.
29
30 :param target: String module.class or module.object expression to patch
31 :param **kwargs: Passed as-is to `mock.patch`. See mock documentation
32 for details.
33 """
34 p = mock.patch(target, **kwargs)
35 m = p.start()
36 self.addCleanup(p.stop)
37 return m
Jordan Pittier0021c292016-03-29 21:33:34 +020038
39 def patchobject(self, target, attribute, new=mock.DEFAULT):
40 """Convenient wrapper around `mock.patch.object`
41
42 Returns a started mock that will be automatically stopped after the
43 test ran.
44 """
45
46 p = mock.patch.object(target, attribute, new)
47 m = p.start()
48 self.addCleanup(p.stop)
49 return m