Add ServiceCollection

This commit is contained in:
Ben Firshman 2013-12-09 14:10:23 +00:00
parent 973760a501
commit bc51134ceb
2 changed files with 81 additions and 0 deletions

View File

@ -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

View File

@ -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')