Browse Source

Introduce ''mock_object'' method to base test class

We would like to fully remove mox from the test tree. Even for tests
that don't use mox's validation, many of them are using the symbol
patching with self.stubs.Set. We can do the same thing with the
monkeypatch fixture instead.

This introduces self.stub_out to nova/test.py and an example of what a
stubs => stub_out change would look like.

The teardown function in the converted test was removed at the same
time, as those should no longer be used.

Part of the mox community goal for Rocky.

Change-Id: I8f471ff8fee600ebb4e8907bf240007b7b4fe59f
Signed-off-by: Chuck Short <chucks@redhat.com>
Charles Short 11 months ago
parent
commit
8954959817

+ 4
- 4
glance/tests/functional/db/test_sqlalchemy.py View File

@@ -117,8 +117,8 @@ class TestSqlAlchemyDBDataIntegrity(base.TestDriver,
117 117
             return original_method(query, model, limit,
118 118
                                    sort_keys, marker, sort_dir, sort_dirs)
119 119
 
120
-        self.stubs.Set(self.db_api, '_paginate_query',
121
-                       fake_paginate_query)
120
+        self.mock_object(self.db_api, '_paginate_query',
121
+                         fake_paginate_query)
122 122
         self.db_api.image_get_all(self.context, sort_key=['created_at'])
123 123
 
124 124
     def test_paginate_non_redundant_sort_keys(self):
@@ -130,8 +130,8 @@ class TestSqlAlchemyDBDataIntegrity(base.TestDriver,
130 130
             return original_method(query, model, limit,
131 131
                                    sort_keys, marker, sort_dir, sort_dirs)
132 132
 
133
-        self.stubs.Set(self.db_api, '_paginate_query',
134
-                       fake_paginate_query)
133
+        self.mock_object(self.db_api, '_paginate_query',
134
+                         fake_paginate_query)
135 135
         self.db_api.image_get_all(self.context, sort_key=['name'])
136 136
 
137 137
 

+ 3
- 2
glance/tests/integration/v2/base.py View File

@@ -117,6 +117,7 @@ CONF = cfg.CONF
117 117
 
118 118
 
119 119
 class ApiTest(test_utils.BaseTestCase):
120
+
120 121
     def setUp(self):
121 122
         super(ApiTest, self).setUp()
122 123
         self.test_dir = self.useFixture(fixtures.TempDir()).path
@@ -209,8 +210,8 @@ class ApiTest(test_utils.BaseTestCase):
209 210
                 return test_utils.HttplibWsgiAdapter(self.glance_registry_app)
210 211
             return wrapped
211 212
 
212
-        self.stubs.Set(glance.common.client.BaseClient,
213
-                       'get_connection_type', get_connection_type)
213
+        self.mock_object(glance.common.client.BaseClient,
214
+                         'get_connection_type', get_connection_type)
214 215
 
215 216
     def tearDown(self):
216 217
         glance.db.sqlalchemy.api.clear_db_env()

+ 16
- 25
glance/tests/unit/api/test_cmd.py View File

@@ -52,19 +52,12 @@ class TestGlanceApiCmd(test_utils.BaseTestCase):
52 52
 
53 53
         store.register_opts(CONF)
54 54
 
55
-        self.config_patcher = mock.patch(
56
-            'glance.common.config.load_paste_app',
57
-            side_effect=self._do_nothing)
58
-        self.start_patcher = mock.patch('glance.common.wsgi.Server.start',
59
-                                        side_effect=self._do_nothing)
60
-        self.wait_patcher = mock.patch('glance.common.wsgi.Server.wait',
61
-                                       side_effect=self._do_nothing)
62
-
63
-        self.addCleanup(mock.patch.stopall)
64
-
65
-        self.config_patcher.start()
66
-        self.start_patcher.start()
67
-        self.wait_patcher.start()
55
+        self.mock_object(glance.common.config, 'load_paste_app',
56
+                         self._do_nothing)
57
+        self.mock_object(glance.common.wsgi.Server, 'start',
58
+                         self._do_nothing)
59
+        self.mock_object(glance.common.wsgi.Server, 'wait',
60
+                         self._do_nothing)
68 61
 
69 62
     def tearDown(self):
70 63
         sys.stderr = sys.__stderr__
@@ -77,10 +70,10 @@ class TestGlanceApiCmd(test_utils.BaseTestCase):
77 70
 
78 71
     def test_worker_creation_failure(self):
79 72
         failure = exc.WorkerCreationFailure(reason='test')
80
-        with mock.patch('glance.common.wsgi.Server.start',
81
-                        side_effect=self._raise(failure)):
82
-            exit = self.assertRaises(SystemExit, glance.cmd.api.main)
83
-            self.assertEqual(2, exit.code)
73
+        self.mock_object(glance.common.wsgi.Server, 'start',
74
+                         self._raise(failure))
75
+        exit = self.assertRaises(SystemExit, glance.cmd.api.main)
76
+        self.assertEqual(2, exit.code)
84 77
 
85 78
     @mock.patch.object(glance.common.config, 'parse_cache_args')
86 79
     @mock.patch.object(logging, 'setup')
@@ -103,12 +96,11 @@ class TestGlanceApiCmd(test_utils.BaseTestCase):
103 96
                                   mock.call.mock_cache_clean()]
104 97
         self.assertEqual(expected_call_sequence, manager.mock_calls)
105 98
 
106
-    @mock.patch.object(glance.image_cache.cleaner.Cleaner, 'run')
107 99
     @mock.patch.object(glance.image_cache.base.CacheApp, '__init__')
108
-    def test_cache_cleaner_main_runtime_exception_handling(self, mock_cache,
109
-                                                           mock_run):
100
+    def test_cache_cleaner_main_runtime_exception_handling(self, mock_cache):
110 101
         mock_cache.return_value = None
111
-        mock_run.side_effect = self._raise(RuntimeError)
102
+        self.mock_object(glance.image_cache.cleaner.Cleaner, 'run',
103
+                         self._raise(RuntimeError))
112 104
         exit = self.assertRaises(SystemExit, glance.cmd.cache_cleaner.main)
113 105
         self.assertEqual('ERROR: ', exit.code)
114 106
 
@@ -133,12 +125,11 @@ class TestGlanceApiCmd(test_utils.BaseTestCase):
133 125
                                   mock.call.mock_cache_prune()]
