Files
galaxy/test/unit/managers/base.py
T
John Chilton 11c1715fc3 Holistic approach to dependency injection.
Dependency injection is cool - it should however not be confined to the top-layer of the application. Inversion of control can help every layer and is a great way to de-couple various parts of the app.

This code brings in a framework (Lagom) to build a dependency injection framework and then adds a small function (``depends``) that adapts it to FastAPI's dependency injection mechanism ("Depends").

The advantages to this approach are numerous.

We don't need to write these little adapters for each component of the backend to adapt it FastAPI. For example look at the change to the roles API controller:

```diff
-def get_role_manager(app: UniverseApplication = Depends(get_app)) -> RoleManager:
-    return app.role_manager
-
-
 @cbv(router)
 class FastAPIRoles:
-    role_manager: RoleManager = Depends(get_role_manager)
+    role_manager: RoleManager = depends(RoleManager)
```

This is much less boilerplate. We don't need to implement & type that function get_role_manager and we don't need to bring in the import on UniverseApplication.

Additionally, we've got a clean abstraction that shields us from ``fastapi`` imports in all of our controllers. It should make it more possible to switch to new frameworks and such as the Python ecosystem matures.

Also, the same DI that is used to inject ``RoleManager`` into this contoller is used to inject app into RoleManager when it is constructed during application initialization. Any component being managed by UniverseApplication can now rely on its constructor arguments to be injected if it wants. It is easy to see the cool examples on FastAPI and think it is just a technology for controllers, but it totally is not.

I don't think there is really a way to use FastAPI's dependency injection outside the context of that framework, but even if one could Lagom is superior. All the auto-wiring is by type and requires zero framework and zero configuration (https://github.com/meadsteve/lagom#auto-wiring-with-zero-configuraton).

Having a web framework provide these framework-bound extension points for injecting stuff into controllers was the state of the art of Java like 15 years ago. Skipping that whole learning process and using the type system and auto-wiring that isn't dependent on framework annotation really jumps out to Java circa 8 years ago!

Why Lagom is an interesting question. When researching DI frameworks, I couldn't find a clear winner but Lagom focus on type annotations versus annotating by name makes it clearly more modern than a lot frameworks by much bigger names (https://github.com/meadsteve/lagom/blob/master/docs/comparison.md). The other type-centric framework that had even a nice interface that I found was punq (https://punq.readthedocs.io/en/latest/). The development just doesn't seem as active on punq. While I didn't land up using the integration Lagom seems to have async frameworks in mind (https://github.com/meadsteve/lagom/blob/master/lagom/integrations/fast_api.py), so that is another plus. Ultimately though I think I can swap between these two with like 10 lines of code switch, they do cool things with very simple interfaces and neither requires a bunch of investment in annotation on your components.
2021-02-23 10:28:46 -05:00

144 lines
4.8 KiB
Python

"""
"""
import json
import unittest
import sqlalchemy
from galaxy.managers.users import UserManager
from ..unittest_utils import galaxy_mock
# =============================================================================
admin_email = 'admin@admin.admin'
admin_users = admin_email
default_password = '123456'
# =============================================================================
class BaseTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
print('\n', '-' * 20, 'begin class', cls)
@classmethod
def tearDownClass(cls):
print('\n', '-' * 20, 'end class', cls)
def __init__(self, *args):
unittest.TestCase.__init__(self, *args)
def setUp(self):
self.log('.' * 20, 'begin test', self)
self.set_up_mocks()
self.set_up_managers()
self.set_up_trans()
def set_up_mocks(self):
admin_users_list = [u for u in admin_users.split(',') if u]
self.trans = galaxy_mock.MockTrans(admin_users=admin_users, admin_users_list=admin_users_list)
self.app = self.trans.app
def mock_is_admin_user(user):
return user.email in admin_users
self.trans.app.config.is_admin_user = mock_is_admin_user
def set_up_managers(self):
self.user_manager = self.app[UserManager]
def set_up_trans(self):
self.admin_user = self.user_manager.create(email=admin_email, username='admin', password=default_password)
self.trans.set_user(self.admin_user)
self.trans.set_history(None)
def tearDown(self):
self.log('.' * 20, 'end test', self, '\n')
def log(self, *args, **kwargs):
print(*args, **kwargs)
# ---- additional test types
TYPES_NEEDING_NO_SERIALIZERS = (str, bool, type(None), int, float)
def assertKeys(self, obj, key_list):
self.assertEqual(sorted(obj.keys()), sorted(key_list))
def assertHasKeys(self, obj, key_list):
for key in key_list:
if key not in obj:
self.fail('Missing key: ' + key)
else:
self.assertTrue(True, 'keys found in object')
def assertNullableBasestring(self, item):
if not isinstance(item, (str, type(None))):
self.fail('Non-nullable basestring: ' + str(type(item)))
# TODO: len mod 8 and hex re
self.assertTrue(True, 'is nullable basestring: ' + str(item))
def assertEncodedId(self, item):
if not isinstance(item, str):
self.fail('Non-string: ' + str(type(item)))
# TODO: len mod 8 and hex re
self.assertTrue(True, 'is id: ' + item)
def assertNullableEncodedId(self, item):
if item is None:
self.assertTrue(True, 'nullable id is None')
else:
self.assertEncodedId(item)
def assertDate(self, item):
if not isinstance(item, str):
self.fail('Non-string: ' + str(type(item)))
# TODO: no great way to parse this fully (w/o python-dateutil)
# TODO: re?
self.assertTrue(True, 'is date: ' + item)
def assertUUID(self, item):
if not isinstance(item, str):
self.fail('Non-string: ' + str(type(item)))
# TODO: re for d4d76d69-80d4-4ed7-80c7-211ebcc1a358
self.assertTrue(True, 'is uuid: ' + item)
def assertORMFilter(self, item, msg=None):
if not isinstance(item.filter, (sqlalchemy.sql.elements.BinaryExpression, sqlalchemy.sql.elements.BooleanClauseList)):
self.fail('Not an orm filter: ' + str(type(item.filter)))
self.assertTrue(True, msg or ('is an orm filter: ' + str(item.filter)))
def assertORMFunctionFilter(self, item, msg=None):
assert item.filter_type == 'orm_function'
assert callable(item.filter)
def assertFnFilter(self, item, msg=None):
if not item.filter or not callable(item.filter):
self.fail('Not a fn filter: ' + str(type(item.filter)))
self.assertTrue(True, msg or ('is a fn filter: ' + str(item.filter)))
def assertIsJsonifyable(self, item):
# TODO: use galaxy's override
self.assertIsInstance(json.dumps(item), str)
class CreatesCollectionsMixin:
def build_element_identifiers(self, elements):
identifier_list = []
for element in elements:
src = 'hda'
# if isinstance( element, model.DatasetCollection ):
# src = 'collection'#?
# elif isinstance( element, model.LibraryDatasetDatasetAssociation ):
# src = 'ldda'#?
encoded_id = self.trans.security.encode_id(element.id)
identifier_list.append(dict(src=src, name=element.name, id=encoded_id))
return identifier_list
# =============================================================================
if __name__ == '__main__':
# or more generally, nosetests test_resourcemanagers.py -s -v
unittest.main()