Matthew Treinish | 9e26ca8 | 2016-02-23 11:43:20 -0500 | [diff] [blame] | 1 | # 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 | |
| 15 | import mock |
| 16 | from oslotest import base |
Matthew Treinish | 9e26ca8 | 2016-02-23 11:43:20 -0500 | [diff] [blame] | 17 | |
| 18 | |
| 19 | class TestCase(base.BaseTestCase): |
| 20 | |
Matthew Treinish | 9e26ca8 | 2016-02-23 11:43:20 -0500 | [diff] [blame] | 21 | 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 Pittier | 0021c29 | 2016-03-29 21:33:34 +0200 | [diff] [blame] | 38 | |
| 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 |