Commit 9b554083 by Simon János

flatten method for resource groups (and resources)

parent 0b005a39
Pipeline #283 passed with stage
in 45 seconds
...@@ -93,6 +93,10 @@ class Resource(object): ...@@ -93,6 +93,10 @@ class Resource(object):
def __add__(self, other): def __add__(self, other):
return ResourceGroup(resources=[self, other]) return ResourceGroup(resources=[self, other])
def flatten(self, fqn=None):
fqn = '%s.%s' % (fqn, self.id) if fqn else self.id
return {'%s.%s' % (fqn, key): str(value) for key, value in self.items()}
@staticmethod @staticmethod
def json_encoder(data): def json_encoder(data):
if isinstance(data, ResourceType): if isinstance(data, ResourceType):
...@@ -130,6 +134,12 @@ class ResourceGroup(Resource): ...@@ -130,6 +134,12 @@ class ResourceGroup(Resource):
def resources(self): def resources(self):
return list(self.__resources.values()) return list(self.__resources.values())
def flatten(self, fqn=None):
flat = dict()
for resource in self.resources:
flat.update(resource.flatten('%s.%s' % (fqn, self.id) if fqn else self.id))
return flat
class Instance(Resource): class Instance(Resource):
ADDITIONAL_SCHEMA = { ADDITIONAL_SCHEMA = {
......
...@@ -249,3 +249,42 @@ class ResourceGroupTest(TestCase): ...@@ -249,3 +249,42 @@ class ResourceGroupTest(TestCase):
ResourceGroup(id='some_other_group')) ResourceGroup(id='some_other_group'))
self.assertNotEqual(ResourceGroup(id='some_group', resources=[resource1]), self.assertNotEqual(ResourceGroup(id='some_group', resources=[resource1]),
ResourceGroup(id='some_group', resources=[resource2])) ResourceGroup(id='some_group', resources=[resource2]))
def test_resource_group_flatten(self):
tree_dict = {
'id': 'root',
'type': 'group',
'resources': [
{
'id': 'instance-1',
'type': 'instance'
},
{
'id': 'level-1',
'type': 'group',
'resources': [
{
'id': 'instance-2',
'type': 'instance'
},
{
'id': 'instance-3',
'type': 'instance'
}
]
}
]
}
expected_flat_dict = {
'root.instance-1.id': 'instance-1',
'root.instance-1.type': 'instance',
'root.level-1.instance-2.id': 'instance-2',
'root.level-1.instance-2.type': 'instance',
'root.level-1.instance-3.id': 'instance-3',
'root.level-1.instance-3.type': 'instance'
}
tree_resource = Resource(tree_dict)
flat_dict = tree_resource.flatten()
self.assertEqual(expected_flat_dict, flat_dict)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment