summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorZuul <zuul@review.openstack.org>2018-08-10 14:40:35 +0000
committerGerrit Code Review <review@openstack.org>2018-08-10 14:40:35 +0000
commit0988d938572d87b59704b527516a1aa587ab67fd (patch)
tree84e4e2468d79b17161e784487402cbd0802f0d3a
parentf0e75d90a6e1129cc820163406cbc5b136dd64b2 (diff)
parent8954959817332ef4002e6bad20edb8e77a8f096b (diff)
Merge "Introduce ''mock_object'' method to base test class"
-rw-r--r--glance/tests/functional/db/test_sqlalchemy.py8
-rw-r--r--glance/tests/integration/v2/base.py5
-rw-r--r--glance/tests/unit/api/test_cmd.py41
-rw-r--r--glance/tests/unit/base.py12
-rw-r--r--glance/tests/unit/common/test_config.py3
-rw-r--r--glance/tests/unit/common/test_location_strategy.py28
-rw-r--r--glance/tests/unit/common/test_wsgi.py9
-rw-r--r--glance/tests/unit/test_auth.py11
-rw-r--r--glance/tests/unit/test_image_cache.py5
-rw-r--r--glance/tests/unit/test_policy.py19
-rw-r--r--glance/tests/unit/test_quota.py22
-rw-r--r--glance/tests/unit/test_store_image.py16
-rw-r--r--glance/tests/unit/test_store_location.py4
-rw-r--r--glance/tests/unit/v2/test_image_data_resource.py12
-rw-r--r--glance/tests/unit/v2/test_images_resource.py25
-rw-r--r--glance/tests/unit/v2/test_registry_client.py2
-rw-r--r--glance/tests/utils.py16
17 files changed, 142 insertions, 96 deletions
diff --git a/glance/tests/functional/db/test_sqlalchemy.py b/glance/tests/functional/db/test_sqlalchemy.py
index 57070b2..102bd2e 100644
--- a/glance/tests/functional/db/test_sqlalchemy.py
+++ b/glance/tests/functional/db/test_sqlalchemy.py
@@ -117,8 +117,8 @@ class TestSqlAlchemyDBDataIntegrity(base.TestDriver,
117 return original_method(query, model, limit, 117 return original_method(query, model, limit,
118 sort_keys, marker, sort_dir, sort_dirs) 118 sort_keys, marker, sort_dir, sort_dirs)
119 119
120 self.stubs.Set(self.db_api, '_paginate_query', 120 self.mock_object(self.db_api, '_paginate_query',
121 fake_paginate_query) 121 fake_paginate_query)
122 self.db_api.image_get_all(self.context, sort_key=['created_at']) 122 self.db_api.image_get_all(self.context, sort_key=['created_at'])
123 123
124 def test_paginate_non_redundant_sort_keys(self): 124 def test_paginate_non_redundant_sort_keys(self):
@@ -130,8 +130,8 @@ class TestSqlAlchemyDBDataIntegrity(base.TestDriver,
130 return original_method(query, model, limit, 130 return original_method(query, model, limit,
131 sort_keys, marker, sort_dir, sort_dirs) 131 sort_keys, marker, sort_dir, sort_dirs)
132 132
133 self.stubs.Set(self.db_api, '_paginate_query', 133 self.mock_object(self.db_api, '_paginate_query',
134 fake_paginate_query) 134 fake_paginate_query)
135 self.db_api.image_get_all(self.context, sort_key=['name']) 135 self.db_api.image_get_all(self.context, sort_key=['name'])
136 136
137 137
diff --git a/glance/tests/integration/v2/base.py b/glance/tests/integration/v2/base.py
index f38c4e5..2277102 100644
--- a/glance/tests/integration/v2/base.py
+++ b/glance/tests/integration/v2/base.py
@@ -117,6 +117,7 @@ CONF = cfg.CONF
117 117
118 118
119class ApiTest(test_utils.BaseTestCase): 119class ApiTest(test_utils.BaseTestCase):
120
120 def setUp(self): 121 def setUp(self):
121 super(ApiTest, self).setUp() 122 super(ApiTest, self).setUp()
122 self.test_dir = self.useFixture(fixtures.TempDir()).path 123 self.test_dir = self.useFixture(fixtures.TempDir()).path
@@ -209,8 +210,8 @@ class ApiTest(test_utils.BaseTestCase):
209 return test_utils.HttplibWsgiAdapter(self.glance_registry_app) 210 return test_utils.HttplibWsgiAdapter(self.glance_registry_app)
210 return wrapped 211 return wrapped
211 212
212 self.stubs.Set(glance.common.client.BaseClient, 213 self.mock_object(glance.common.client.BaseClient,
213 'get_connection_type', get_connection_type) 214 'get_connection_type', get_connection_type)
214 215
215 def tearDown(self): 216 def tearDown(self):
216 glance.db.sqlalchemy.api.clear_db_env() 217 glance.db.sqlalchemy.api.clear_db_env()
diff --git a/glance/tests/unit/api/test_cmd.py b/glance/tests/unit/api/test_cmd.py
index ca21f45..788673a 100644
--- a/glance/tests/unit/api/test_cmd.py
+++ b/glance/tests/unit/api/test_cmd.py
@@ -52,19 +52,12 @@ class TestGlanceApiCmd(test_utils.BaseTestCase):
52 52
53 store.register_opts(CONF) 53 store.register_opts(CONF)
54 54
55 self.config_patcher = mock.patch( 55 self.mock_object(glance.common.config, 'load_paste_app',
56 'glance.common.config.load_paste_app', 56 self._do_nothing)
57 side_effect=self._do_nothing) 57 self.mock_object(glance.common.wsgi.Server, 'start',
58 self.start_patcher = mock.patch('glance.common.wsgi.Server.start', 58 self._do_nothing)
59 side_effect=self._do_nothing) 59 self.mock_object(glance.common.wsgi.Server, 'wait',
60 self.wait_patcher = mock.patch('glance.common.wsgi.Server.wait', 60 self._do_nothing)
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()
68 61
69 def tearDown(self): 62 def tearDown(self):
70 sys.stderr = sys.__stderr__ 63 sys.stderr = sys.__stderr__
@@ -77,10 +70,10 @@ class TestGlanceApiCmd(test_utils.BaseTestCase):
77 70
78 def test_worker_creation_failure(self): 71 def test_worker_creation_failure(self):
79 failure = exc.WorkerCreationFailure(reason='test') 72 failure = exc.WorkerCreationFailure(reason='test')
80 with mock.patch('glance.common.wsgi.Server.start', 73 self.mock_object(glance.common.wsgi.Server, 'start',
81 side_effect=self._raise(failure)): 74 self._raise(failure))
82 exit = self.assertRaises(SystemExit, glance.cmd.api.main) 75 exit = self.assertRaises(SystemExit, glance.cmd.api.main)
83 self.assertEqual(2, exit.code) 76 self.assertEqual(2, exit.code)
84 77
85 @mock.patch.object(glance.common.config, 'parse_cache_args') 78 @mock.patch.object(glance.common.config, 'parse_cache_args')
86 @mock.patch.object(logging, 'setup') 79 @mock.patch.object(logging, 'setup')
@@ -103,12 +96,11 @@ class TestGlanceApiCmd(test_utils.BaseTestCase):
103 mock.call.mock_cache_clean()] 96 mock.call.mock_cache_clean()]
104 self.assertEqual(expected_call_sequence, manager.mock_calls) 97 self.assertEqual(expected_call_sequence, manager.mock_calls)
105 98
106 @mock.patch.object(glance.image_cache.cleaner.Cleaner, 'run')
107 @mock.patch.object(glance.image_cache.base.CacheApp, '__init__') 99 @mock.patch.object(glance.image_cache.base.CacheApp, '__init__')
108 def test_cache_cleaner_main_runtime_exception_handling(self, mock_cache, 100 def test_cache_cleaner_main_runtime_exception_handling(self, mock_cache):
109 mock_run):
110 mock_cache.return_value = None 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 exit = self.assertRaises(SystemExit, glance.cmd.cache_cleaner.main) 104 exit = self.assertRaises(SystemExit, glance.cmd.cache_cleaner.main)
113 self.assertEqual('ERROR: ', exit.code) 105 self.assertEqual('ERROR: ', exit.code)
114 106
@@ -133,12 +125,11 @@ class TestGlanceApiCmd(test_utils.BaseTestCase):
133 mock.call.mock_cache_prune()] 125 mock.call.mock_cache_prune()]
134 self.assertEqual(expected_call_sequence, manager.mock_calls) 126 self.assertEqual(expected_call_sequence, manager.mock_calls)
135 127
136 @mock.patch.object(glance.image_cache.pruner.Pruner, 'run')
137 @mock.patch.object(glance.image_cache.base.CacheApp, '__init__') 128 @mock.patch.object(glance.image_cache.base.CacheApp, '__init__')
138 def test_cache_pruner_main_runtime_exception_handling(self, mock_cache, 129 def test_cache_pruner_main_runtime_exception_handling(self, mock_cache):
139 mock_run):
140 mock_cache.return_value = None 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 exit = self.assertRaises(SystemExit, glance.cmd.cache_pruner.main) 133 exit = self.assertRaises(SystemExit, glance.cmd.cache_pruner.main)
143 self.assertEqual('ERROR: ', exit.code) 134 self.assertEqual('ERROR: ', exit.code)
144 135
diff --git a/glance/tests/unit/base.py b/glance/tests/unit/base.py
index 1cd992b..69de6fa 100644
--- a/glance/tests/unit/base.py
+++ b/glance/tests/unit/base.py
@@ -17,6 +17,7 @@ import os
17 17
18import glance_store as store 18import glance_store as store
19from glance_store import location 19from glance_store import location
20import mock
20from oslo_concurrency import lockutils 21from oslo_concurrency import lockutils
21from oslo_config import cfg 22from oslo_config import cfg
22from oslo_db import options 23from oslo_db import options
@@ -134,3 +135,14 @@ class MultiIsolatedUnitTest(MultiStoreClearingUnitTest):
134 fap = open(CONF.oslo_policy.policy_file, 'w') 135 fap = open(CONF.oslo_policy.policy_file, 'w')
135 fap.write(jsonutils.dumps(rules)) 136 fap.write(jsonutils.dumps(rules))
136 fap.close() 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
diff --git a/glance/tests/unit/common/test_config.py b/glance/tests/unit/common/test_config.py
index d91c55f..b3e4d67 100644
--- a/glance/tests/unit/common/test_config.py
+++ b/glance/tests/unit/common/test_config.py
@@ -18,7 +18,6 @@ import shutil
18 18
19import fixtures 19import fixtures
20import oslo_middleware 20import oslo_middleware
21from oslotest import moxstubout
22 21
23from glance.api.middleware import context 22from glance.api.middleware import context
24from glance.common import config 23from glance.common import config
@@ -29,8 +28,6 @@ class TestPasteApp(test_utils.BaseTestCase):
29 28
30 def setUp(self): 29 def setUp(self):
31 super(TestPasteApp, self).setUp() 30 super(TestPasteApp, self).setUp()
32 mox_fixture = self.useFixture(moxstubout.MoxStubout())
33 self.stubs = mox_fixture.stubs
34 31
35 def _do_test_load_paste_app(self, 32 def _do_test_load_paste_app(self,
36 expected_app_type, 33 expected_app_type,
diff --git a/glance/tests/unit/common/test_location_strategy.py b/glance/tests/unit/common/test_location_strategy.py
index bef1a9f..1b47bc6 100644
--- a/glance/tests/unit/common/test_location_strategy.py
+++ b/glance/tests/unit/common/test_location_strategy.py
@@ -48,12 +48,14 @@ class TestLocationStrategy(base.IsolatedUnitTest):
48 modules = ['module1', 'module2'] 48 modules = ['module1', 'module2']
49 49
50 def _fake_stevedore_extension_manager(*args, **kwargs): 50 def _fake_stevedore_extension_manager(*args, **kwargs):
51 ret = lambda: None 51 def ret():
52 return None
52 ret.names = lambda: modules 53 ret.names = lambda: modules
53 return ret 54 return ret
54 55
55 def _fake_stevedore_driver_manager(*args, **kwargs): 56 def _fake_stevedore_driver_manager(*args, **kwargs):
56 ret = lambda: None 57 def ret():
58 return None
57 ret.driver = lambda: None 59 ret.driver = lambda: None
58 ret.driver.__name__ = kwargs['name'] 60 ret.driver.__name__ = kwargs['name']
59 # Module 1 and 2 has a same strategy name 61 # Module 1 and 2 has a same strategy name
@@ -61,10 +63,10 @@ class TestLocationStrategy(base.IsolatedUnitTest):
61 ret.driver.init = lambda: None 63 ret.driver.init = lambda: None
62 return ret 64 return ret
63 65
64 self.stub = self.stubs.Set(stevedore.extension, "ExtensionManager", 66 self.stub = self.mock_object(stevedore.extension, "ExtensionManager",
65 _fake_stevedore_extension_manager) 67 _fake_stevedore_extension_manager)
66 self.stub = self.stubs.Set(stevedore.driver, "DriverManager", 68 self.stub = self.mock_object(stevedore.driver, "DriverManager",
67 _fake_stevedore_driver_manager) 69 _fake_stevedore_driver_manager)
68 70
69 loaded_modules = location_strategy._load_strategies() 71 loaded_modules = location_strategy._load_strategies()
70 self.assertEqual(1, len(loaded_modules)) 72 self.assertEqual(1, len(loaded_modules))
@@ -76,7 +78,8 @@ class TestLocationStrategy(base.IsolatedUnitTest):
76 modules = ['module_init_exception', 'module_good'] 78 modules = ['module_init_exception', 'module_good']
77 79
78 def _fake_stevedore_extension_manager(*args, **kwargs): 80 def _fake_stevedore_extension_manager(*args, **kwargs):
79 ret = lambda: None 81 def ret():
82 return None
80 ret.names = lambda: modules 83 ret.names = lambda: modules
81 return ret 84 return ret
82 85
@@ -84,17 +87,18 @@ class TestLocationStrategy(base.IsolatedUnitTest):
84 if kwargs['name'] == 'module_init_exception': 87 if kwargs['name'] == 'module_init_exception':
85 raise Exception('strategy module failed to initialize.') 88 raise Exception('strategy module failed to initialize.')
86 else: 89 else:
87 ret = lambda: None 90 def ret():
91 return None
88 ret.driver = lambda: None 92 ret.driver = lambda: None
89 ret.driver.__name__ = kwargs['name'] 93 ret.driver.__name__ = kwargs['name']
90 ret.driver.get_strategy_name = lambda: kwargs['name'] 94 ret.driver.get_strategy_name = lambda: kwargs['name']
91 ret.driver.init = lambda: None 95 ret.driver.init = lambda: None
92 return ret 96 return ret
93 97
94 self.stub = self.stubs.Set(stevedore.extension, "ExtensionManager", 98 self.stub = self.mock_object(stevedore.extension, "ExtensionManager",
95 _fake_stevedore_extension_manager) 99 _fake_stevedore_extension_manager)
96 self.stub = self.stubs.Set(stevedore.driver, "DriverManager", 100 self.stub = self.mock_object(stevedore.driver, "DriverManager",
97 _fake_stevedore_driver_manager) 101 _fake_stevedore_driver_manager)
98 102
99 loaded_modules = location_strategy._load_strategies() 103 loaded_modules = location_strategy._load_strategies()
100 self.assertEqual(1, len(loaded_modules)) 104 self.assertEqual(1, len(loaded_modules))
diff --git a/glance/tests/unit/common/test_wsgi.py b/glance/tests/unit/common/test_wsgi.py
index 3b348f1..adda23e 100644
--- a/glance/tests/unit/common/test_wsgi.py
+++ b/glance/tests/unit/common/test_wsgi.py
@@ -49,7 +49,8 @@ class RequestTest(test_utils.BaseTestCase):
49 def returns_some_locales(*args, **kwargs): 49 def returns_some_locales(*args, **kwargs):
50 return all_locales 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 # Override gettext.find to return other than None for some languages. 55 # Override gettext.find to return other than None for some languages.
55 def fake_gettext_find(lang_id, *args, **kwargs): 56 def fake_gettext_find(lang_id, *args, **kwargs):
@@ -62,7 +63,7 @@ class RequestTest(test_utils.BaseTestCase):
62 return found_ret 63 return found_ret
63 return None 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 def test_content_range(self): 68 def test_content_range(self):
68 request = wsgi.Request.blank('/tests/123') 69 request = wsgi.Request.blank('/tests/123')
@@ -338,7 +339,7 @@ class ResourceTest(test_utils.BaseTestCase):
338 if isinstance(obj, wsgi.JSONResponseSerializer): 339 if isinstance(obj, wsgi.JSONResponseSerializer):
339 raise webob.exc.HTTPForbidden() 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 request = wsgi.Request.blank('/') 344 request = wsgi.Request.blank('/')
344 345
@@ -357,7 +358,7 @@ class ResourceTest(test_utils.BaseTestCase):
357 def dispatch(self, obj, action, *args, **kwargs): 358 def dispatch(self, obj, action, *args, **kwargs):
358 raise Exception("test exception") 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 request = wsgi.Request.blank('/') 363 request = wsgi.Request.blank('/')
363 364
diff --git a/glance/tests/unit/test_auth.py b/glance/tests/unit/test_auth.py
index 4807f14..f3600e9 100644
--- a/glance/tests/unit/test_auth.py
+++ b/glance/tests/unit/test_auth.py
@@ -15,7 +15,6 @@
15# under the License. 15# under the License.
16 16
17from oslo_serialization import jsonutils 17from oslo_serialization import jsonutils
18from oslotest import moxstubout
19from six.moves import http_client as http 18from six.moves import http_client as http
20import webob 19import webob
21 20
@@ -123,8 +122,6 @@ class TestKeystoneAuthPlugin(utils.BaseTestCase):
123 122
124 def setUp(self): 123 def setUp(self):
125 super(TestKeystoneAuthPlugin, self).setUp() 124 super(TestKeystoneAuthPlugin, self).setUp()
126 mox_fixture = self.useFixture(moxstubout.MoxStubout())
127 self.stubs = mox_fixture.stubs
128 125
129 def test_get_plugin_from_strategy_keystone(self): 126 def test_get_plugin_from_strategy_keystone(self):
130 strategy = auth.get_plugin_from_strategy('keystone') 127 strategy = auth.get_plugin_from_strategy('keystone')
@@ -200,7 +197,7 @@ class TestKeystoneAuthPlugin(utils.BaseTestCase):
200 resp.status = http.BAD_REQUEST 197 resp.status = http.BAD_REQUEST
201 return FakeResponse(resp), "" 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 bad_creds = { 202 bad_creds = {
206 'username': 'user1', 203 'username': 'user1',
@@ -222,7 +219,7 @@ class TestKeystoneAuthPlugin(utils.BaseTestCase):
222 resp.status = http.BAD_REQUEST 219 resp.status = http.BAD_REQUEST
223 return FakeResponse(resp), "" 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 bad_creds = { 224 bad_creds = {
228 'username': 'user1', 225 'username': 'user1',
@@ -254,7 +251,7 @@ class TestKeystoneAuthPlugin(utils.BaseTestCase):
254 251
255 return FakeResponse(resp), "" 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 unauthorized_creds = [ 256 unauthorized_creds = [
260 { 257 {
@@ -344,7 +341,7 @@ class TestKeystoneAuthPlugin(utils.BaseTestCase):
344 341
345 mock_token = V2Token() 342 mock_token = V2Token()
346 mock_token.add_service('image', ['RegionOne']) 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 unauthorized_creds = [ 346 unauthorized_creds = [
350 { 347 {
diff --git a/glance/tests/unit/test_image_cache.py b/glance/tests/unit/test_image_cache.py
index f77e9ae..8226d60 100644
--- a/glance/tests/unit/test_image_cache.py
+++ b/glance/tests/unit/test_image_cache.py
@@ -23,7 +23,6 @@ import time
23 23
24import fixtures 24import fixtures
25from oslo_utils import units 25from oslo_utils import units
26from oslotest import moxstubout
27import six 26import six
28# NOTE(jokke): simplified transition to py3, behaves like py2 xrange 27# NOTE(jokke): simplified transition to py3, behaves like py2 xrange
29from six.moves import range 28from six.moves import range
@@ -518,9 +517,7 @@ class TestImageCacheNoDep(test_utils.BaseTestCase):
518 def init_driver(self2): 517 def init_driver(self2):
519 self2.driver = self.driver 518 self2.driver = self.driver
520 519
521 mox_fixture = self.useFixture(moxstubout.MoxStubout()) 520 self.mock_object(image_cache.ImageCache, 'init_driver', init_driver)
522 self.stubs = mox_fixture.stubs
523 self.stubs.Set(image_cache.ImageCache, 'init_driver', init_driver)
524 521
525 def test_get_caching_iter_when_write_fails(self): 522 def test_get_caching_iter_when_write_fails(self):
526 523
diff --git a/glance/tests/unit/test_policy.py b/glance/tests/unit/test_policy.py
index b5abca7..03de222 100644
--- a/glance/tests/unit/test_policy.py
+++ b/glance/tests/unit/test_policy.py
@@ -32,12 +32,14 @@ UUID1 = 'c80a1a6c-bd1f-41c5-90ee-81afedb1d58d'
32 32
33 33
34class IterableMock(mock.Mock, collections.Iterable): 34class IterableMock(mock.Mock, collections.Iterable):
35
35 def __iter__(self): 36 def __iter__(self):
36 while False: 37 while False:
37 yield None 38 yield None
38 39
39 40
40class ImageRepoStub(object): 41class ImageRepoStub(object):
42
41 def get(self, *args, **kwargs): 43 def get(self, *args, **kwargs):
42 return 'image_from_get' 44 return 'image_from_get'
43 45
@@ -52,6 +54,7 @@ class ImageRepoStub(object):
52 54
53 55
54class ImageStub(object): 56class ImageStub(object):
57
55 def __init__(self, image_id=None, visibility='private', 58 def __init__(self, image_id=None, visibility='private',
56 container_format='bear', disk_format='raw', 59 container_format='bear', disk_format='raw',
57 status='active', extra_properties=None, 60 status='active', extra_properties=None,
@@ -87,6 +90,7 @@ class ImageStub(object):
87 90
88 91
89class ImageFactoryStub(object): 92class ImageFactoryStub(object):
93
90 def new_image(self, image_id=None, name=None, visibility='private', 94 def new_image(self, image_id=None, name=None, visibility='private',
91 min_disk=0, min_ram=0, protected=False, owner=None, 95 min_disk=0, min_ram=0, protected=False, owner=None,
92 disk_format=None, container_format=None, 96 disk_format=None, container_format=None,
@@ -117,11 +121,13 @@ class MemberRepoStub(object):
117 121
118 122
119class ImageMembershipStub(object): 123class ImageMembershipStub(object):
124
120 def __init__(self, output=None): 125 def __init__(self, output=None):
121 self.output = output 126 self.output = output
122 127
123 128
124class TaskRepoStub(object): 129class TaskRepoStub(object):
130
125 def get(self, *args, **kwargs): 131 def get(self, *args, **kwargs):
126 return 'task_from_get' 132 return 'task_from_get'
127 133
@@ -133,6 +139,7 @@ class TaskRepoStub(object):
133 139
134 140
135class TaskStub(object): 141class TaskStub(object):
142
136 def __init__(self, task_id): 143 def __init__(self, task_id):
137 self.task_id = task_id 144 self.task_id = task_id
138 self.status = 'pending' 145 self.status = 'pending'
@@ -142,11 +149,13 @@ class TaskStub(object):
142 149
143 150
144class TaskFactoryStub(object): 151class TaskFactoryStub(object):
152
145 def new_task(self, *args): 153 def new_task(self, *args):
146 return 'new_task' 154 return 'new_task'
147 155
148 156
149class TestPolicyEnforcer(base.IsolatedUnitTest): 157class TestPolicyEnforcer(base.IsolatedUnitTest):
158
150 def test_policy_file_default_rules_default_location(self): 159 def test_policy_file_default_rules_default_location(self):
151 enforcer = glance.api.policy.Enforcer() 160 enforcer = glance.api.policy.Enforcer()
152 161
@@ -209,6 +218,7 @@ class TestPolicyEnforcer(base.IsolatedUnitTest):
209 218
210 219
211class TestPolicyEnforcerNoFile(base.IsolatedUnitTest): 220class TestPolicyEnforcerNoFile(base.IsolatedUnitTest):
221
212 def test_policy_file_specified_but_not_found(self): 222 def test_policy_file_specified_but_not_found(self):
213 """Missing defined policy file should result in a default ruleset""" 223 """Missing defined policy file should result in a default ruleset"""
214 self.config(policy_file='gobble.gobble', group='oslo_policy') 224 self.config(policy_file='gobble.gobble', group='oslo_policy')
@@ -223,11 +233,12 @@ class TestPolicyEnforcerNoFile(base.IsolatedUnitTest):
223 233
224 def test_policy_file_default_not_found(self): 234 def test_policy_file_default_not_found(self):
225 """Missing default policy file should result in a default ruleset""" 235 """Missing default policy file should result in a default ruleset"""
236
226 def fake_find_file(self, name): 237 def fake_find_file(self, name):
227 return None 238 return None
228 239
229 self.stubs.Set(oslo_config.cfg.ConfigOpts, 'find_file', 240 self.mock_object(oslo_config.cfg.ConfigOpts, 'find_file',
230 fake_find_file) 241 fake_find_file)
231 242
232 enforcer = glance.api.policy.Enforcer() 243 enforcer = glance.api.policy.Enforcer()
233 244
@@ -240,6 +251,7 @@ class TestPolicyEnforcerNoFile(base.IsolatedUnitTest):
240 251
241 252
242class TestImagePolicy(test_utils.BaseTestCase): 253class TestImagePolicy(test_utils.BaseTestCase):
254
243 def setUp(self): 255 def setUp(self):
244 self.image_stub = ImageStub(UUID1) 256 self.image_stub = ImageStub(UUID1)
245 self.image_repo_stub = ImageRepoStub() 257 self.image_repo_stub = ImageRepoStub()
@@ -416,6 +428,7 @@ class TestImagePolicy(test_utils.BaseTestCase):
416 428
417 429
418class TestMemberPolicy(test_utils.BaseTestCase): 430class TestMemberPolicy(test_utils.BaseTestCase):
431
419 def setUp(self): 432 def setUp(self):
420 self.policy = mock.Mock() 433 self.policy = mock.Mock()
421 self.policy.enforce = mock.Mock() 434 self.policy.enforce = mock.Mock()
@@ -491,6 +504,7 @@ class TestMemberPolicy(test_utils.BaseTestCase):
491 504
492 505
493class TestTaskPolicy(test_utils.BaseTestCase): 506class TestTaskPolicy(test_utils.BaseTestCase):
507
494 def setUp(self): 508 def setUp(self):
495 self.task_stub = TaskStub(UUID1) 509 self.task_stub = TaskStub(UUID1)
496 self.task_repo_stub = TaskRepoStub() 510 self.task_repo_stub = TaskRepoStub()
@@ -569,6 +583,7 @@ class TestTaskPolicy(test_utils.BaseTestCase):
569 583
570 584
571class TestContextPolicyEnforcer(base.IsolatedUnitTest): 585class TestContextPolicyEnforcer(base.IsolatedUnitTest):
586
572 def _do_test_policy_influence_context_admin(self, 587 def _do_test_policy_influence_context_admin(self,
573 policy_admin_role, 588 policy_admin_role,
574 context_role, 589 context_role,
diff --git a/glance/tests/unit/test_quota.py b/glance/tests/unit/test_quota.py
index 6419adc..f024de9 100644
--- a/glance/tests/unit/test_quota.py
+++ b/glance/tests/unit/test_quota.py
@@ -52,6 +52,7 @@ class FakeImage(object):
52 52
53 53
54class TestImageQuota(test_utils.BaseTestCase): 54class TestImageQuota(test_utils.BaseTestCase):
55
55 def setUp(self): 56 def setUp(self):
56 super(TestImageQuota, self).setUp() 57 super(TestImageQuota, self).setUp()
57 58
@@ -283,8 +284,8 @@ class TestImageQuota(test_utils.BaseTestCase):
283 image = glance.quota.ImageProxy(base_image, context, db_api, store) 284 image = glance.quota.ImageProxy(base_image, context, db_api, store)
284 self.assertIsNone(image.size) 285 self.assertIsNone(image.size)
285 286
286 self.stubs.Set(store_api, 'get_size_from_backend', 287 self.mock_object(store_api, 'get_size_from_backend',
287 unit_test_utils.fake_get_size_from_backend) 288 unit_test_utils.fake_get_size_from_backend)
288 image.locations.append({'url': 'file:///fake.img.tar.gz', 289 image.locations.append({'url': 'file:///fake.img.tar.gz',
289 'metadata': {}}) 290 'metadata': {}})
290 self.assertIn({'url': 'file:///fake.img.tar.gz', 'metadata': {}}, 291 self.assertIn({'url': 'file:///fake.img.tar.gz', 'metadata': {}},
@@ -300,8 +301,8 @@ class TestImageQuota(test_utils.BaseTestCase):
300 image = glance.quota.ImageProxy(base_image, context, db_api, store) 301 image = glance.quota.ImageProxy(base_image, context, db_api, store)
301 self.assertIsNone(image.size) 302 self.assertIsNone(image.size)
302 303
303 self.stubs.Set(store_api, 'get_size_from_backend', 304 self.mock_object(store_api, 'get_size_from_backend',
304 unit_test_utils.fake_get_size_from_backend) 305 unit_test_utils.fake_get_size_from_backend)
305 image.locations.insert(0, 306 image.locations.insert(0,
306 {'url': 'file:///fake.img.tar.gz', 307 {'url': 'file:///fake.img.tar.gz',
307 'metadata': {}}) 308 'metadata': {}})
@@ -318,8 +319,8 @@ class TestImageQuota(test_utils.BaseTestCase):
318 image = glance.quota.ImageProxy(base_image, context, db_api, store) 319 image = glance.quota.ImageProxy(base_image, context, db_api, store)
319 self.assertIsNone(image.size) 320 self.assertIsNone(image.size)
320 321
321 self.stubs.Set(store_api, 'get_size_from_backend', 322 self.mock_object(store_api, 'get_size_from_backend',
322 unit_test_utils.fake_get_size_from_backend) 323 unit_test_utils.fake_get_size_from_backend)
323 image.locations = [{'url': 'file:///fake.img.tar.gz', 'metadata': {}}] 324 image.locations = [{'url': 'file:///fake.img.tar.gz', 'metadata': {}}]
324 self.assertEqual([{'url': 'file:///fake.img.tar.gz', 'metadata': {}}], 325 self.assertEqual([{'url': 'file:///fake.img.tar.gz', 'metadata': {}}],
325 image.locations) 326 image.locations)
@@ -334,14 +335,15 @@ class TestImageQuota(test_utils.BaseTestCase):
334 image = glance.quota.ImageProxy(base_image, context, db_api, store) 335 image = glance.quota.ImageProxy(base_image, context, db_api, store)
335 self.assertIsNone(image.size) 336 self.assertIsNone(image.size)
336 337
337 self.stubs.Set(store_api, 'get_size_from_backend', 338 self.mock_object(store_api, 'get_size_from_backend',
338 unit_test_utils.fake_get_size_from_backend) 339 unit_test_utils.fake_get_size_from_backend)
339 image.locations += [{'url': 'file:///fake.img.tar.gz', 'metadata': {}}] 340 image.locations += [{'url': 'file:///fake.img.tar.gz', 'metadata': {}}]
340 self.assertIn({'url': 'file:///fake.img.tar.gz', 'metadata': {}}, 341 self.assertIn({'url': 'file:///fake.img.tar.gz', 'metadata': {}},
341 image.locations) 342 image.locations)
342 343
343 344
344class TestImagePropertyQuotas(test_utils.BaseTestCase): 345class TestImagePropertyQuotas(test_utils.BaseTestCase):
346
345 def setUp(self): 347 def setUp(self):
346 super(TestImagePropertyQuotas, self).setUp() 348 super(TestImagePropertyQuotas, self).setUp()
347 self.base_image = FakeImage() 349 self.base_image = FakeImage()
@@ -485,6 +487,7 @@ class TestImagePropertyQuotas(test_utils.BaseTestCase):
485 487
486 488
487class TestImageTagQuotas(test_utils.BaseTestCase): 489class TestImageTagQuotas(test_utils.BaseTestCase):
490
488 def setUp(self): 491 def setUp(self):
489 super(TestImageTagQuotas, self).setUp() 492 super(TestImageTagQuotas, self).setUp()
490 self.base_image = mock.Mock() 493 self.base_image = mock.Mock()
@@ -549,6 +552,7 @@ class TestImageTagQuotas(test_utils.BaseTestCase):
549 552
550 553
551class TestQuotaImageTagsProxy(test_utils.BaseTestCase): 554class TestQuotaImageTagsProxy(test_utils.BaseTestCase):
555
552 def setUp(self): 556 def setUp(self):
553 super(TestQuotaImageTagsProxy, self).setUp() 557 super(TestQuotaImageTagsProxy, self).setUp()
554 558
@@ -594,6 +598,7 @@ class TestQuotaImageTagsProxy(test_utils.BaseTestCase):
594 598
595 599
596class TestImageMemberQuotas(test_utils.BaseTestCase): 600class TestImageMemberQuotas(test_utils.BaseTestCase):
601
597 def setUp(self): 602 def setUp(self):
598 super(TestImageMemberQuotas, self).setUp() 603 super(TestImageMemberQuotas, self).setUp()
599 db_api = unit_test_utils.FakeDB() 604 db_api = unit_test_utils.FakeDB()
@@ -631,6 +636,7 @@ class TestImageMemberQuotas(test_utils.BaseTestCase):
631 636
632 637
633class TestImageLocationQuotas(test_utils.BaseTestCase): 638class TestImageLocationQuotas(test_utils.BaseTestCase):
639
634 def setUp(self): 640 def setUp(self):
635 super(TestImageLocationQuotas, self).setUp() 641 super(TestImageLocationQuotas, self).setUp()
636 self.base_image = mock.Mock() 642 self.base_image = mock.Mock()
diff --git a/glance/tests/unit/test_store_image.py b/glance/tests/unit/test_store_image.py
index cdf5a9c..55d7344 100644
--- a/glance/tests/unit/test_store_image.py
+++ b/glance/tests/unit/test_store_image.py
@@ -128,8 +128,8 @@ class TestStoreImage(utils.BaseTestCase):
128 self.assertEqual(2, len(image1.locations)) 128 self.assertEqual(2, len(image1.locations))
129 self.assertEqual(UUID2, location_data['url']) 129 self.assertEqual(UUID2, location_data['url'])
130 130
131 self.stubs.Set(unit_test_utils.FakeStoreAPI, 'get_from_backend', 131 self.mock_object(unit_test_utils.FakeStoreAPI, 'get_from_backend',
132 fake_get_from_backend) 132 fake_get_from_backend)
133 # This time, image1.get_data() returns the data wrapped in a 133 # This time, image1.get_data() returns the data wrapped in a
134 # LimitingReader|CooperativeReader pipeline, so peeking under 134 # LimitingReader|CooperativeReader pipeline, so peeking under
135 # the hood of those objects to get at the underlying string. 135 # the hood of those objects to get at the underlying string.
@@ -200,8 +200,8 @@ class TestStoreImage(utils.BaseTestCase):
200 } 200 }
201 image_stub = ImageStub(UUID2, status='queued', 201 image_stub = ImageStub(UUID2, status='queued',
202 extra_properties=extra_properties) 202 extra_properties=extra_properties)
203 self.stubs.Set(signature_utils, 'get_verifier', 203 self.mock_object(signature_utils, 'get_verifier',
204 unit_test_utils.fake_get_verifier) 204 unit_test_utils.fake_get_verifier)
205 image = glance.location.ImageProxy(image_stub, context, 205 image = glance.location.ImageProxy(image_stub, context,
206 self.store_api, self.store_utils) 206 self.store_api, self.store_utils)
207 image.set_data('YYYY', 4) 207 image.set_data('YYYY', 4)
@@ -220,8 +220,8 @@ class TestStoreImage(utils.BaseTestCase):
220 } 220 }
221 image_stub = ImageStub(UUID2, status='queued', 221 image_stub = ImageStub(UUID2, status='queued',
222 extra_properties=extra_properties) 222 extra_properties=extra_properties)
223 self.stubs.Set(signature_utils, 'get_verifier', 223 self.mock_object(signature_utils, 'get_verifier',
224 unit_test_utils.fake_get_verifier) 224 unit_test_utils.fake_get_verifier)
225 image = glance.location.ImageProxy(image_stub, context, 225 image = glance.location.ImageProxy(image_stub, context,
226 self.store_api, self.store_utils) 226 self.store_api, self.store_utils)
227 with mock.patch.object(self.store_api, 227 with mock.patch.object(self.store_api,
@@ -240,8 +240,8 @@ class TestStoreImage(utils.BaseTestCase):
240 } 240 }
241 image_stub = ImageStub(UUID2, status='queued', 241 image_stub = ImageStub(UUID2, status='queued',
242 extra_properties=extra_properties) 242 extra_properties=extra_properties)
243 self.stubs.Set(signature_utils, 'get_verifier', 243 self.mock_object(signature_utils, 'get_verifier',
244 unit_test_utils.fake_get_verifier) 244 unit_test_utils.fake_get_verifier)
245 image = glance.location.ImageProxy(image_stub, context, 245 image = glance.location.ImageProxy(image_stub, context,
246 self.store_api, self.store_utils) 246 self.store_api, self.store_utils)
247 image.set_data('YYYY', 4) 247 image.set_data('YYYY', 4)
diff --git a/glance/tests/unit/test_store_location.py b/glance/tests/unit/test_store_location.py
index 1d9dbdd..a3db624 100644
--- a/glance/tests/unit/test_store_location.py
+++ b/glance/tests/unit/test_store_location.py
@@ -43,8 +43,8 @@ class TestStoreLocation(base.StoreClearingUnitTest):
43 def fake_get_size_from_backend(uri, context=None): 43 def fake_get_size_from_backend(uri, context=None):
44 return 1 44 return 1
45 45
46 self.stubs.Set(glance_store, 'get_size_from_backend', 46 self.mock_object(glance_store, 'get_size_from_backend',
47 fake_get_size_from_backend) 47 fake_get_size_from_backend)
48 48
49 with mock.patch('glance.location._check_image_location'): 49 with mock.patch('glance.location._check_image_location'):
50 loc1 = {'url': 'file:///fake1.img.tar.gz', 'metadata': {}} 50 loc1 = {'url': 'file:///fake1.img.tar.gz', 'metadata': {}}
diff --git a/glance/tests/unit/v2/test_image_data_resource.py b/glance/tests/unit/v2/test_image_data_resource.py
index a6e122b..cd76fe5 100644
--- a/glance/tests/unit/v2/test_image_data_resource.py
+++ b/glance/tests/unit/v2/test_image_data_resource.py
@@ -32,6 +32,7 @@ import glance.tests.utils as test_utils
32 32
33 33
34class Raise(object): 34class Raise(object):
35
35 def __init__(self, exc): 36 def __init__(self, exc):
36 self.exc = exc 37 self.exc = exc
37 38
@@ -40,6 +41,7 @@ class Raise(object):
40 41
41 42
42class FakeImage(object): 43class FakeImage(object):
44
43 def __init__(self, image_id=None, data=None, checksum=None, size=0, 45 def __init__(self, image_id=None, data=None, checksum=None, size=0,
44 virtual_size=0, locations=None, container_format='bear', 46 virtual_size=0, locations=None, container_format='bear',
45 disk_format='rawr', status=None): 47 disk_format='rawr', status=None):
@@ -76,6 +78,7 @@ class FakeImage(object):
76 78
77 79
78class FakeImageRepo(object): 80class FakeImageRepo(object):
81
79 def __init__(self, result=None): 82 def __init__(self, result=None):
80 self.result = result 83 self.result = result
81 84
@@ -90,6 +93,7 @@ class FakeImageRepo(object):
90 93
91 94
92class FakeGateway(object): 95class FakeGateway(object):
96
93 def __init__(self, db=None, store=None, notifier=None, 97 def __init__(self, db=None, store=None, notifier=None,
94 policy=None, repo=None): 98 policy=None, repo=None):
95 self.db = db 99 self.db = db
@@ -103,6 +107,7 @@ class FakeGateway(object):
103 107
104 108
105class TestImagesController(base.StoreClearingUnitTest): 109class TestImagesController(base.StoreClearingUnitTest):
110
106 def setUp(self): 111 def setUp(self):
107 super(TestImagesController, self).setUp() 112 super(TestImagesController, self).setUp()
108 113
@@ -157,6 +162,7 @@ class TestImagesController(base.StoreClearingUnitTest):
157 162
158 def test_download_ok_when_get_image_location_forbidden(self): 163 def test_download_ok_when_get_image_location_forbidden(self):
159 class ImageLocations(object): 164 class ImageLocations(object):
165
160 def __len__(self): 166 def __len__(self):
161 raise exception.Forbidden() 167 raise exception.Forbidden()
162 168
@@ -888,9 +894,9 @@ class TestImageDataSerializer(test_utils.BaseTestCase):
888 def get_data(*args, **kwargs): 894 def get_data(*args, **kwargs):
889 raise exception.Forbidden() 895 raise exception.Forbidden()
890 896
891 self.stubs.Set(glance.api.policy.ImageProxy, 897 self.mock_object(glance.api.policy.ImageProxy,
892 'get_data', 898 'get_data',
893 get_data) 899 get_data)
894 request = wsgi.Request.blank('/') 900 request = wsgi.Request.blank('/')
895 request.environ = {} 901 request.environ = {}
896 response = webob.Response() 902 response = webob.Response()
diff --git a/glance/tests/unit/v2/test_images_resource.py b/glance/tests/unit/v2/test_images_resource.py
index 1786be2..83e2caf 100644
--- a/glance/tests/unit/v2/test_images_resource.py
+++ b/glance/tests/unit/v2/test_images_resource.py
@@ -1973,8 +1973,8 @@ class TestImagesController(base.IsolatedUnitTest):
1973 as long as the image has fewer than the limited number of image 1973 as long as the image has fewer than the limited number of image
1974 locations after the transaction. 1974 locations after the transaction.
1975 """ 1975 """
1976 self.stubs.Set(store, 'get_size_from_backend', 1976 self.mock_object(store, 'get_size_from_backend',
1977 unit_test_utils.fake_get_size_from_backend) 1977 unit_test_utils.fake_get_size_from_backend)
1978 self.config(show_multiple_locations=True) 1978 self.config(show_multiple_locations=True)
1979 request = unit_test_utils.get_fake_request() 1979 request = unit_test_utils.get_fake_request()
1980 1980
@@ -2039,8 +2039,8 @@ class TestImagesController(base.IsolatedUnitTest):
2039 2039
2040 def test_update_remove_location(self): 2040 def test_update_remove_location(self):
2041 self.config(show_multiple_locations=True) 2041 self.config(show_multiple_locations=True)
2042 self.stubs.Set(store, 'get_size_from_backend', 2042 self.mock_object(store, 'get_size_from_backend',
2043 unit_test_utils.fake_get_size_from_backend) 2043 unit_test_utils.fake_get_size_from_backend)
2044 2044
2045 request = unit_test_utils.get_fake_request() 2045 request = unit_test_utils.get_fake_request()
2046 new_location = {'url': '%s/fake_location' % BASE_URI, 'metadata': {}} 2046 new_location = {'url': '%s/fake_location' % BASE_URI, 'metadata': {}}
@@ -2080,8 +2080,9 @@ class TestImagesController(base.IsolatedUnitTest):
2080 def fake_delete_image_location_from_backend(self, *args, **kwargs): 2080 def fake_delete_image_location_from_backend(self, *args, **kwargs):
2081 raise Exception('fake_backend_exception') 2081 raise Exception('fake_backend_exception')
2082 2082
2083 self.stubs.Set(self.store_utils, 'delete_image_location_from_backend', 2083 self.mock_object(self.store_utils,
2084 fake_delete_image_location_from_backend) 2084 'delete_image_location_from_backend',
2085 fake_delete_image_location_from_backend)
2085 2086
2086 request = unit_test_utils.get_fake_request() 2087 request = unit_test_utils.get_fake_request()
2087 changes = [ 2088 changes = [
@@ -2288,8 +2289,8 @@ class TestImagesController(base.IsolatedUnitTest):
2288 def test_delete_in_use(self): 2289 def test_delete_in_use(self):
2289 def fake_safe_delete_from_backend(self, *args, **kwargs): 2290 def fake_safe_delete_from_backend(self, *args, **kwargs):
2290 raise store.exceptions.InUseByStore() 2291 raise store.exceptions.InUseByStore()
2291 self.stubs.Set(self.store_utils, 'safe_delete_from_backend', 2292 self.mock_object(self.store_utils, 'safe_delete_from_backend',
2292 fake_safe_delete_from_backend) 2293 fake_safe_delete_from_backend)
2293 request = unit_test_utils.get_fake_request() 2294 request = unit_test_utils.get_fake_request()
2294 self.assertRaises(webob.exc.HTTPConflict, self.controller.delete, 2295 self.assertRaises(webob.exc.HTTPConflict, self.controller.delete,
2295 request, UUID1) 2296 request, UUID1)
@@ -2297,8 +2298,8 @@ class TestImagesController(base.IsolatedUnitTest):
2297 def test_delete_has_snapshot(self): 2298 def test_delete_has_snapshot(self):
2298 def fake_safe_delete_from_backend(self, *args, **kwargs): 2299 def fake_safe_delete_from_backend(self, *args, **kwargs):
2299 raise store.exceptions.HasSnapshot() 2300 raise store.exceptions.HasSnapshot()
2300 self.stubs.Set(self.store_utils, 'safe_delete_from_backend', 2301 self.mock_object(self.store_utils, 'safe_delete_from_backend',
2301 fake_safe_delete_from_backend) 2302 fake_safe_delete_from_backend)
2302 request = unit_test_utils.get_fake_request() 2303 request = unit_test_utils.get_fake_request()
2303 self.assertRaises(webob.exc.HTTPConflict, self.controller.delete, 2304 self.assertRaises(webob.exc.HTTPConflict, self.controller.delete,
2304 request, UUID1) 2305 request, UUID1)
@@ -3584,6 +3585,7 @@ class TestImagesSerializer(test_utils.BaseTestCase):
3584 3585
3585 """ 3586 """
3586 class ImageLocations(object): 3587 class ImageLocations(object):
3588
3587 def __len__(self): 3589 def __len__(self):
3588 raise exception.Forbidden() 3590 raise exception.Forbidden()
3589 3591
@@ -4140,6 +4142,7 @@ class TestImagesSerializerWithAdditionalProperties(test_utils.BaseTestCase):
4140 4142
4141 4143
4142class TestImagesSerializerDirectUrl(test_utils.BaseTestCase): 4144class TestImagesSerializerDirectUrl(test_utils.BaseTestCase):
4145
4143 def setUp(self): 4146 def setUp(self):
4144 super(TestImagesSerializerDirectUrl, self).setUp() 4147 super(TestImagesSerializerDirectUrl, self).setUp()
4145 self.serializer = glance.api.v2.images.ResponseSerializer() 4148 self.serializer = glance.api.v2.images.ResponseSerializer()
@@ -4225,6 +4228,7 @@ class TestImagesSerializerDirectUrl(test_utils.BaseTestCase):
4225 4228
4226 4229
4227class TestImageSchemaFormatConfiguration(test_utils.BaseTestCase): 4230class TestImageSchemaFormatConfiguration(test_utils.BaseTestCase):
4231
4228 def test_default_disk_formats(self): 4232 def test_default_disk_formats(self):
4229 schema = glance.api.v2.images.get_schema() 4233 schema = glance.api.v2.images.get_schema()
4230 expected = [None, 'ami', 'ari', 'aki', 'vhd', 'vhdx', 'vmdk', 4234 expected = [None, 'ami', 'ari', 'aki', 'vhd', 'vhdx', 'vmdk',
@@ -4254,6 +4258,7 @@ class TestImageSchemaFormatConfiguration(test_utils.BaseTestCase):
4254 4258
4255 4259
4256class TestImageSchemaDeterminePropertyBasis(test_utils.BaseTestCase): 4260class TestImageSchemaDeterminePropertyBasis(test_utils.BaseTestCase):
4261
4257 def test_custom_property_marked_as_non_base(self): 4262 def test_custom_property_marked_as_non_base(self):
4258 self.config(allow_additional_image_properties=False) 4263 self.config(allow_additional_image_properties=False)
4259 custom_image_properties = { 4264 custom_image_properties = {
diff --git a/glance/tests/unit/v2/test_registry_client.py b/glance/tests/unit/v2/test_registry_client.py
index 6d5b11b..2401dd5 100644
--- a/glance/tests/unit/v2/test_registry_client.py
+++ b/glance/tests/unit/v2/test_registry_client.py
@@ -759,7 +759,7 @@ class TestRegistryV2ClientApi(base.IsolatedUnitTest):
759 self.config(admin_tenant_name=expected['tenant']) 759 self.config(admin_tenant_name=expected['tenant'])
760 self.config(auth_strategy=expected['strategy']) 760 self.config(auth_strategy=expected['strategy'])
761 self.config(auth_region=expected['region']) 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 self.assertIsNone(rapi._CLIENT_CREDS) 764 self.assertIsNone(rapi._CLIENT_CREDS)
765 rapi.configure_registry_admin_creds() 765 rapi.configure_registry_admin_creds()
diff --git a/glance/tests/utils.py b/glance/tests/utils.py
index 056c449..0b0d143 100644
--- a/glance/tests/utils.py
+++ b/glance/tests/utils.py
@@ -25,6 +25,7 @@ import subprocess
25 25
26from alembic import command as alembic_command 26from alembic import command as alembic_command
27import fixtures 27import fixtures
28import mock
28from oslo_config import cfg 29from oslo_config import cfg
29from oslo_config import fixture as cfg_fixture 30from oslo_config import fixture as cfg_fixture
30from oslo_log.fixture import logging_error as log_fixture 31from oslo_log.fixture import logging_error as log_fixture
@@ -79,7 +80,7 @@ class BaseTestCase(testtools.TestCase):
79 self.addCleanup(CONF.reset) 80 self.addCleanup(CONF.reset)
80 mox_fixture = self.useFixture(moxstubout.MoxStubout()) 81 mox_fixture = self.useFixture(moxstubout.MoxStubout())
81 self.stubs = mox_fixture.stubs 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 self.test_dir = self.useFixture(fixtures.TempDir()).path 84 self.test_dir = self.useFixture(fixtures.TempDir()).path
84 self.conf_dir = os.path.join(self.test_dir, 'etc') 85 self.conf_dir = os.path.join(self.test_dir, 'etc')
85 utils.safe_mkdirs(self.conf_dir) 86 utils.safe_mkdirs(self.conf_dir)
@@ -139,9 +140,21 @@ class BaseTestCase(testtools.TestCase):
139 """ 140 """
140 self._config_fixture.config(**kw) 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
143class requires(object): 155class requires(object):
144 """Decorator that initiates additional test setup/teardown.""" 156 """Decorator that initiates additional test setup/teardown."""
157
145 def __init__(self, setup=None, teardown=None): 158 def __init__(self, setup=None, teardown=None):
146 self.setup = setup 159 self.setup = setup
147 self.teardown = teardown 160 self.teardown = teardown
@@ -160,6 +173,7 @@ class requires(object):
160 173
161class depends_on_exe(object): 174class depends_on_exe(object):
162 """Decorator to skip test if an executable is unavailable""" 175 """Decorator to skip test if an executable is unavailable"""
176
163 def __init__(self, exe): 177 def __init__(self, exe):
164 self.exe = exe 178 self.exe = exe
165 179