Add function to marshal resource associations

It will be useful e.g. for setting/updating links from Racks to
Resource Classes, from Nodes to Racks or other similar associations.

Change-Id: I7a525cc525940ee2ae72269004b5d8d1b27f123b
This commit is contained in:
Jiri Stransky 2013-10-08 17:04:31 +02:00
parent e3eb26281f
commit 0da5ad4ab9
2 changed files with 43 additions and 0 deletions

View File

@ -84,6 +84,26 @@ def find_resource(manager, name_or_id):
raise exc.CommandError(msg)
def marshal_association(args, resource_dict, assoc_name):
"""Marshal resource association into an API request dict.
Distinguish between 3 cases:
- when the value in args is present, set the value in dict too,
- when the value in args is an empty string, set the value in dict
to none,
- when the value in args is None, it means the user did not specify
it on the command line and it should not be present in the dict
(important for update).
"""
assoc_value = getattr(args, assoc_name, None)
if assoc_value == '':
resource_dict[assoc_name] = None
elif assoc_value:
# TODO(jistr): support for selecting resources by name
resource_dict[assoc_name] = {'id': assoc_value}
def string_to_bool(arg):
return arg.strip().lower() in ('t', 'true', 'yes', '1')

View File

@ -46,3 +46,26 @@ class DefineCommandsTest(test_utils.TestCase):
dummy.do_dummy_list = do_dummy_list
dummy.other_method = mock.Mock('other_method', return_value=43)
return dummy
class MarshalAssociationTest(test_utils.TestCase):
def setUp(self):
super(MarshalAssociationTest, self).setUp()
self.args = mock.Mock(spec=['rack'])
self.dict = {}
def test_with_id(self):
self.args.rack = '10'
utils.marshal_association(self.args, self.dict, 'rack')
self.assertEqual(self.dict['rack']['id'], '10')
def test_with_empty_association(self):
self.args.rack = ''
utils.marshal_association(self.args, self.dict, 'rack')
self.assertEqual(self.dict['rack'], None)
def test_when_unset(self):
self.args.rack = None
utils.marshal_association(self.args, self.dict, 'rack')
self.assertFalse('rack' in self.dict)