Debian Codegraph @

oslo_db/sqlalchemy/test_fixtures.py

raw symbols SCIP
1 # Copyright (c) 2016 OpenStack Foundation
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 import fixtures
17 import os
18 import testresources
19 import testscenarios
20
21 from oslo_db import exception
22 from oslo_db.sqlalchemy import enginefacade
23 from oslo_db.sqlalchemy import provision
24 from oslo_db.sqlalchemy import utils
25
26
27 class ReplaceEngineFacadeFixture(fixtures.Fixture):
28 """A fixture that will plug the engine of one enginefacade into another.
29
30 This fixture can be used by test suites that already have their own non-
31 oslo_db database setup / teardown schemes, to plug any URL or test-oriented
32 enginefacade as-is into an enginefacade-oriented API.
33
34 For applications that use oslo.db's testing fixtures, the
35 ReplaceEngineFacade fixture is used internally.
36
37 E.g.::
38
39 class MyDBTest(TestCase):
40
41 def setUp(self):
42 from myapplication.api import main_enginefacade
43
44 my_test_enginefacade = enginefacade.transaction_context()
45 my_test_enginefacade.configure(connection=my_test_url)
46
47 self.useFixture(
48 ReplaceEngineFacadeFixture(
49 main_enginefacade, my_test_enginefacade))
50
51 Above, the main_enginefacade object is the normal application level
52 one, and my_test_enginefacade is a local one that we've created to
53 refer to some testing database. Throughout the fixture's setup,
54 the application level enginefacade will use the engine factory and
55 engines of the testing enginefacade, and at fixture teardown will be
56 replaced back.
57
58 """
59 def __init__(self, enginefacade, replace_with_enginefacade):
60 super().__init__()
61 self.enginefacade = enginefacade
62 self.replace_with_enginefacade = replace_with_enginefacade
63
64 def _setUp(self):
65 _reset_facade = self.enginefacade.patch_factory(
66 self.replace_with_enginefacade._factory
67 )
68 self.addCleanup(_reset_facade)
69
70
71 class BaseDbFixture(fixtures.Fixture):
72 """Base database provisioning fixture.
73
74 This serves as the base class for the other fixtures, but by itself
75 does not implement _setUp(). It provides the basis for the flags
76 implemented by the various capability mixins (GenerateSchema,
77 DeletesFromSchema, etc.) as well as providing an abstraction over
78 the provisioning objects, which are specific to testresources.
79 Overall, consumers of this fixture just need to use the right classes
80 and the testresources mechanics are taken care of.
81
82 """
83 DRIVER = "sqlite"
84
85 _DROP_SCHEMA_PER_TEST = True
86 _BUILD_SCHEMA = False
87 _BUILD_WITH_MIGRATIONS = False
88
89 _database_resources = {}
90 _db_not_available = {}
91 _schema_resources = {}
92
93 def __init__(self, driver=None, ident=None):
94 super().__init__()
95 self.driver = driver or self.DRIVER
96 self.ident = ident or "default"
97 self.resource_key = (self.driver, self.__class__, self.ident)
98
99 def get_enginefacade(self):
100 """Return an enginefacade._TransactionContextManager.
101
102 This is typically a global variable like "context_manager" declared
103 in the db/api.py module and is the object returned by
104 enginefacade.transaction_context().
105
106 If left not implemented, the global enginefacade manager is used.
107
108 For the case where a project uses per-object or per-test enginefacades
109 like Gnocchi, the get_per_test_enginefacade()
110 method should also be implemented.
111
112
113 """
114 return enginefacade._context_manager
115
116 def get_per_test_enginefacade(self):
117 """Return an enginefacade._TransactionContextManager per test.
118
119 This facade should be the one that the test expects the code to
120 use. Usually this is the same one returned by get_engineafacade()
121 which is the default. For special applications like Gnocchi,
122 this can be overridden to provide an instance-level facade.
123
124 """
125 return self.get_enginefacade()
126
127 def _get_db_resource_not_available_reason(self):
128 return self._db_not_available.get(self.resource_key, None)
129
130 def _has_db_resource(self):
131 return self._database_resources.get(
132 self.resource_key, None) is not None
133
134 def _generate_schema_resource(self, database_resource):
135 return provision.SchemaResource(
136 database_resource,
137 None if not self._BUILD_SCHEMA
138 else self.generate_schema_create_all
139 if not self._BUILD_WITH_MIGRATIONS
140 else self.generate_schema_migrations,
141 self._DROP_SCHEMA_PER_TEST
142 )
143
144 def _get_resources(self):
145 key = self.resource_key
146
147 # the DatabaseResource and SchemaResource provision objects
148 # can be used by testresources as a marker outside of an individual
149 # test to indicate that this database / schema can be used across
150 # multiple tests. To make this work, many instances of this
151 # fixture have to return the *same* resource object given the same
152 # inputs. so we cache these in class-level dictionaries.
153
154 if key not in self._database_resources:
155 _enginefacade = self.get_enginefacade()
156 try:
157 self._database_resources[key] = \
158 self._generate_database_resource(_enginefacade)
159 except exception.BackendNotAvailable as bne:
160 self._database_resources[key] = None
161 self._db_not_available[key] = str(bne)
162
163 database_resource = self._database_resources[key]
164
165 if database_resource is None:
166 return []
167 else:
168 if key in self._schema_resources:
169 schema_resource = self._schema_resources[key]
170 else:
171 schema_resource = self._schema_resources[key] = \
172 self._generate_schema_resource(database_resource)
173
174 return [
175 ('_schema_%s' % self.ident, schema_resource),
176 ('_db_%s' % self.ident, database_resource)
177 ]
178
179
180 class GeneratesSchema:
181 """Mixin defining a fixture as generating a schema using create_all().
182
183 This is a "capability" mixin that works in conjunction with classes
184 that include BaseDbFixture as a base.
185
186 """
187
188 _BUILD_SCHEMA = True
189 _BUILD_WITH_MIGRATIONS = False
190
191 def generate_schema_create_all(self, engine):
192 """A hook which should generate the model schema using create_all().
193
194 This hook is called within the scope of creating the database
195 assuming BUILD_WITH_MIGRATIONS is False.
196
197 """
198
199
200 class GeneratesSchemaFromMigrations(GeneratesSchema):
201 """Mixin defining a fixture as generating a schema using migrations.
202
203 This is a "capability" mixin that works in conjunction with classes
204 that include BaseDbFixture as a base.
205
206 """
207
208 _BUILD_WITH_MIGRATIONS = True
209
210 def generate_schema_migrations(self, engine):
211 """A hook which should generate the model schema using migrations.
212
213
214 This hook is called within the scope of creating the database
215 assuming BUILD_WITH_MIGRATIONS is True.
216
217 """
218
219
220 class ResetsData:
221 """Mixin defining a fixture that resets schema data without dropping."""
222
223 _DROP_SCHEMA_PER_TEST = False
224
225 def setup_for_reset(self, engine, enginefacade):
226 """"Perform setup that may be needed before the test runs."""
227
228 def reset_schema_data(self, engine, enginefacade):
229 """Reset the data in the schema."""
230
231
232 class DeletesFromSchema(ResetsData):
233 """Mixin defining a fixture that can delete from all tables in place.
234
235 When DeletesFromSchema is present in a fixture,
236 _DROP_SCHEMA_PER_TEST is now False; this means that the
237 "teardown" flag of provision.SchemaResource will be False, which
238 prevents SchemaResource from dropping all objects within the schema
239 after each test.
240
241 This is a "capability" mixin that works in conjunction with classes
242 that include BaseDbFixture as a base.
243
244 """
245
246 def reset_schema_data(self, engine, facade):
247 self.delete_from_schema(engine)
248
249 def delete_from_schema(self, engine):
250 """A hook which should delete all data from an existing schema.
251
252 Should *not* drop any objects, just remove data from tables
253 that needs to be reset between tests.
254 """
255
256
257 class SimpleDbFixture(BaseDbFixture):
258 """Fixture which provides an engine from a fixed URL.
259
260 The SimpleDbFixture is generally appropriate only for a SQLite memory
261 database, as this database is naturally isolated from other processes and
262 does not require management of schemas. For tests that need to
263 run specifically against MySQL or Postgresql, the OpportunisticDbFixture
264 is more appropriate.
265
266 The database connection information itself comes from the provisoning
267 system, matching the desired driver (typically sqlite) to the default URL
268 that provisioning provides for this driver (in the case of sqlite, it's
269 the SQLite memory URL, e.g. sqlite://. For MySQL and Postgresql, it's
270 the familiar "openstack_citest" URL on localhost).
271
272 There are a variety of create/drop schemes that can take place:
273
274 * The default is to procure a database connection on setup,
275 and at teardown, an instruction is issued to "drop" all
276 objects in the schema (e.g. tables, indexes). The SQLAlchemy
277 engine itself remains referenced at the class level for subsequent
278 re-use.
279
280 * When the GeneratesSchema or GeneratesSchemaFromMigrations mixins
281 are implemented, the appropriate generate_schema method is also
282 called when the fixture is set up, by default this is per test.
283
284 * When the DeletesFromSchema mixin is implemented, the generate_schema
285 method is now only called **once**, and the "drop all objects"
286 system is replaced with the delete_from_schema method. This
287 allows the same database to remain set up with all schema objects
288 intact, so that expensive migrations need not be run on every test.
289
290 * The fixture does **not** dispose the engine at the end of a test.
291 It is assumed the same engine will be re-used many times across
292 many tests. The AdHocDbFixture extends this one to provide
293 engine.dispose() at the end of a test.
294
295 This fixture is intended to work without needing a reference to
296 the test itself, and therefore cannot take advantage of the
297 OptimisingTestSuite.
298
299 """
300
301 _dependency_resources = {}
302
303 def _get_provisioned_db(self):
304 return self._dependency_resources["_db_%s" % self.ident]
305
306 def _generate_database_resource(self, _enginefacade):
307 return provision.DatabaseResource(self.driver, _enginefacade,
308 provision_new_database=False)
309
310 def _setUp(self):
311 super()._setUp()
312
313 cls = self.__class__
314
315 if "_db_%s" % self.ident not in cls._dependency_resources:
316
317 resources = self._get_resources()
318
319 # initialize resources the same way that testresources does.
320 for name, resource in resources:
321 cls._dependency_resources[name] = resource.getResource()
322
323 provisioned_db = self._get_provisioned_db()
324
325 if not self._DROP_SCHEMA_PER_TEST:
326 self.setup_for_reset(
327 provisioned_db.engine, provisioned_db.enginefacade)
328
329 self.useFixture(ReplaceEngineFacadeFixture(
330 self.get_per_test_enginefacade(),
331 provisioned_db.enginefacade
332 ))
333
334 if not self._DROP_SCHEMA_PER_TEST:
335 self.addCleanup(
336 self.reset_schema_data,
337 provisioned_db.engine, provisioned_db.enginefacade)
338
339 self.addCleanup(self._cleanup)
340
341 def _teardown_resources(self):
342 for name, resource in self._get_resources():
343 dep = self._dependency_resources.pop(name)
344 resource.finishedWith(dep)
345
346 def _cleanup(self):
347 pass
348
349
350 class AdHocDbFixture(SimpleDbFixture):
351 """"Fixture which creates and disposes a database engine per test.
352
353 Also allows a specific URL to be passed, meaning the fixture can
354 be hardcoded to a specific SQLite file.
355
356 For a SQLite, this fixture will create the named database upon setup
357 and tear it down upon teardown. For other databases, the
358 database is assumed to exist already and will remain after teardown.
359
360 """
361 def __init__(self, url=None):
362 if url:
363 self.url = utils.make_url(url)
364 driver = self.url.get_backend_name()
365 else:
366 driver = None
367 self.url = None
368
369 BaseDbFixture.__init__(
370 self, driver=driver,
371 ident=provision._random_ident())
372 self.url = url
373
374 def _generate_database_resource(self, _enginefacade):
375 return provision.DatabaseResource(
376 self.driver, _enginefacade, ad_hoc_url=self.url,
377 provision_new_database=False)
378
379 def _cleanup(self):
380 self._teardown_resources()
381
382
383 class OpportunisticDbFixture(BaseDbFixture):
384 """Fixture which uses testresources fully for optimised runs.
385
386 This fixture relies upon the use of the OpportunisticDBTestMixin to supply
387 a test.resources attribute, and also works much more effectively when
388 combined the testresources.OptimisingTestSuite. The
389 optimize_package_test_loader() function should be
390 used at the module and package levels to optimize database
391 provisioning across many tests.
392
393 """
394 def __init__(self, test, driver=None, ident=None):
395 super().__init__(
396 driver=driver, ident=ident)
397 self.test = test
398
399 def _get_provisioned_db(self):
400 return getattr(self.test, "_db_%s" % self.ident)
401
402 def _generate_database_resource(self, _enginefacade):
403 return provision.DatabaseResource(
404 self.driver, _enginefacade, provision_new_database=True)
405
406 def _setUp(self):
407 super()._setUp()
408
409 if not self._has_db_resource():
410 return
411
412 provisioned_db = self._get_provisioned_db()
413
414 if not self._DROP_SCHEMA_PER_TEST:
415 self.setup_for_reset(
416 provisioned_db.engine, provisioned_db.enginefacade)
417
418 self.useFixture(ReplaceEngineFacadeFixture(
419 self.get_per_test_enginefacade(),
420 provisioned_db.enginefacade
421 ))
422
423 if not self._DROP_SCHEMA_PER_TEST:
424 self.addCleanup(
425 self.reset_schema_data,
426 provisioned_db.engine, provisioned_db.enginefacade)
427
428
429 class OpportunisticDBTestMixin:
430 """Test mixin that integrates the test suite with testresources.
431
432 There are three goals to this system:
433
434 1. Allow creation of "stub" test suites that will run all the tests in a
435 parent suite against a specific kind of database (e.g. Mysql,
436 Postgresql), where the entire suite will be skipped if that target
437 kind of database is not available to the suite.
438
439 2. provide a test with a process-local, anonymously named schema within a
440 target database, so that the test can run concurrently with other tests
441 without conflicting data
442
443 3. provide compatibility with the testresources.OptimisingTestSuite, which
444 organizes TestCase instances ahead of time into groups that all
445 make use of the same type of database, setting up and tearing down
446 a database schema once for the scope of any number of tests within.
447 This technique is essential when testing against a non-SQLite database
448 because building of a schema is expensive, and also is most ideally
449 accomplished using the applications schema migration which are
450 even more vastly slow than a straight create_all().
451
452 This mixin provides the .resources attribute required by testresources when
453 using the OptimisingTestSuite.The .resources attribute then provides a
454 collection of testresources.TestResourceManager objects, which are defined
455 here in oslo_db.sqlalchemy.provision. These objects know how to find
456 available database backends, build up temporary databases, and invoke
457 schema generation and teardown instructions. The actual "build the schema
458 objects" part of the equation, and optionally a "delete from all the
459 tables" step, is provided by the implementing application itself.
460
461
462 """
463 SKIP_ON_UNAVAILABLE_DB = True
464
465 FIXTURE = OpportunisticDbFixture
466
467 _collected_resources = None
468 _instantiated_fixtures = None
469
470 @property
471 def resources(self):
472 """Provide a collection of TestResourceManager objects.
473
474 The collection here is memoized, both at the level of the test
475 case itself, as well as in the fixture object(s) which provide
476 those resources.
477
478 """
479
480 if self._collected_resources is not None:
481 return self._collected_resources
482
483 fixtures = self._instantiate_fixtures()
484 self._collected_resources = []
485 for fixture in fixtures:
486 self._collected_resources.extend(fixture._get_resources())
487 return self._collected_resources
488
489 def setUp(self):
490 self._setup_fixtures()
491 super().setUp()
492
493 def _get_default_provisioned_db(self):
494 return self._db_default
495
496 def _instantiate_fixtures(self):
497 if self._instantiated_fixtures:
498 return self._instantiated_fixtures
499
500 self._instantiated_fixtures = utils.to_list(self.generate_fixtures())
501 return self._instantiated_fixtures
502
503 def generate_fixtures(self):
504 return self.FIXTURE(test=self)
505
506 def _setup_fixtures(self):
507 testresources.setUpResources(
508 self, self.resources, testresources._get_result())
509 self.addCleanup(
510 testresources.tearDownResources,
511 self, self.resources, testresources._get_result()
512 )
513
514 fixtures = self._instantiate_fixtures()
515 for fixture in fixtures:
516 self.useFixture(fixture)
517
518 if not fixture._has_db_resource():
519 msg = fixture._get_db_resource_not_available_reason()
520 if self.SKIP_ON_UNAVAILABLE_DB:
521 self.skipTest(msg)
522 else:
523 self.fail(msg)
524
525
526 class MySQLOpportunisticFixture(OpportunisticDbFixture):
527 DRIVER = 'mysql'
528
529
530 class PostgresqlOpportunisticFixture(OpportunisticDbFixture):
531 DRIVER = 'postgresql'
532
533
534 def optimize_package_test_loader(file_):
535 """Organize package-level tests into a testresources.OptimizingTestSuite.
536
537 This function provides a unittest-compatible load_tests hook
538 for a given package; for per-module, use the
539 :func:`.optimize_module_test_loader` function.
540
541 When a unitest or subunit style
542 test runner is used, the function will be called in order to
543 return a TestSuite containing the tests to run; this function
544 ensures that this suite is an OptimisingTestSuite, which will organize
545 the production of test resources across groups of tests at once.
546
547 The function is invoked as::
548
549 from oslo_db.sqlalchemy import test_fixtures
550
551 load_tests = test_fixtures.optimize_package_test_loader(__file__)
552
553 The loader *must* be present in the package level __init__.py.
554
555 The function also applies testscenarios expansion to all test collections.
556 This so that an existing test suite that already needs to build
557 TestScenarios from a load_tests call can still have this take place when
558 replaced with this function.
559
560 """
561
562 this_dir = os.path.dirname(file_)
563
564 def load_tests(loader, found_tests, pattern):
565 result = testresources.OptimisingTestSuite()
566 result.addTests(found_tests)
567 pkg_tests = loader.discover(start_dir=this_dir, pattern=pattern)
568 result.addTests(testscenarios.generate_scenarios(pkg_tests))
569
570 return result
571 return load_tests
572
573
574 def optimize_module_test_loader():
575 """Organize module-level tests into a testresources.OptimizingTestSuite.
576
577 This function provides a unittest-compatible load_tests hook
578 for a given module; for per-package, use the
579 :func:`.optimize_package_test_loader` function.
580
581 When a unitest or subunit style
582 test runner is used, the function will be called in order to
583 return a TestSuite containing the tests to run; this function
584 ensures that this suite is an OptimisingTestSuite, which will organize
585 the production of test resources across groups of tests at once.
586
587 The function is invoked as::
588
589 from oslo_db.sqlalchemy import test_fixtures
590
591 load_tests = test_fixtures.optimize_module_test_loader()
592
593 The loader *must* be present in an individual module, and *not* the
594 package level __init__.py.
595
596 The function also applies testscenarios expansion to all test collections.
597 This so that an existing test suite that already needs to build
598 TestScenarios from a load_tests call can still have this take place when
599 replaced with this function.
600
601 """
602
603 def load_tests(loader, found_tests, pattern):
604 result = testresources.OptimisingTestSuite()
605 result.addTests(testscenarios.generate_scenarios(found_tests))
606 return result
607 return load_tests