diff --git a/plum/service_collection.py b/plum/service_collection.py new file mode 100644 index 000000000..b73511a92 --- /dev/null +++ b/plum/service_collection.py @@ -0,0 +1,37 @@ +from .service import Service + +def sort_service_dicts(services): + # Sort in dependency order + def cmp(x, y): + x_deps_y = y['name'] in x.get('links', []) + y_deps_x = x['name'] in y.get('links', []) + if x_deps_y and not y_deps_x: + return 1 + elif y_deps_x and not x_deps_y: + return -1 + return 0 + return sorted(services, cmp=cmp) + +class ServiceCollection(list): + @classmethod + def from_dicts(cls, client, service_dicts): + """ + Construct a ServiceCollection from a list of dicts representing services. + """ + collection = ServiceCollection() + for service_dict in sort_service_dicts(service_dicts): + # Reference links by object + links = [] + if 'links' in service_dict: + for name in service_dict.get('links', []): + links.append(collection.get(name)) + del service_dict['links'] + collection.append(Service(client=client, links=links, **service_dict)) + return collection + + def get(self, name): + for service in self: + if service.name == name: + return service + + diff --git a/plum/tests/service_collection_test.py b/plum/tests/service_collection_test.py new file mode 100644 index 000000000..88641c0a9 --- /dev/null +++ b/plum/tests/service_collection_test.py @@ -0,0 +1,44 @@ +from plum.service import Service +from plum.service_collection import ServiceCollection +from unittest import TestCase + + +class ServiceCollectionTest(TestCase): + def test_from_dict(self): + collection = ServiceCollection.from_dicts(None, [ + { + 'name': 'web', + 'image': 'ubuntu' + }, + { + 'name': 'db', + 'image': 'ubuntu' + } + ]) + self.assertEqual(len(collection), 2) + web = [s for s in collection if s.name == 'web'][0] + self.assertEqual(web.name, 'web') + self.assertEqual(web.image, 'ubuntu') + db = [s for s in collection if s.name == 'db'][0] + self.assertEqual(db.name, 'db') + self.assertEqual(db.image, 'ubuntu') + + def test_from_dict_sorts_in_dependency_order(self): + collection = ServiceCollection.from_dicts(None, [ + { + 'name': 'web', + 'image': 'ubuntu', + 'links': ['db'], + }, + { + 'name': 'db', + 'image': 'ubuntu' + } + ]) + + self.assertEqual(collection[0].name, 'db') + self.assertEqual(collection[1].name, 'web') + + + +