134 126
         self.assertEqual(expected_call_sequence, manager.mock_calls)
135 127
 
136
-    @mock.patch.object(glance.image_cache.pruner.Pruner, 'run')
137 128
     @mock.patch.object(glance.image_cache.base.CacheApp, '__init__')
138
-    def test_cache_pruner_main_runtime_exception_handling(self, mock_cache,
139
-                                                          mock_run):
129
+    def test_cache_pruner_main_runtime_exception_handling(self, mock_cache):
140 130
         mock_cache.return_value = None
141
-        mock_run.side_effect = self._raise(RuntimeError)
131
+        self.mock_object(glance.image_cache.pruner.Pruner, 'run',
132
+                         self._raise(RuntimeError))
142 133
         exit = self.assertRaises(SystemExit, glance.cmd.cache_pruner.main)
143 134
         self.assertEqual('ERROR: ', exit.code)
144 135
 

+ 12
- 0
glance/tests/unit/base.py View File

@@ -17,6 +17,7 @@ import os
17 17
 
18 18
 import glance_store as store
19 19
 from glance_store import location
20
+import mock
20 21
 from oslo_concurrency import lockutils
21 22
 from oslo_config import cfg
22 23
 from oslo_db import options
@@ -134,3 +135,14 @@ class MultiIsolatedUnitTest(MultiStoreClearingUnitTest):
134 135
         fap = open(CONF.oslo_policy.policy_file, 'w')
135 136
         fap.write(jsonutils.dumps(rules))
136 137
         fap.close()
138
+
139
+    def mock_object(self, obj, attr_name, *args, **kwargs):
140
+        """Use python mock to mock an object attribute
141
+
142
+        Mocks the specified objects attribute with the given value.
143
+        Automatically performs 'addCleanup' for the mock.
144
+        """
145
+        patcher = mock.patch.object(obj, attr_name, *args, **kwargs)
146
+        result = patcher.start()
147
+        self.addCleanup(patcher.stop)
148
+        return result

+ 0
- 3
glance/tests/unit/common/test_config.py View File

@@ -18,7 +18,6 @@ import shutil
18 18
 
19 19
 import fixtures
20 20
 import oslo_middleware
21
-from oslotest import moxstubout
22 21
 
23 22
 from glance.api.middleware import context
24 23
 from glance.common import config
@@ -29,8 +28,6 @@ class TestPasteApp(test_utils.BaseTestCase):
29 28
 
30 29
     def setUp(self):
31 30
         super(TestPasteApp, self).setUp()
32
-        mox_fixture = self.useFixture(moxstubout.MoxStubout())
33
-        self.stubs = mox_fixture.stubs
34 31
 
