From 3f6b7424ffb6e576b50346f338d64cc5e8289e6a Mon Sep 17 00:00:00 2001 From: Ihar Hrachyshka Date: Mon, 26 May 2014 22:06:43 +0200 Subject: [PATCH] Cleanup mock patches on BaseTestCase tearDown() Instead of cleaning up any remaining mock patches in each unit test that uses them, do it once on BaseTestCase tearDown(). Change-Id: I121ba554e16d83fc5908bb85afee4940f42dc4eb Closes-Bug: 1323214 --- oslotest/base.py | 2 ++ tests/unit/test_base.py | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/oslotest/base.py b/oslotest/base.py index f81fae6..f84e810 100644 --- a/oslotest/base.py +++ b/oslotest/base.py @@ -20,6 +20,7 @@ import os import tempfile import fixtures +import mock import testtools _TRUE_VALUES = ('True', 'true', '1', 'yes') @@ -35,6 +36,7 @@ class BaseTestCase(testtools.TestCase): self._fake_logs() self.useFixture(fixtures.NestedTempfile()) self.useFixture(fixtures.TempHomeDir()) + self.addCleanup(mock.patch.stopall) def _set_timeout(self): test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0) diff --git a/tests/unit/test_base.py b/tests/unit/test_base.py index 8317d28..8b76cc9 100644 --- a/tests/unit/test_base.py +++ b/tests/unit/test_base.py @@ -13,6 +13,7 @@ # under the License. import logging +import unittest import mock import testtools @@ -71,3 +72,23 @@ class TestBaseTestCase(testtools.TestCase): env_get_mock.assert_any_call('OS_LOG_CAPTURE') env_get_mock.assert_any_calls('OS_DEBUG') self.assertEqual(fixture_mock.call_count, 1) + + def test_mock_patch_cleanup_on_teardown(self): + # create an object and save its reference + class Sub(object): + pass + + obj = Sub() + obj.value = obj.backup = object() + + # patch the object + mock.patch.object(obj, 'value').start() + self.assertNotEqual(obj.value, obj.backup) + + # run a test case + loader = unittest.defaultTestLoader + suite = loader.loadTestsFromTestCase(self.FakeTestCase) + suite.run(unittest.TestResult()) + + # check that mock patches are cleaned up + self.assertEqual(obj.value, obj.backup)