Matthew Treinish | 8708621 | 2013-10-28 20:21:54 +0000 | [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 os |
| 16 | |
| 17 | import fixtures |
Jay Pipes | 8fe5392 | 2014-01-14 20:08:16 -0500 | [diff] [blame] | 18 | import mock |
Matthew Treinish | 8708621 | 2013-10-28 20:21:54 +0000 | [diff] [blame] | 19 | import testtools |
| 20 | |
Matthew Treinish | dde9d0a | 2013-10-31 18:26:52 -0400 | [diff] [blame] | 21 | from tempest.openstack.common.fixture import moxstubout |
Matthew Treinish | 8708621 | 2013-10-28 20:21:54 +0000 | [diff] [blame] | 22 | |
| 23 | |
| 24 | class TestCase(testtools.TestCase): |
| 25 | |
| 26 | def setUp(self): |
| 27 | super(TestCase, self).setUp() |
| 28 | if (os.environ.get('OS_STDOUT_CAPTURE') == 'True' or |
| 29 | os.environ.get('OS_STDOUT_CAPTURE') == '1'): |
| 30 | stdout = self.useFixture(fixtures.StringStream('stdout')).stream |
| 31 | self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) |
| 32 | if (os.environ.get('OS_STDERR_CAPTURE') == 'True' or |
| 33 | os.environ.get('OS_STDERR_CAPTURE') == '1'): |
| 34 | stderr = self.useFixture(fixtures.StringStream('stderr')).stream |
| 35 | self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) |
| 36 | |
Matthew Treinish | dde9d0a | 2013-10-31 18:26:52 -0400 | [diff] [blame] | 37 | mox_fixture = self.useFixture(moxstubout.MoxStubout()) |
Matthew Treinish | 8708621 | 2013-10-28 20:21:54 +0000 | [diff] [blame] | 38 | self.mox = mox_fixture.mox |
| 39 | self.stubs = mox_fixture.stubs |
Jay Pipes | 8fe5392 | 2014-01-14 20:08:16 -0500 | [diff] [blame] | 40 | |
| 41 | def patch(self, target, **kwargs): |
| 42 | """ |
| 43 | Returns a started `mock.patch` object for the supplied target. |
| 44 | |
| 45 | The caller may then call the returned patcher to create a mock object. |
| 46 | |
| 47 | The caller does not need to call stop() on the returned |
| 48 | patcher object, as this method automatically adds a cleanup |
| 49 | to the test class to stop the patcher. |
| 50 | |
| 51 | :param target: String module.class or module.object expression to patch |
| 52 | :param **kwargs: Passed as-is to `mock.patch`. See mock documentation |
| 53 | for details. |
| 54 | """ |
| 55 | p = mock.patch(target, **kwargs) |
| 56 | m = p.start() |
| 57 | self.addCleanup(p.stop) |
| 58 | return m |