35 32
     def _do_test_load_paste_app(self,
36 33
                                 expected_app_type,

+ 16
- 12
glance/tests/unit/common/test_location_strategy.py View File

@@ -48,12 +48,14 @@ class TestLocationStrategy(base.IsolatedUnitTest):
48 48
         modules = ['module1', 'module2']
49 49
 
50 50
         def _fake_stevedore_extension_manager(*args, **kwargs):
51
-            ret = lambda: None
51
+            def ret():
52
+                return None
52 53
             ret.names = lambda: modules
53 54
             return ret
54 55
 
55 56
         def _fake_stevedore_driver_manager(*args, **kwargs):
56
-            ret = lambda: None
57
+            def ret():
58
+                return None
57 59
             ret.driver = lambda: None
58 60
             ret.driver.__name__ = kwargs['name']
59 61
             # Module 1 and 2 has a same strategy name
@@ -61,10 +63,10 @@ class TestLocationStrategy(base.IsolatedUnitTest):
61 63
             ret.driver.init = lambda: None
62 64
             return ret
63 65
 
64
-        self.stub = self.stubs.Set(stevedore.extension, "ExtensionManager",
65
-                                   _fake_stevedore_extension_manager)
66
-        self.stub = self.stubs.Set(stevedore.driver, "DriverManager",
67
-                                   _fake_stevedore_driver_manager)
66
+        self.stub = self.mock_object(stevedore.extension, "ExtensionManager",
67
+                                     _fake_stevedore_extension_manager)
68
+        self.stub = self.mock_object(stevedore.driver, "DriverManager",
69
+                                     _fake_stevedore_driver_manager)
68 70
 
69 71
         loaded_modules = location_strategy._load_strategies()
70 72
         self.assertEqual(1, len(loaded_modules))
@@ -76,7 +78,8 @@ class TestLocationStrategy(base.IsolatedUnitTest):
76 78
         modules = ['module_init_exception', 'module_good']
77 79
 
78 80
         def _fake_stevedore_extension_manager(*args, **kwargs):
79
-            ret = lambda: None
81
+            def ret():
82
+                return None
80 83
             ret.names = lambda: modules
81 84
             return ret
82 85
 
@@ -84,17 +87,18 @@ class TestLocationStrategy(base.IsolatedUnitTest):
84 87
             if kwargs['name'] == 'module_init_exception':
85 88
                 raise Exception('strategy module failed to initialize.')
86 89
             else:
87
-                ret = lambda: None
90
+                def ret():
91
+                    return None
88 92
                 ret.driver = lambda: None
89 93
                 ret.driver.__name__ = kwargs['name']
90 94
                 ret.driver.get_strategy_name = lambda: kwargs['name']
91 95
                 ret.driver.init = lambda: None
92 96
             return ret
93 97
 
94
-        self.stub = self.stubs.Set(stevedore.extension, "ExtensionManager",
95
-                                   _fake_stevedore_extension_manager)
96
-        self.stub = self.stubs.Set(stevedore.driver, "DriverManager",
97
-                                   _fake_stevedore_driver_manager)
98
+        self.stub = self.mock_object(stevedore.extension, "ExtensionManager",
99
+                                     _fake_stevedore_extension_manager)
100
+        self.stub = self.mock_object(stevedore.driver, "DriverManager",
101
+                                     _fake_stevedore_driver_manager)
98 102
 
99 103
         loaded_modules = location_strategy._load_strategies()
100 104
         self.assertEqual(1, len(loaded_modules))

+ 5
- 4
glance/tests/unit/common/test_wsgi.py View File

@@ -49,7 +49,8 @@ class RequestTest(test_utils.BaseTestCase):
49 49
         def returns_some_locales(*args, **kwargs):
50 50
             return all_locales
51 51
 
52
-        self.stubs.Set(localedata, 'locale_identifiers', returns_some_locales)
52
+        self.mock_object(localedata, 'locale_identifiers',
53
+                         returns_some_locales)
53 54
 
54 55
         # Override gettext.find to return other than None for some languages.
55 56
         def fake_gettext_find(lang_id, *args, **kwargs):
@@ -62,7 +63,7 @@ class RequestTest(test_utils.BaseTestCase):
62 63
                 return found_ret
63 64
             return None
64 65
 
65
-        self.stubs.Set(gettext, 'find', fake_gettext_find)
66
+        self.mock_object(gettext, 'find', fake_gettext_find)
66 67
 
67 68
     def test_content_range(self):
68 69
         request = wsgi.Request.blank('/tests/123')
@@ -338,7 +339,7 @@ class ResourceTest(test_utils.BaseTestCase):
338 339
             if isinstance(obj, wsgi.JSONResponseSerializer):
339 340
                 raise webob.exc.HTTPForbidden()
340 341
 
341
-        self.stubs.Set(wsgi.Resource, 'dispatch', dispatch)
342
+        self.mock_object(wsgi.Resource, 'dispatch', dispatch)
342 343
 
343 344
         request = wsgi.Request.blank('/')
344 345
 
@@ -357,7 +358,7 @@ class ResourceTest(test_utils.BaseTestCase):
357 358
         def dispatch(self, obj, action, *args, **kwargs):
358 359
             raise Exception("test exception")
359 360
 
360
-        self.stubs.Set(wsgi.Resource, 'dispatch', dispatch)
361
+        self.mock_object(wsgi.Resource, 'dispatch', dispatch)
361 362
 
362 363
         request = wsgi.Request.blank('/')
363 364
 

+ 4
- 7
glance/tests/unit/test_auth.py View File

@@ -15,7 +15,6 @@
15 15
 #    under the License.
16 16
 
17 17
 from oslo_serialization import jsonutils
18
-from oslotest import moxstubout
19 18
 from six.moves import http_client as http
20 19
 import webob
21 20
 
@@ -123,8 +122,6 @@ class TestKeystoneAuthPlugin(utils.BaseTestCase):
123 122
 
124 123
     def setUp(self):
125 124
         super(TestKeystoneAuthPlugin, self).setUp()
126
-        mox_fixture = self.useFixture(moxstubout.MoxStubout())
127
-        self.stubs = mox_fixture.stubs
128 125
 
129 126
     def test_get_plugin_from_strategy_keystone(self):
130 127
         strategy = auth.get_plugin_from_strategy('keystone')
@@ -200,7 +197,7 @@ class TestKeystoneAuthPlugin(utils.BaseTestCase):
200 197
             resp.status = http.BAD_REQUEST
201 198
             return FakeResponse(resp), ""
202 199
 
203
-        self.stubs.Set(auth.KeystoneStrategy, '_do_request', fake_do_request)
200
+        self.mock_object(auth.KeystoneStrategy, '_do_request', fake_do_request)
204 201
 
205 202
         bad_creds = {
206 203
             'username': 'user1',
@@ -222,7 +219,7 @@ class TestKeystoneAuthPlugin(utils.BaseTestCase):
222 219
             resp.status = http.BAD_REQUEST
223 220
             return FakeResponse(resp), ""
224 221
 
225
-        self.stubs.Set(auth.KeystoneStrategy, '_do_request', fake_do_request)
222
+        self.mock_object(auth.KeystoneStrategy, '_do_request', fake_do_request)
226 223
 
227 224
         bad_creds = {
228 225
             'username': 'user1',
@@ -254,7 +251,7 @@ class TestKeystoneAuthPlugin(utils.BaseTestCase):
254 251
 
255 252
             return FakeResponse(resp), ""
256 253
 
257
-        self.stubs.Set(auth.KeystoneStrategy, '_do_request', fake_do_request)
254
+        self.mock_object(auth.KeystoneStrategy, '_do_request', fake_do_request)
258 255
 
259 256
         unauthorized_creds = [
260 257
             {
@@ -344,7 +341,7 @@ class TestKeystoneAuthPlugin(utils.BaseTestCase):
344 341
 
345 342
         mock_token = V2Token()
346 343
         mock_token.add_service('image', ['RegionOne'])
347
-        self.stubs.Set(auth.KeystoneStrategy, '_do_request', fake_do_request)
344
+        self.mock_object(auth.KeystoneStrategy, '_do_request', fake_do_request)
348 345
 
349 346
         unauthorized_creds = [
350 347
             {

+ 1
- 4
glance/tests/unit/test_image_cache.py View File

@@ -23,7 +23,6 @@ import time
23 23
 
24 24
 import fixtures
25 25
 from oslo_utils import units
26
-from oslotest import moxstubout
27 26
 import six
28 27
 # NOTE(jokke): simplified transition to py3, behaves like py2 xrange
29 28
 from six.moves import range
@@ -518,9 +517,7 @@ class TestImageCacheNoDep(test_utils.BaseTestCase):
518 517
         def init_driver(self2):
519 518
             self2.driver = self.driver
520 519
 
521
-        mox_fixture = self.useFixture(moxstubout.MoxStubout())
522
-        self.stubs = mox_fixture.stubs
523
-        self.stubs.Set(image_cache.ImageCache, 'init_driver', init_driver)
520
+        self.mock_object(image_cache.ImageCache, 'init_driver', init_driver)
524 521
 
525 522
     def test_get_caching_iter_when_write_fails(self):
526 523
 

+ 17
- 2
glance/tests/unit/test_policy.py View File

@@ -32,12 +32,14 @@ UUID1 = 'c80a1a6c-bd1f-41c5-90ee-81afedb1d58d'
32 32
 
33 33
 
34 34
 class IterableMock(mock.Mock, collections.Iterable):
35
+
35 36
     def __iter__(self):
36 37
         while False:
37 38
             yield None
38 39
 
39 40
 
40 41
 class ImageRepoStub(object):
42
+
41 43
     def get(self, *args, **kwargs):
42 44
         return 'image_from_get'
43 45
 
@@ -52,6 +54,7 @@ class ImageRepoStub(object):
52 54
 
53 55
 
54 56
 class ImageStub(object):
57
+
55 58
     def __init__(self, image_id=None, visibility='private',
56 59
                  container_format='bear', disk_format='raw',
57 60
                  status='active', extra_properties=None,
@@ -87,6 +90,7 @@ class ImageStub(object):
87 90
 
88 91
 
89 92
 class ImageFactoryStub(object):
93
+
90 94
     def new_image(self, image_id=None, name=None, visibility='private',
91 95
                   min_disk=0, min_ram=0, protected=False, owner=None,
92 96
                   disk_format=None, container_format=None,
@@ -117,11 +121,13 @@ class MemberRepoStub(object):
117 121
 
118 122
 
119 123
 class ImageMembershipStub(object):
124
+
120 125
     def __init__(self, output=None):
121 126
         self.output = output
122 127
 
123 128
 
124 129
 class TaskRepoStub(object):
130
+
125 131
     def get(self, *args, **kwargs):
126 132
         return 'task_from_get'
127 133
 
@@ -133,6 +139,7 @@ class TaskRepoStub(object):
133 139
 
134 140
 
135 141
 class TaskStub(object):
142
+
136 143
     def __init__(self, task_id):
137 144
         self.task_id = task_id
138 145
         self.status = 'pending'
@@ -142,11 +149,13 @@ class TaskStub(object):
142 149
 
143 150
 
144 151
 class TaskFactoryStub(object):
152
+
145 153
     def new_task(self, *args):
146 154
         return 'new_task'
147 155
 
148 156
 
149 157
 class TestPolicyEnforcer(base.IsolatedUnitTest):
158
+
150 159
     def test_policy_file_default_rules_default_location(self):
151 160
         enforcer = glance.api.policy.Enforcer()
152 161
 
@@ -209,6 +218,7 @@ class TestPolicyEnforcer(base.IsolatedUnitTest):
209 218
 
210 219
 
211 220
 class TestPolicyEnforcerNoFile(base.IsolatedUnitTest):
221
+
212 222
     def test_policy_file_specified_but_not_found(self):
213 223
         """Missing defined policy file should result in a default ruleset"""
214 224
         self.config(policy_file='gobble.gobble', group='oslo_policy')
@@ -223,11 +233,12 @@ class TestPolicyEnforcerNoFile(base.IsolatedUnitTest):
223 233
 
224 234
     def test_policy_file_default_not_found(self):
225 235
         """Missing default policy file should result in a default ruleset"""
236
+
226 237
         def fake_find_file(self, name):
227 238
             return None
228 239
 
229
-        self.stubs.Set(oslo_config.cfg.ConfigOpts, 'find_file',
230
-                       fake_find_file)
240
+        self.mock_object(oslo_config.cfg.ConfigOpts, 'find_file',
241
+                         fake_find_file)
231 242
 
232 243
         enforcer = glance.api.policy.Enforcer()
233 244
 
@@ -240,6 +251,7 @@ class TestPolicyEnforcerNoFile(base.IsolatedUnitTest):
240 251
 
241 252
 
242 253
 class TestImagePolicy(test_utils.BaseTestCase):
254
+
243 255
     def setUp(self):
244 256
         self.image_stub = ImageStub(UUID1)
245 257
         self.image_repo_stub = ImageRepoStub()
@@ -416,6 +428,7 @@ class TestImagePolicy(test_utils.BaseTestCase):
416 428
 
417 429
 
418 430
 class TestMemberPolicy(test_utils.BaseTestCase):
431
+
419 432
     def setUp(self):
420 433
         self.policy = mock.Mock()
421 434
         self.policy.enforce = mock.Mock()
@@ -491,6 +504,7 @@ class TestMemberPolicy(test_utils.BaseTestCase):
491 504
 
492 505
 
493 506
 class TestTaskPolicy(test_utils.BaseTestCase):
507
+
494 508
     def setUp(self):
495 509
         self.task_stub = TaskStub(UUID1)
496 510
         self.task_repo_stub = TaskRepoStub()
@@ -569,6 +583,7 @@ class TestTaskPolicy(test_utils.BaseTestCase):
569 583
 
570 584
 
571 585
 class TestContextPolicyEnforcer(base.IsolatedUnitTest):
586
+
572 587
     def _do_test_policy_influence_context_admin(self,
573 588
                                                 policy_admin_role,
574 589
                                                 context_role,

+ 14
- 8
glance/tests/unit/test_quota.py View File

@@ -52,6 +52,7 @@ class FakeImage(object):
52 52
 
53 53
 
54 54
 class TestImageQuota(test_utils.BaseTestCase):
55
+
55 56
     def setUp(self):
56 57
         super(TestImageQuota, self).setUp()
57 58
 
@@ -283,8 +284,8 @@ class TestImageQuota(test_utils.BaseTestCase):
283 284
         image = glance.quota.ImageProxy(base_image, context, db_api, store)
284 285
         self.assertIsNone(image.size)
285 286
 
286
-        self.stubs.Set(store_api, 'get_size_from_backend',
287
-                       unit_test_utils.fake_get_size_from_backend)
287
+        self.mock_object(store_api, 'get_size_from_backend',
288
+                         unit_test_utils.fake_get_size_from_backend)
288 289
         image.locations.append({'url': 'file:///fake.img.tar.gz',
289 290
                                 'metadata': {}})
290 291
         self.assertIn({'url': 'file:///fake.img.tar.gz', 'metadata': {}},
@@ -300,8 +301,8 @@ class TestImageQuota(test_utils.BaseTestCase):
300 301
         image = glance.quota.ImageProxy(base_image, context, db_api, store)
301 302
         self.assertIsNone(image.size)
302 303
 
303
-        self.stubs.Set(store_api, 'get_size_from_backend',
304
-                       unit_test_utils.fake_get_size_from_backend)
304
+        self.mock_object(store_api, 'get_size_from_backend',
305
+                         unit_test_utils.fake_get_size_from_backend)
305 306
         image.locations.insert(0,
306 307
                                {'url': 'file:///fake.img.tar.gz',
307 308
                                 'metadata': {}})
@@ -318,8 +319,8 @@ class TestImageQuota(test_utils.BaseTestCase):
318 319
         image = glance.quota.ImageProxy(base_image, context, db_api, store)
319 320
         self.assertIsNone(image.size)
320 321
 
321
-        self.stubs.Set(store_api, 'get_size_from_backend',
322
-                       unit_test_utils.fake_get_size_from_backend)
322
+        self.mock_object(store_api, 'get_size_from_backend',
323
+                         unit_test_utils.fake_get_size_from_backend)
323 324
         image.locations = [{'url': 'file:///fake.img.tar.gz', 'metadata': {}}]
324 325
         self.assertEqual([{'url': 'file:///fake.img.tar.gz', 'metadata': {}}],
325 326
                          image.locations)
@@ -334,14 +335,15 @@ class TestImageQuota(test_utils.BaseTestCase):
334 335
         image = glance.quota.ImageProxy(base_image, context, db_api, store)
335 336
         self.assertIsNone(image.size)
336 337
 
337
-        self.stubs.Set(store_api, 'get_size_from_backend',
338
-                       unit_test_utils.fake_get_size_from_backend)
338
+        self.mock_object(store_api, 'get_size_from_backend',
339
+                         unit_test_utils.fake_get_size_from_backend)
339 340
         image.locations += [{'url': 'file:///fake.img.tar.gz', 'metadata': {}}]
340 341
         self.assertIn({'url': 'file:///fake.img.tar.gz', 'metadata': {}},
341 342
                       image.locations)
342 343
 
343 344
 
344 345
 class TestImagePropertyQuotas(test_utils.BaseTestCase):
346
+
345 347
     def setUp(self):
346 348
         super(TestImagePropertyQuotas, self).setUp()
347 349
         self.base_image = FakeImage()
@@ -485,6 +487,7 @@ class TestImagePropertyQuotas(test_utils.BaseTestCase):
485 487
 
486 488
 
487 489
 class TestImageTagQuotas(test_utils.BaseTestCase):
490
+
488 491
     def setUp(self):
489 492
         super(TestImageTagQuotas, self).setUp()
490 493
         self.base_image = mock.Mock()
@@ -549,6 +552,7 @@ class TestImageTagQuotas(test_utils.BaseTestCase):
549 552
 
550 553
 
551 554
 class TestQuotaImageTagsProxy(test_utils.BaseTestCase):
555
+
552 556
     def setUp(self):
553 557
         super(TestQuotaImageTagsProxy, self).setUp()
554 558
 
@@ -594,6 +598,7 @@ class TestQuotaImageTagsProxy(test_utils.BaseTestCase):
594 598
 
595 599
 
596 600
 class TestImageMemberQuotas(test_utils.BaseTestCase):
601
+
597 602
     def setUp(self):
598 603
         super(TestImageMemberQuotas, self).setUp()
599 604
         db_api = unit_test_utils.FakeDB()
@@ -631,6 +636,7 @@ class TestImageMemberQuotas(test_utils.BaseTestCase):
631 636
 
632 637
 
633 638
 class TestImageLocationQuotas(test_utils.BaseTestCase):
639
+
634 640
     def setUp(self):
635 641
         super(TestImageLocationQuotas, self).setUp()
636 642
         self.base_image = mock.Mock()

+ 8
- 8
glance/tests/unit/test_store_image.py View File

@@ -128,8 +128,8 @@ class TestStoreImage(utils.BaseTestCase):
128 128
         self.assertEqual(2, len(image1.locations))
129 129
         self.assertEqual(UUID2, location_data['url'])
130 130
 
131
-        self.stubs.Set(unit_test_utils.FakeStoreAPI, 'get_from_backend',
132
-                       fake_get_from_backend)
131
+        self.mock_object(unit_test_utils.FakeStoreAPI, 'get_from_backend',
132
+                         fake_get_from_backend)
133 133
         # This time, image1.get_data() returns the data wrapped in a
134 134
         # LimitingReader|CooperativeReader pipeline, so peeking under
135 135
         # the hood of those objects to get at the underlying string.
@@ -200,8 +200,8 @@ class TestStoreImage(utils.BaseTestCase):
200 200
         }
201 201
         image_stub = ImageStub(UUID2, status='queued',
202 202
                                extra_properties=extra_properties)
203
-        self.stubs.Set(signature_utils, 'get_verifier',
204
-                       unit_test_utils.fake_get_verifier)
203
+        self.mock_object(signature_utils, 'get_verifier',
204
+                         unit_test_utils.fake_get_verifier)
205 205
         image = glance.location.ImageProxy(image_stub, context,
206 206
                                            self.store_api, self.store_utils)
207 207
         image.set_data('YYYY', 4)
@@ -220,8 +220,8 @@ class TestStoreImage(utils.BaseTestCase):
220 220
         }
221 221
         image_stub = ImageStub(UUID2, status='queued',
222 222
                                extra_properties=extra_properties)
223
-        self.stubs.Set(signature_utils, 'get_verifier',
224
-                       unit_test_utils.fake_get_verifier)
223
+        self.mock_object(signature_utils, 'get_verifier',
224
+                         unit_test_utils.fake_get_verifier)
225 225
         image = glance.location.ImageProxy(image_stub, context,
226 226
                                            self.store_api, self.store_utils)
227 227
         with mock.patch.object(self.store_api,
@@ -240,8 +240,8 @@ class TestStoreImage(utils.BaseTestCase):
240 240
         }
241 241
         image_stub = ImageStub(UUID2, status='queued',
242 242
                                extra_properties=extra_properties)
243
-        self.stubs.Set(signature_utils, 'get_verifier',
244
-                       unit_test_utils.fake_get_verifier)
243
+        self.mock_object(signature_utils, 'get_verifier',
244
+                         unit_test_utils.fake_get_verifier)
245 245
         image = glance.location.ImageProxy(image_stub, context,
246 246
                                            self.store_api, self.store_utils)
247 247
         image.set_data('YYYY', 4)

+ 2
- 2
glance/tests/unit/test_store_location.py View File

@@ -43,8 +43,8 @@ class TestStoreLocation(base.StoreClearingUnitTest):
43 43
         def fake_get_size_from_backend(uri, context=None):
44 44
             return 1
45 45
 
46
-        self.stubs.Set(glance_store, 'get_size_from_backend',
47
-                       fake_get_size_from_backend)
46
+        self.mock_object(glance_store, 'get_size_from_backend',
47
+                         fake_get_size_from_backend)
48 48
 
49 49
         with mock.patch('glance.location._check_image_location'):
50 50
             loc1 = {'url': 'file:///fake1.img.tar.gz', 'metadata': {}}

+ 9
- 3
glance/tests/unit/v2/test_image_data_resource.py View File

@@ -32,6 +32,7 @@ import glance.tests.utils as test_utils
32 32
 
33 33
 
34 34
 class Raise(object):
35
+
35 36
     def __init__(self, exc):
36 37
         self.exc = exc
37 38
 
@@ -40,6 +41,7 @@ class Raise(object):
40 41
 
41 42
 
42 43
 class FakeImage(object):
44
+
43 45
     def __init__(self, image_id=None, data=None, checksum=None, size=0,
44 46
                  virtual_size=0, locations=None, container_format='bear',
45 47
                  disk_format='rawr', status=None):
@@ -76,6 +78,7 @@ class FakeImage(object):
76 78
 
77 79
 
78 80
 class FakeImageRepo(object):
81
+
79 82
     def __init__(self, result=None):
80 83
         self.result = result
81 84
 
@@ -90,6 +93,7 @@ class FakeImageRepo(object):
90 93
 
91 94
 
92 95
 class FakeGateway(object):
96
+
93 97
     def __init__(self, db=None, store=None, notifier=None,
94 98
                  policy=None, repo=None):
95 99
         self.db = db
@@ -103,6 +107,7 @@ class FakeGateway(object):
103 107
 
104 108
 
105 109
 class TestImagesController(base.StoreClearingUnitTest):
110
+
106 111
     def setUp(self):
107 112
         super(TestImagesController, self).setUp()
108 113
 
@@ -157,6 +162,7 @@ class TestImagesController(base.StoreClearingUnitTest):
157 162
 
158 163
     def test_download_ok_when_get_image_location_forbidden(self):
159 164
         class ImageLocations(object):
165
+
160 166
             def __len__(self):
161 167
                 raise exception.Forbidden()
162 168
 
@@ -888,9 +894,9 @@ class TestImageDataSerializer(test_utils.BaseTestCase):
888 894
         def get_data(*args, **kwargs):
889 895
             raise exception.Forbidden()
890 896
 
891
-        self.stubs.Set(glance.api.policy.ImageProxy,
892
-                       'get_data',
893
-                       get_data)
897
+        self.mock_object(glance.api.policy.ImageProxy,
898
+                         'get_data',
899
+                         get_data)
894 900
         request = wsgi.Request.blank('/')
895 901
         request.environ = {}
896 902
         response = webob.Response()

+ 15
- 10
glance/tests/unit/v2/test_images_resource.py View File

@@ -1973,8 +1973,8 @@ class TestImagesController(base.IsolatedUnitTest):
1973 1973
         as long as the image has fewer than the limited number of image
1974 1974
         locations after the transaction.
1975 1975
         """
1976
-        self.stubs.Set(store, 'get_size_from_backend',
1977
-                       unit_test_utils.fake_get_size_from_backend)
1976
+        self.mock_object(store, 'get_size_from_backend',
1977
+                         unit_test_utils.fake_get_size_from_backend)
1978 1978
         self.config(show_multiple_locations=True)
1979 1979
         request = unit_test_utils.get_fake_request()
1980 1980
 
@@ -2039,8 +2039,8 @@ class TestImagesController(base.IsolatedUnitTest):
2039 2039
 
2040 2040
     def test_update_remove_location(self):
2041 2041
         self.config(show_multiple_locations=True)
2042
-        self.stubs.Set(store, 'get_size_from_backend',
2043
-                       unit_test_utils.fake_get_size_from_backend)
2042
+        self.mock_object(store, 'get_size_from_backend',
2043
+                         unit_test_utils.fake_get_size_from_backend)
2044 2044
 
2045 2045
         request = unit_test_utils.get_fake_request()
2046 2046
         new_location = {'url': '%s/fake_location' % BASE_URI, 'metadata': {}}
@@ -2080,8 +2080,9 @@ class TestImagesController(base.IsolatedUnitTest):
2080 2080
         def fake_delete_image_location_from_backend(self, *args, **kwargs):
2081 2081
             raise Exception('fake_backend_exception')
2082 2082
 
2083
-        self.stubs.Set(self.store_utils, 'delete_image_location_from_backend',
2084
-                       fake_delete_image_location_from_backend)
2083
+        self.mock_object(self.store_utils,
2084
+                         'delete_image_location_from_backend',
2085
+                         fake_delete_image_location_from_backend)
2085 2086
 
2086 2087
         request = unit_test_utils.get_fake_request()
2087 2088
         changes = [
@@ -2288,8 +2289,8 @@ class TestImagesController(base.IsolatedUnitTest):
2288 2289
     def test_delete_in_use(self):
2289 2290
         def fake_safe_delete_from_backend(self, *args, **kwargs):
2290 2291
             raise store.exceptions.InUseByStore()
2291
-        self.stubs.Set(self.store_utils, 'safe_delete_from_backend',
2292
-                       fake_safe_delete_from_backend)
2292
+        self.mock_object(self.store_utils, 'safe_delete_from_backend',
2293
+                         fake_safe_delete_from_backend)
2293 2294
         request = unit_test_utils.get_fake_request()
2294 2295
         self.assertRaises(webob.exc.HTTPConflict, self.controller.delete,
2295 2296
                           request, UUID1)
@@ -2297,8 +2298,8 @@ class TestImagesController(base.IsolatedUnitTest):
2297 2298
     def test_delete_has_snapshot(self):
2298 2299
         def fake_safe_delete_from_backend(self, *args, **kwargs):
2299 2300
             raise store.exceptions.HasSnapshot()
2300
-        self.stubs.Set(self.store_utils, 'safe_delete_from_backend',
2301
-                       fake_safe_delete_from_backend)
2301
+        self.mock_object(self.store_utils, 'safe_delete_from_backend',
2302
+                         fake_safe_delete_from_backend)
2302 2303
         request = unit_test_utils.get_fake_request()
2303 2304
         self.assertRaises(webob.exc.HTTPConflict, self.controller.delete,
2304 2305
                           request, UUID1)
@@ -3584,6 +3585,7 @@ class TestImagesSerializer(test_utils.BaseTestCase):
3584 3585
 
3585 3586
         """
3586 3587
         class ImageLocations(object):
3588
+
3587 3589
             def __len__(self):
3588 3590
                 raise exception.Forbidden()
3589 3591
 
@@ -4140,6 +4142,7 @@ class TestImagesSerializerWithAdditionalProperties(test_utils.BaseTestCase):
4140 4142
 
4141 4143
 
4142 4144
 class TestImagesSerializerDirectUrl(test_utils.BaseTestCase):
4145
+
4143 4146
     def setUp(self):
4144 4147
         super(TestImagesSerializerDirectUrl, self).setUp()
4145 4148
         self.serializer = glance.api.v2.images.ResponseSerializer()
@@ -4225,6 +4228,7 @@ class TestImagesSerializerDirectUrl(test_utils.BaseTestCase):
4225 4228
 
4226 4229
 
4227 4230
 class TestImageSchemaFormatConfiguration(test_utils.BaseTestCase):
4231
+
4228 4232
     def test_default_disk_formats(self):
4229 4233
         schema = glance.api.v2.images.get_schema()
4230 4234
         expected = [None, 'ami', 'ari', 'aki', 'vhd', 'vhdx', 'vmdk',
@@ -4254,6 +4258,7 @@ class TestImageSchemaFormatConfiguration(test_utils.BaseTestCase):
4254 4258
 
4255 4259
 
4256 4260
 class TestImageSchemaDeterminePropertyBasis(test_utils.BaseTestCase):
4261
+
4257 4262
     def test_custom_property_marked_as_non_base(self):
4258 4263
         self.config(allow_additional_image_properties=False)
4259 4264
         custom_image_properties = {

+ 1
- 1
glance/tests/unit/v2/test_registry_client.py View File

@@ -759,7 +759,7 @@ class TestRegistryV2ClientApi(base.IsolatedUnitTest):
759 759
         self.config(admin_tenant_name=expected['tenant'])
760 760
         self.config(auth_strategy=expected['strategy'])
761 761
         self.config(auth_region=expected['region'])
762
-        self.stubs.Set(os, 'getenv', lambda x: None)
762
+        self.mock_object(os, 'getenv', lambda x: None)
763 763
 
764 764
         self.assertIsNone(rapi._CLIENT_CREDS)
765 765
         rapi.configure_registry_admin_creds()

+ 15
- 1
glance/tests/utils.py View File

@@ -25,6 +25,7 @@ import subprocess
25 25
 
26 26
 from alembic import command as alembic_command
27 27
 import fixtures
28
+import mock
28 29
 from oslo_config import cfg
29 30
 from oslo_config import fixture as cfg_fixture
30 31
 from oslo_log.fixture import logging_error as log_fixture
@@ -79,7 +80,7 @@ class BaseTestCase(testtools.TestCase):
79 80
         self.addCleanup(CONF.reset)
80 81
         mox_fixture = self.useFixture(moxstubout.MoxStubout())
81 82
         self.stubs = mox_fixture.stubs
82
-        self.stubs.Set(exception, '_FATAL_EXCEPTION_FORMAT_ERRORS', True)
83
+        self.mock_object(exception, '_FATAL_EXCEPTION_FORMAT_ERRORS', True)
83 84
         self.test_dir = self.useFixture(fixtures.TempDir()).path
84 85
         self.conf_dir = os.path.join(self.test_dir, 'etc')
85 86
         utils.safe_mkdirs(self.conf_dir)
@@ -139,9 +140,21 @@ class BaseTestCase(testtools.TestCase):
139 140
         """
140 141
         self._config_fixture.config(**kw)
141 142
 
143
+    def mock_object(self, obj, attr_name, *args, **kwargs):
144
+        """"Use python mock to mock an object attirbute
145
+
146
+        Mocks the specified objects attribute with the given value.
147
+        Automatically performs 'addCleanup' for the mock.
148
+        """
149
+        patcher = mock.patch.object(obj, attr_name, *args, **kwargs)
150
+        result = patcher.start()
151
+        self.addCleanup(patcher.stop)
152
+        return result
153
+
142 154
 
143 155
 class requires(object):
144 156
     """Decorator that initiates additional test setup/teardown."""
157
+
145 158
     def __init__(self, setup=None, teardown=None):
146 159
         self.setup = setup
147 160
         self.teardown = teardown
@@ -160,6 +173,7 @@ class requires(object):
160 173
 
161 174
 class depends_on_exe(object):
162 175
     """Decorator to skip test if an executable is unavailable"""
176
+
163 177
     def __init__(self, exe):
164 178
         self.exe = exe
165 179
 

Loading…
Cancel
Save