Debian Codegraph @

neutron_lib/fixture.py

raw
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 import copy
14 from unittest import mock
15 import warnings
16
17 import fixtures
18 from oslo_config import cfg
19 from oslo_db.sqlalchemy import enginefacade
20 from oslo_db.sqlalchemy import provision
21 from oslo_db.sqlalchemy import session
22 from oslo_messaging import conffixture
23
24 from neutron_lib.api import attributes
25 from neutron_lib.api import definitions
26 from neutron_lib.callbacks import manager
27 from neutron_lib.callbacks import registry
28 from neutron_lib.db import api as db_api
29 from neutron_lib.db import model_base
30 from neutron_lib.db import model_query
31 from neutron_lib.db import resource_extend
32 from neutron_lib.plugins import directory
33 from neutron_lib import rpc
34 from neutron_lib.tests.unit import fake_notifier
35
36
37 CONF = cfg.CONF
38
39
40 class PluginDirectoryFixture(fixtures.Fixture):
41
42 def __init__(self, plugin_directory=None):
43 super().__init__()
44 self.plugin_directory = (
45 plugin_directory or directory._PluginDirectory())
46
47 def _setUp(self):
48 self._orig_directory = directory._PLUGIN_DIRECTORY
49 directory._PLUGIN_DIRECTORY = self.plugin_directory
50 self.addCleanup(self._restore)
51
52 def _restore(self):
53 directory._PLUGIN_DIRECTORY = self._orig_directory
54
55
56 class CallbackRegistryFixture(fixtures.Fixture):
57 """Callback registry fixture.
58
59 This class is intended to be used as a fixture within unit tests and
60 therefore consumers must register it using useFixture() within their
61 unit test class. The implementation optionally allows consumers to pass
62 in the CallbacksManager manager to use for your tests.
63 """
64
65 def __init__(self, callback_manager=None):
66 """Creates a new RegistryFixture.
67
68 :param callback_manager: If specified, the return value to use for
69 _get_callback_manager(). Otherwise a new instance of CallbacksManager
70 is used.
71 """
72 super().__init__()
73 self.callback_manager = callback_manager or manager.CallbacksManager()
74 self.patcher = None
75
76 def _setUp(self):
77 self._orig_manager = registry._get_callback_manager()
78 self.patcher = mock.patch.object(
79 registry, '_get_callback_manager',
80 return_value=self.callback_manager)
81 self.patcher.start()
82 self.addCleanup(self._restore)
83
84 def _restore(self):
85 registry._CALLBACK_MANAGER = self._orig_manager
86 self.patcher.stop()
87
88
89 class _EnableSQLiteFKsFixture(fixtures.Fixture):
90 """Turn SQLite PRAGMA foreign keys on and off for tests.
91
92 FIXME(zzzeek): figure out some way to get oslo.db test_base to honor
93 oslo_db.engines.create_engine() arguments like sqlite_fks as well
94 as handling that it needs to be turned off during drops.
95
96 """
97
98 def __init__(self, engine):
99 self.engine = engine
100
101 def _setUp(self):
102 if self.engine.name == 'sqlite':
103 with self.engine.connect() as conn:
104 cursor = conn.connection.cursor()
105 cursor.execute('PRAGMA foreign_keys=ON')
106 cursor.close()
107
108
109 class SqlFixture(fixtures.Fixture):
110
111 @classmethod
112 def _generate_schema(cls, engine):
113 model_base.BASEV2.metadata.create_all(engine)
114
115 def _delete_from_schema(self, engine):
116 with engine.begin() as conn:
117 for table in reversed(
118 model_base.BASEV2.metadata.sorted_tables):
119 conn.execute(table.delete())
120
121 def _init_resources(self):
122 pass
123
124 def _setUp(self):
125 self._init_resources()
126
127 # check if the fixtures failed to get
128 # an engine. The test setUp() itself should also be checking
129 # this and raising skipTest.
130 if not hasattr(self, 'engine'):
131 return
132
133 engine = self.engine
134 self.addCleanup(lambda: self._delete_from_schema(engine))
135
136 self.sessionmaker = session.get_maker(engine)
137
138 _restore_factory = db_api.get_context_manager()._root_factory
139
140 self.enginefacade_factory = enginefacade._TestTransactionFactory(
141 self.engine, self.sessionmaker, from_factory=_restore_factory,
142 apply_global=False)
143
144 db_api.get_context_manager()._root_factory = self.enginefacade_factory
145
146 engine = db_api.CONTEXT_WRITER.get_engine()
147
148 self.addCleanup(
149 lambda: setattr(
150 db_api.get_context_manager(),
151 "_root_factory", _restore_factory))
152
153 self.useFixture(_EnableSQLiteFKsFixture(engine))
154
155
156 class StaticSqlFixture(SqlFixture):
157
158 _GLOBAL_RESOURCES = False
159
160 @classmethod
161 def _init_resources(cls):
162 # this is a classlevel version of what testresources
163 # does w/ the resources attribute as well as the
164 # setUpResources() step (which requires a test instance, that
165 # SqlFixture does not have). Because this is a SQLite memory
166 # database, we don't actually tear it down, so we can keep
167 # it running throughout all tests.
168 if cls._GLOBAL_RESOURCES:
169 return
170 else:
171 cls._GLOBAL_RESOURCES = True
172 cls.schema_resource = provision.SchemaResource(
173 provision.DatabaseResource(
174 "sqlite", db_api.get_context_manager()),
175 cls._generate_schema, teardown=False)
176 dependency_resources = {}
177 for name, resource in cls.schema_resource.resources:
178 dependency_resources[name] = resource.getResource()
179 cls.schema_resource.make(dependency_resources)
180 cls.engine = dependency_resources['database'].engine
181
182
183 class APIDefinitionFixture(fixtures.Fixture):
184 """Test fixture for testing neutron-lib API definitions.
185
186 Extension API definition RESOURCE_ATTRIBUTE_MAP dicts get updated as
187 part of standard extension processing/handling. While this behavior is
188 fine for service runtime, it can impact testing scenarios whereby test1
189 updates the attribute map (globally) and test2 doesn't expect the
190 test1 updates.
191
192 This fixture saves and restores 1 or more neutron-lib API definitions
193 attribute maps. It should be used anywhere multiple tests can be run
194 that might update an extension attribute map.
195
196 In addition the fixture backs up and restores the global attribute
197 RESOURCES base on the boolean value of its backup_global_resources
198 attribute.
199 """
200
201 def __init__(self, *api_definitions):
202 """Create a new instance.
203
204 Consumers can also control if the fixture should handle the global
205 attribute RESOURCE map using the backup_global_resources of the
206 fixture instance. If True the fixture will also handle
207 neutron_lib.api.attributes.RESOURCES.
208
209 :param api_definitions: Zero or more API definitions the fixture
210 should handle. If no api_definitions are passed, the default is
211 to handle all neutron_lib API definitions as well as the global
212 RESOURCES attribute map.
213 """
214 self.definitions = api_definitions or definitions._ALL_API_DEFINITIONS
215 self._orig_attr_maps = {}
216 self._orig_resources = {}
217 self.backup_global_resources = True
218
219 def _setUp(self):
220 for api_def in self.definitions:
221 self._orig_attr_maps[api_def.ALIAS] = (
222 api_def, {k: copy.deepcopy(v)
223 for k, v in api_def.RESOURCE_ATTRIBUTE_MAP.items()})
224 if self.backup_global_resources:
225 for resource, attrs in attributes.RESOURCES.items():
226 self._orig_resources[resource] = copy.deepcopy(attrs)
227 self.addCleanup(self._restore)
228
229 def _restore(self):
230 # clear + repopulate so consumer refs don't change
231 for alias, def_and_map in self._orig_attr_maps.items():
232 api_def, attr_map = def_and_map[0], def_and_map[1]
233 api_def.RESOURCE_ATTRIBUTE_MAP.clear()
234 api_def.RESOURCE_ATTRIBUTE_MAP.update(attr_map)
235 if self.backup_global_resources:
236 attributes.RESOURCES.clear()
237 attributes.RESOURCES.update(self._orig_resources)
238
239 @classmethod
240 def all_api_definitions_fixture(cls):
241 """Return a fixture that handles all neutron-lib api-defs."""
242 return APIDefinitionFixture(*tuple(definitions._ALL_API_DEFINITIONS))
243
244
245 class PlacementAPIClientFixture(fixtures.Fixture):
246 """Placement API client fixture.
247
248 This class is intended to be used as a fixture within unit tests and
249 therefore consumers must register it using useFixture() within their
250 unit test class.
251 """
252
253 def __init__(self, placement_api_client):
254 """Creates a new PlacementAPIClientFixture.
255
256 :param placement_api_client: Placement API client object.
257 """
258 super().__init__()
259 self.placement_api_client = placement_api_client
260
261 def _setUp(self):
262 self.addCleanup(self._restore)
263
264 def mock_create_client():
265 self.placement_api_client.client = mock.Mock()
266
267 self._mock_create_client = mock.patch.object(
268 self.placement_api_client, '_create_client',
269 side_effect=mock_create_client)
270 self._mock_get = mock.patch.object(self.placement_api_client, '_get')
271 self._mock_post = mock.patch.object(self.placement_api_client, '_post')
272 self._mock_put = mock.patch.object(self.placement_api_client, '_put')
273 self._mock_delete = mock.patch.object(self.placement_api_client,
274 '_delete')
275 self._mock_create_client.start()
276 self.mock_get = self._mock_get.start()
277 self.mock_post = self._mock_post.start()
278 self.mock_put = self._mock_put.start()
279 self.mock_delete = self._mock_delete.start()
280
281 def _restore(self):
282 self._mock_create_client.stop()
283 self._mock_get.stop()
284 self._mock_post.stop()
285 self._mock_put.stop()
286 self._mock_delete.stop()
287
288
289 class DBRetryErrorsFixture(fixtures.Fixture):
290
291 def __init__(self, **retry_kwargs):
292 self._retry_kwargs = retry_kwargs
293 self._patchers = []
294
295 def _setUp(self):
296 for k, v in self._retry_kwargs.items():
297 patcher = mock.patch.object(db_api._retry_db_errors, k, new=v)
298 patcher.start()
299 self._patchers.append(patcher)
300 self.addCleanup(self._restore)
301
302 def _restore(self):
303 for p in self._patchers:
304 p.stop()
305
306
307 class DBAPIContextManagerFixture(fixtures.Fixture):
308
309 def __init__(self, mock_context_manager=mock.ANY):
310 self.cxt_manager = (mock.Mock() if mock_context_manager == mock.ANY
311 else mock_context_manager)
312 self._backup_mgr = None
313
314 def _setUp(self):
315 self._backup_mgr = db_api._CTX_MANAGER
316 db_api._CTX_MANAGER = self.cxt_manager
317 self.addCleanup(self._restore)
318
319 def _restore(self):
320 db_api._CTX_MANAGER = self._backup_mgr
321
322
323 class DBQueryHooksFixture(fixtures.Fixture):
324
325 def _setUp(self, query_hooks=None):
326 self._backup = model_query._model_query_hooks
327 model_query._model_query_hooks = query_hooks or {}
328 self.addCleanup(self._restore)
329
330 def _restore(self):
331 model_query._model_query_hooks = self._backup
332
333
334 class RPCFixture(fixtures.Fixture):
335
336 def _setUp(self):
337 # don't actually start RPC listeners when testing
338 mock.patch.object(rpc.Connection, 'consume_in_threads',
339 return_value=[]).start()
340 self.useFixture(fixtures.MonkeyPatch(
341 'oslo_messaging.Notifier', fake_notifier.FakeNotifier))
342
343 self.messaging_conf = conffixture.ConfFixture(CONF)
344 self.messaging_conf.transport_url = 'fake:/'
345 # NOTE(russellb) We want all calls to return immediately.
346 self.messaging_conf.response_timeout = 0
347 self.useFixture(self.messaging_conf)
348
349 self.addCleanup(rpc.cleanup)
350 rpc.init(CONF)
351
352
353 class DBResourceExtendFixture(fixtures.Fixture):
354
355 def __init__(self, extended_functions=None):
356 self.extended_functions = extended_functions or {}
357
358 def _setUp(self):
359 self._backup = copy.deepcopy(
360 resource_extend._resource_extend_functions)
361 resource_extend._resource_extend_functions = self.extended_functions
362 self.addCleanup(self._restore)
363
364 def _restore(self):
365 resource_extend._resource_extend_functions = self._backup
366
367
368 class OpenFixture(fixtures.Fixture):
369 """Mock access to a specific file while preserving open for others."""
370
371 def __init__(self, filepath, contents=''):
372 self.path = filepath
373 self.contents = contents
374
375 def _setUp(self):
376 self.mock_open = mock.mock_open(read_data=self.contents)
377 self._orig_open = open
378
379 def replacement_open(name, *args, **kwargs):
380 method = self.mock_open if name == self.path else self._orig_open
381 return method(name, *args, **kwargs)
382
383 self._patch = mock.patch('builtins.open', new=replacement_open)
384 self._patch.start()
385 self.addCleanup(self._patch.stop)
386
387
388 class WarningsFixture(fixtures.Fixture):
389 """Filters out warnings during test runs."""
390
391 warning_types = (
392 DeprecationWarning, PendingDeprecationWarning, ImportWarning
393 )
394
395 def __init__(self, module_re=None):
396 """Create a new WarningsFixture.
397
398 :param module_re: A list of regular expression strings that will be
399 used with filterwarnings. Multiple expressions are or'd together.
400 """
401 self._modules = ['^neutron_lib\\.']
402 if module_re:
403 self._modules.extend(module_re)
404
405 def _setUp(self):
406 self.addCleanup(warnings.resetwarnings)
407 for wtype in self.warning_types:
408 warnings.filterwarnings(
409 "once", category=wtype, module='|'.join(self._modules))